xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/TargetInstrInfo.cpp (revision 9e5787d2284e187abb5b654d924394a65772e004)
1 //===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/TargetInstrInfo.h"
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineMemOperand.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/MachineScheduler.h"
20 #include "llvm/CodeGen/PseudoSourceValue.h"
21 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
22 #include "llvm/CodeGen/StackMaps.h"
23 #include "llvm/CodeGen/TargetFrameLowering.h"
24 #include "llvm/CodeGen/TargetLowering.h"
25 #include "llvm/CodeGen/TargetRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSchedule.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCInstrItineraries.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include <cctype>
36 
37 using namespace llvm;
38 
39 static cl::opt<bool> DisableHazardRecognizer(
40   "disable-sched-hazard", cl::Hidden, cl::init(false),
41   cl::desc("Disable hazard detection during preRA scheduling"));
42 
43 TargetInstrInfo::~TargetInstrInfo() {
44 }
45 
46 const TargetRegisterClass*
47 TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
48                              const TargetRegisterInfo *TRI,
49                              const MachineFunction &MF) const {
50   if (OpNum >= MCID.getNumOperands())
51     return nullptr;
52 
53   short RegClass = MCID.OpInfo[OpNum].RegClass;
54   if (MCID.OpInfo[OpNum].isLookupPtrRegClass())
55     return TRI->getPointerRegClass(MF, RegClass);
56 
57   // Instructions like INSERT_SUBREG do not have fixed register classes.
58   if (RegClass < 0)
59     return nullptr;
60 
61   // Otherwise just look it up normally.
62   return TRI->getRegClass(RegClass);
63 }
64 
65 /// insertNoop - Insert a noop into the instruction stream at the specified
66 /// point.
67 void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
68                                  MachineBasicBlock::iterator MI) const {
69   llvm_unreachable("Target didn't implement insertNoop!");
70 }
71 
72 static bool isAsmComment(const char *Str, const MCAsmInfo &MAI) {
73   return strncmp(Str, MAI.getCommentString().data(),
74                  MAI.getCommentString().size()) == 0;
75 }
76 
77 /// Measure the specified inline asm to determine an approximation of its
78 /// length.
79 /// Comments (which run till the next SeparatorString or newline) do not
80 /// count as an instruction.
81 /// Any other non-whitespace text is considered an instruction, with
82 /// multiple instructions separated by SeparatorString or newlines.
83 /// Variable-length instructions are not handled here; this function
84 /// may be overloaded in the target code to do that.
85 /// We implement a special case of the .space directive which takes only a
86 /// single integer argument in base 10 that is the size in bytes. This is a
87 /// restricted form of the GAS directive in that we only interpret
88 /// simple--i.e. not a logical or arithmetic expression--size values without
89 /// the optional fill value. This is primarily used for creating arbitrary
90 /// sized inline asm blocks for testing purposes.
91 unsigned TargetInstrInfo::getInlineAsmLength(
92   const char *Str,
93   const MCAsmInfo &MAI, const TargetSubtargetInfo *STI) const {
94   // Count the number of instructions in the asm.
95   bool AtInsnStart = true;
96   unsigned Length = 0;
97   const unsigned MaxInstLength = MAI.getMaxInstLength(STI);
98   for (; *Str; ++Str) {
99     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
100                                 strlen(MAI.getSeparatorString())) == 0) {
101       AtInsnStart = true;
102     } else if (isAsmComment(Str, MAI)) {
103       // Stop counting as an instruction after a comment until the next
104       // separator.
105       AtInsnStart = false;
106     }
107 
108     if (AtInsnStart && !isSpace(static_cast<unsigned char>(*Str))) {
109       unsigned AddLength = MaxInstLength;
110       if (strncmp(Str, ".space", 6) == 0) {
111         char *EStr;
112         int SpaceSize;
113         SpaceSize = strtol(Str + 6, &EStr, 10);
114         SpaceSize = SpaceSize < 0 ? 0 : SpaceSize;
115         while (*EStr != '\n' && isSpace(static_cast<unsigned char>(*EStr)))
116           ++EStr;
117         if (*EStr == '\0' || *EStr == '\n' ||
118             isAsmComment(EStr, MAI)) // Successfully parsed .space argument
119           AddLength = SpaceSize;
120       }
121       Length += AddLength;
122       AtInsnStart = false;
123     }
124   }
125 
126   return Length;
127 }
128 
129 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
130 /// after it, replacing it with an unconditional branch to NewDest.
131 void
132 TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
133                                          MachineBasicBlock *NewDest) const {
134   MachineBasicBlock *MBB = Tail->getParent();
135 
136   // Remove all the old successors of MBB from the CFG.
137   while (!MBB->succ_empty())
138     MBB->removeSuccessor(MBB->succ_begin());
139 
140   // Save off the debug loc before erasing the instruction.
141   DebugLoc DL = Tail->getDebugLoc();
142 
143   // Update call site info and remove all the dead instructions
144   // from the end of MBB.
145   while (Tail != MBB->end()) {
146     auto MI = Tail++;
147     if (MI->shouldUpdateCallSiteInfo())
148       MBB->getParent()->eraseCallSiteInfo(&*MI);
149     MBB->erase(MI);
150   }
151 
152   // If MBB isn't immediately before MBB, insert a branch to it.
153   if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
154     insertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(), DL);
155   MBB->addSuccessor(NewDest);
156 }
157 
158 MachineInstr *TargetInstrInfo::commuteInstructionImpl(MachineInstr &MI,
159                                                       bool NewMI, unsigned Idx1,
160                                                       unsigned Idx2) const {
161   const MCInstrDesc &MCID = MI.getDesc();
162   bool HasDef = MCID.getNumDefs();
163   if (HasDef && !MI.getOperand(0).isReg())
164     // No idea how to commute this instruction. Target should implement its own.
165     return nullptr;
166 
167   unsigned CommutableOpIdx1 = Idx1; (void)CommutableOpIdx1;
168   unsigned CommutableOpIdx2 = Idx2; (void)CommutableOpIdx2;
169   assert(findCommutedOpIndices(MI, CommutableOpIdx1, CommutableOpIdx2) &&
170          CommutableOpIdx1 == Idx1 && CommutableOpIdx2 == Idx2 &&
171          "TargetInstrInfo::CommuteInstructionImpl(): not commutable operands.");
172   assert(MI.getOperand(Idx1).isReg() && MI.getOperand(Idx2).isReg() &&
173          "This only knows how to commute register operands so far");
174 
175   Register Reg0 = HasDef ? MI.getOperand(0).getReg() : Register();
176   Register Reg1 = MI.getOperand(Idx1).getReg();
177   Register Reg2 = MI.getOperand(Idx2).getReg();
178   unsigned SubReg0 = HasDef ? MI.getOperand(0).getSubReg() : 0;
179   unsigned SubReg1 = MI.getOperand(Idx1).getSubReg();
180   unsigned SubReg2 = MI.getOperand(Idx2).getSubReg();
181   bool Reg1IsKill = MI.getOperand(Idx1).isKill();
182   bool Reg2IsKill = MI.getOperand(Idx2).isKill();
183   bool Reg1IsUndef = MI.getOperand(Idx1).isUndef();
184   bool Reg2IsUndef = MI.getOperand(Idx2).isUndef();
185   bool Reg1IsInternal = MI.getOperand(Idx1).isInternalRead();
186   bool Reg2IsInternal = MI.getOperand(Idx2).isInternalRead();
187   // Avoid calling isRenamable for virtual registers since we assert that
188   // renamable property is only queried/set for physical registers.
189   bool Reg1IsRenamable = Register::isPhysicalRegister(Reg1)
190                              ? MI.getOperand(Idx1).isRenamable()
191                              : false;
192   bool Reg2IsRenamable = Register::isPhysicalRegister(Reg2)
193                              ? MI.getOperand(Idx2).isRenamable()
194                              : false;
195   // If destination is tied to either of the commuted source register, then
196   // it must be updated.
197   if (HasDef && Reg0 == Reg1 &&
198       MI.getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
199     Reg2IsKill = false;
200     Reg0 = Reg2;
201     SubReg0 = SubReg2;
202   } else if (HasDef && Reg0 == Reg2 &&
203              MI.getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
204     Reg1IsKill = false;
205     Reg0 = Reg1;
206     SubReg0 = SubReg1;
207   }
208 
209   MachineInstr *CommutedMI = nullptr;
210   if (NewMI) {
211     // Create a new instruction.
212     MachineFunction &MF = *MI.getMF();
213     CommutedMI = MF.CloneMachineInstr(&MI);
214   } else {
215     CommutedMI = &MI;
216   }
217 
218   if (HasDef) {
219     CommutedMI->getOperand(0).setReg(Reg0);
220     CommutedMI->getOperand(0).setSubReg(SubReg0);
221   }
222   CommutedMI->getOperand(Idx2).setReg(Reg1);
223   CommutedMI->getOperand(Idx1).setReg(Reg2);
224   CommutedMI->getOperand(Idx2).setSubReg(SubReg1);
225   CommutedMI->getOperand(Idx1).setSubReg(SubReg2);
226   CommutedMI->getOperand(Idx2).setIsKill(Reg1IsKill);
227   CommutedMI->getOperand(Idx1).setIsKill(Reg2IsKill);
228   CommutedMI->getOperand(Idx2).setIsUndef(Reg1IsUndef);
229   CommutedMI->getOperand(Idx1).setIsUndef(Reg2IsUndef);
230   CommutedMI->getOperand(Idx2).setIsInternalRead(Reg1IsInternal);
231   CommutedMI->getOperand(Idx1).setIsInternalRead(Reg2IsInternal);
232   // Avoid calling setIsRenamable for virtual registers since we assert that
233   // renamable property is only queried/set for physical registers.
234   if (Register::isPhysicalRegister(Reg1))
235     CommutedMI->getOperand(Idx2).setIsRenamable(Reg1IsRenamable);
236   if (Register::isPhysicalRegister(Reg2))
237     CommutedMI->getOperand(Idx1).setIsRenamable(Reg2IsRenamable);
238   return CommutedMI;
239 }
240 
241 MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr &MI, bool NewMI,
242                                                   unsigned OpIdx1,
243                                                   unsigned OpIdx2) const {
244   // If OpIdx1 or OpIdx2 is not specified, then this method is free to choose
245   // any commutable operand, which is done in findCommutedOpIndices() method
246   // called below.
247   if ((OpIdx1 == CommuteAnyOperandIndex || OpIdx2 == CommuteAnyOperandIndex) &&
248       !findCommutedOpIndices(MI, OpIdx1, OpIdx2)) {
249     assert(MI.isCommutable() &&
250            "Precondition violation: MI must be commutable.");
251     return nullptr;
252   }
253   return commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
254 }
255 
256 bool TargetInstrInfo::fixCommutedOpIndices(unsigned &ResultIdx1,
257                                            unsigned &ResultIdx2,
258                                            unsigned CommutableOpIdx1,
259                                            unsigned CommutableOpIdx2) {
260   if (ResultIdx1 == CommuteAnyOperandIndex &&
261       ResultIdx2 == CommuteAnyOperandIndex) {
262     ResultIdx1 = CommutableOpIdx1;
263     ResultIdx2 = CommutableOpIdx2;
264   } else if (ResultIdx1 == CommuteAnyOperandIndex) {
265     if (ResultIdx2 == CommutableOpIdx1)
266       ResultIdx1 = CommutableOpIdx2;
267     else if (ResultIdx2 == CommutableOpIdx2)
268       ResultIdx1 = CommutableOpIdx1;
269     else
270       return false;
271   } else if (ResultIdx2 == CommuteAnyOperandIndex) {
272     if (ResultIdx1 == CommutableOpIdx1)
273       ResultIdx2 = CommutableOpIdx2;
274     else if (ResultIdx1 == CommutableOpIdx2)
275       ResultIdx2 = CommutableOpIdx1;
276     else
277       return false;
278   } else
279     // Check that the result operand indices match the given commutable
280     // operand indices.
281     return (ResultIdx1 == CommutableOpIdx1 && ResultIdx2 == CommutableOpIdx2) ||
282            (ResultIdx1 == CommutableOpIdx2 && ResultIdx2 == CommutableOpIdx1);
283 
284   return true;
285 }
286 
287 bool TargetInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
288                                             unsigned &SrcOpIdx1,
289                                             unsigned &SrcOpIdx2) const {
290   assert(!MI.isBundle() &&
291          "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
292 
293   const MCInstrDesc &MCID = MI.getDesc();
294   if (!MCID.isCommutable())
295     return false;
296 
297   // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
298   // is not true, then the target must implement this.
299   unsigned CommutableOpIdx1 = MCID.getNumDefs();
300   unsigned CommutableOpIdx2 = CommutableOpIdx1 + 1;
301   if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
302                             CommutableOpIdx1, CommutableOpIdx2))
303     return false;
304 
305   if (!MI.getOperand(SrcOpIdx1).isReg() || !MI.getOperand(SrcOpIdx2).isReg())
306     // No idea.
307     return false;
308   return true;
309 }
310 
311 bool TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
312   if (!MI.isTerminator()) return false;
313 
314   // Conditional branch is a special case.
315   if (MI.isBranch() && !MI.isBarrier())
316     return true;
317   if (!MI.isPredicable())
318     return true;
319   return !isPredicated(MI);
320 }
321 
322 bool TargetInstrInfo::PredicateInstruction(
323     MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
324   bool MadeChange = false;
325 
326   assert(!MI.isBundle() &&
327          "TargetInstrInfo::PredicateInstruction() can't handle bundles");
328 
329   const MCInstrDesc &MCID = MI.getDesc();
330   if (!MI.isPredicable())
331     return false;
332 
333   for (unsigned j = 0, i = 0, e = MI.getNumOperands(); i != e; ++i) {
334     if (MCID.OpInfo[i].isPredicate()) {
335       MachineOperand &MO = MI.getOperand(i);
336       if (MO.isReg()) {
337         MO.setReg(Pred[j].getReg());
338         MadeChange = true;
339       } else if (MO.isImm()) {
340         MO.setImm(Pred[j].getImm());
341         MadeChange = true;
342       } else if (MO.isMBB()) {
343         MO.setMBB(Pred[j].getMBB());
344         MadeChange = true;
345       }
346       ++j;
347     }
348   }
349   return MadeChange;
350 }
351 
352 bool TargetInstrInfo::hasLoadFromStackSlot(
353     const MachineInstr &MI,
354     SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
355   size_t StartSize = Accesses.size();
356   for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
357                                   oe = MI.memoperands_end();
358        o != oe; ++o) {
359     if ((*o)->isLoad() &&
360         dyn_cast_or_null<FixedStackPseudoSourceValue>((*o)->getPseudoValue()))
361       Accesses.push_back(*o);
362   }
363   return Accesses.size() != StartSize;
364 }
365 
366 bool TargetInstrInfo::hasStoreToStackSlot(
367     const MachineInstr &MI,
368     SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
369   size_t StartSize = Accesses.size();
370   for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
371                                   oe = MI.memoperands_end();
372        o != oe; ++o) {
373     if ((*o)->isStore() &&
374         dyn_cast_or_null<FixedStackPseudoSourceValue>((*o)->getPseudoValue()))
375       Accesses.push_back(*o);
376   }
377   return Accesses.size() != StartSize;
378 }
379 
380 bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
381                                         unsigned SubIdx, unsigned &Size,
382                                         unsigned &Offset,
383                                         const MachineFunction &MF) const {
384   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
385   if (!SubIdx) {
386     Size = TRI->getSpillSize(*RC);
387     Offset = 0;
388     return true;
389   }
390   unsigned BitSize = TRI->getSubRegIdxSize(SubIdx);
391   // Convert bit size to byte size.
392   if (BitSize % 8)
393     return false;
394 
395   int BitOffset = TRI->getSubRegIdxOffset(SubIdx);
396   if (BitOffset < 0 || BitOffset % 8)
397     return false;
398 
399   Size = BitSize / 8;
400   Offset = (unsigned)BitOffset / 8;
401 
402   assert(TRI->getSpillSize(*RC) >= (Offset + Size) && "bad subregister range");
403 
404   if (!MF.getDataLayout().isLittleEndian()) {
405     Offset = TRI->getSpillSize(*RC) - (Offset + Size);
406   }
407   return true;
408 }
409 
410 void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
411                                     MachineBasicBlock::iterator I,
412                                     Register DestReg, unsigned SubIdx,
413                                     const MachineInstr &Orig,
414                                     const TargetRegisterInfo &TRI) const {
415   MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
416   MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
417   MBB.insert(I, MI);
418 }
419 
420 bool TargetInstrInfo::produceSameValue(const MachineInstr &MI0,
421                                        const MachineInstr &MI1,
422                                        const MachineRegisterInfo *MRI) const {
423   return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
424 }
425 
426 MachineInstr &TargetInstrInfo::duplicate(MachineBasicBlock &MBB,
427     MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) const {
428   assert(!Orig.isNotDuplicable() && "Instruction cannot be duplicated");
429   MachineFunction &MF = *MBB.getParent();
430   return MF.CloneMachineInstrBundle(MBB, InsertBefore, Orig);
431 }
432 
433 // If the COPY instruction in MI can be folded to a stack operation, return
434 // the register class to use.
435 static const TargetRegisterClass *canFoldCopy(const MachineInstr &MI,
436                                               unsigned FoldIdx) {
437   assert(MI.isCopy() && "MI must be a COPY instruction");
438   if (MI.getNumOperands() != 2)
439     return nullptr;
440   assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
441 
442   const MachineOperand &FoldOp = MI.getOperand(FoldIdx);
443   const MachineOperand &LiveOp = MI.getOperand(1 - FoldIdx);
444 
445   if (FoldOp.getSubReg() || LiveOp.getSubReg())
446     return nullptr;
447 
448   Register FoldReg = FoldOp.getReg();
449   Register LiveReg = LiveOp.getReg();
450 
451   assert(Register::isVirtualRegister(FoldReg) && "Cannot fold physregs");
452 
453   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
454   const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
455 
456   if (Register::isPhysicalRegister(LiveOp.getReg()))
457     return RC->contains(LiveOp.getReg()) ? RC : nullptr;
458 
459   if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
460     return RC;
461 
462   // FIXME: Allow folding when register classes are memory compatible.
463   return nullptr;
464 }
465 
466 void TargetInstrInfo::getNoop(MCInst &NopInst) const {
467   llvm_unreachable("Not implemented");
468 }
469 
470 static MachineInstr *foldPatchpoint(MachineFunction &MF, MachineInstr &MI,
471                                     ArrayRef<unsigned> Ops, int FrameIndex,
472                                     const TargetInstrInfo &TII) {
473   unsigned StartIdx = 0;
474   switch (MI.getOpcode()) {
475   case TargetOpcode::STACKMAP: {
476     // StackMapLiveValues are foldable
477     StartIdx = StackMapOpers(&MI).getVarIdx();
478     break;
479   }
480   case TargetOpcode::PATCHPOINT: {
481     // For PatchPoint, the call args are not foldable (even if reported in the
482     // stackmap e.g. via anyregcc).
483     StartIdx = PatchPointOpers(&MI).getVarIdx();
484     break;
485   }
486   case TargetOpcode::STATEPOINT: {
487     // For statepoints, fold deopt and gc arguments, but not call arguments.
488     StartIdx = StatepointOpers(&MI).getVarIdx();
489     break;
490   }
491   default:
492     llvm_unreachable("unexpected stackmap opcode");
493   }
494 
495   // Return false if any operands requested for folding are not foldable (not
496   // part of the stackmap's live values).
497   for (unsigned Op : Ops) {
498     if (Op < StartIdx)
499       return nullptr;
500   }
501 
502   MachineInstr *NewMI =
503       MF.CreateMachineInstr(TII.get(MI.getOpcode()), MI.getDebugLoc(), true);
504   MachineInstrBuilder MIB(MF, NewMI);
505 
506   // No need to fold return, the meta data, and function arguments
507   for (unsigned i = 0; i < StartIdx; ++i)
508     MIB.add(MI.getOperand(i));
509 
510   for (unsigned i = StartIdx; i < MI.getNumOperands(); ++i) {
511     MachineOperand &MO = MI.getOperand(i);
512     if (is_contained(Ops, i)) {
513       unsigned SpillSize;
514       unsigned SpillOffset;
515       // Compute the spill slot size and offset.
516       const TargetRegisterClass *RC =
517         MF.getRegInfo().getRegClass(MO.getReg());
518       bool Valid =
519           TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF);
520       if (!Valid)
521         report_fatal_error("cannot spill patchpoint subregister operand");
522       MIB.addImm(StackMaps::IndirectMemRefOp);
523       MIB.addImm(SpillSize);
524       MIB.addFrameIndex(FrameIndex);
525       MIB.addImm(SpillOffset);
526     }
527     else
528       MIB.add(MO);
529   }
530   return NewMI;
531 }
532 
533 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
534                                                  ArrayRef<unsigned> Ops, int FI,
535                                                  LiveIntervals *LIS,
536                                                  VirtRegMap *VRM) const {
537   auto Flags = MachineMemOperand::MONone;
538   for (unsigned OpIdx : Ops)
539     Flags |= MI.getOperand(OpIdx).isDef() ? MachineMemOperand::MOStore
540                                           : MachineMemOperand::MOLoad;
541 
542   MachineBasicBlock *MBB = MI.getParent();
543   assert(MBB && "foldMemoryOperand needs an inserted instruction");
544   MachineFunction &MF = *MBB->getParent();
545 
546   // If we're not folding a load into a subreg, the size of the load is the
547   // size of the spill slot. But if we are, we need to figure out what the
548   // actual load size is.
549   int64_t MemSize = 0;
550   const MachineFrameInfo &MFI = MF.getFrameInfo();
551   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
552 
553   if (Flags & MachineMemOperand::MOStore) {
554     MemSize = MFI.getObjectSize(FI);
555   } else {
556     for (unsigned OpIdx : Ops) {
557       int64_t OpSize = MFI.getObjectSize(FI);
558 
559       if (auto SubReg = MI.getOperand(OpIdx).getSubReg()) {
560         unsigned SubRegSize = TRI->getSubRegIdxSize(SubReg);
561         if (SubRegSize > 0 && !(SubRegSize % 8))
562           OpSize = SubRegSize / 8;
563       }
564 
565       MemSize = std::max(MemSize, OpSize);
566     }
567   }
568 
569   assert(MemSize && "Did not expect a zero-sized stack slot");
570 
571   MachineInstr *NewMI = nullptr;
572 
573   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
574       MI.getOpcode() == TargetOpcode::PATCHPOINT ||
575       MI.getOpcode() == TargetOpcode::STATEPOINT) {
576     // Fold stackmap/patchpoint.
577     NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
578     if (NewMI)
579       MBB->insert(MI, NewMI);
580   } else {
581     // Ask the target to do the actual folding.
582     NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, FI, LIS, VRM);
583   }
584 
585   if (NewMI) {
586     NewMI->setMemRefs(MF, MI.memoperands());
587     // Add a memory operand, foldMemoryOperandImpl doesn't do that.
588     assert((!(Flags & MachineMemOperand::MOStore) ||
589             NewMI->mayStore()) &&
590            "Folded a def to a non-store!");
591     assert((!(Flags & MachineMemOperand::MOLoad) ||
592             NewMI->mayLoad()) &&
593            "Folded a use to a non-load!");
594     assert(MFI.getObjectOffset(FI) != -1);
595     MachineMemOperand *MMO =
596         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
597                                 Flags, MemSize, MFI.getObjectAlign(FI));
598     NewMI->addMemOperand(MF, MMO);
599 
600     // The pass "x86 speculative load hardening" always attaches symbols to
601     // call instructions. We need copy it form old instruction.
602     NewMI->cloneInstrSymbols(MF, MI);
603 
604     return NewMI;
605   }
606 
607   // Straight COPY may fold as load/store.
608   if (!MI.isCopy() || Ops.size() != 1)
609     return nullptr;
610 
611   const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
612   if (!RC)
613     return nullptr;
614 
615   const MachineOperand &MO = MI.getOperand(1 - Ops[0]);
616   MachineBasicBlock::iterator Pos = MI;
617 
618   if (Flags == MachineMemOperand::MOStore)
619     storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
620   else
621     loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
622   return &*--Pos;
623 }
624 
625 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
626                                                  ArrayRef<unsigned> Ops,
627                                                  MachineInstr &LoadMI,
628                                                  LiveIntervals *LIS) const {
629   assert(LoadMI.canFoldAsLoad() && "LoadMI isn't foldable!");
630 #ifndef NDEBUG
631   for (unsigned OpIdx : Ops)
632     assert(MI.getOperand(OpIdx).isUse() && "Folding load into def!");
633 #endif
634 
635   MachineBasicBlock &MBB = *MI.getParent();
636   MachineFunction &MF = *MBB.getParent();
637 
638   // Ask the target to do the actual folding.
639   MachineInstr *NewMI = nullptr;
640   int FrameIndex = 0;
641 
642   if ((MI.getOpcode() == TargetOpcode::STACKMAP ||
643        MI.getOpcode() == TargetOpcode::PATCHPOINT ||
644        MI.getOpcode() == TargetOpcode::STATEPOINT) &&
645       isLoadFromStackSlot(LoadMI, FrameIndex)) {
646     // Fold stackmap/patchpoint.
647     NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
648     if (NewMI)
649       NewMI = &*MBB.insert(MI, NewMI);
650   } else {
651     // Ask the target to do the actual folding.
652     NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, LoadMI, LIS);
653   }
654 
655   if (!NewMI)
656     return nullptr;
657 
658   // Copy the memoperands from the load to the folded instruction.
659   if (MI.memoperands_empty()) {
660     NewMI->setMemRefs(MF, LoadMI.memoperands());
661   } else {
662     // Handle the rare case of folding multiple loads.
663     NewMI->setMemRefs(MF, MI.memoperands());
664     for (MachineInstr::mmo_iterator I = LoadMI.memoperands_begin(),
665                                     E = LoadMI.memoperands_end();
666          I != E; ++I) {
667       NewMI->addMemOperand(MF, *I);
668     }
669   }
670   return NewMI;
671 }
672 
673 bool TargetInstrInfo::hasReassociableOperands(
674     const MachineInstr &Inst, const MachineBasicBlock *MBB) const {
675   const MachineOperand &Op1 = Inst.getOperand(1);
676   const MachineOperand &Op2 = Inst.getOperand(2);
677   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
678 
679   // We need virtual register definitions for the operands that we will
680   // reassociate.
681   MachineInstr *MI1 = nullptr;
682   MachineInstr *MI2 = nullptr;
683   if (Op1.isReg() && Register::isVirtualRegister(Op1.getReg()))
684     MI1 = MRI.getUniqueVRegDef(Op1.getReg());
685   if (Op2.isReg() && Register::isVirtualRegister(Op2.getReg()))
686     MI2 = MRI.getUniqueVRegDef(Op2.getReg());
687 
688   // And they need to be in the trace (otherwise, they won't have a depth).
689   return MI1 && MI2 && MI1->getParent() == MBB && MI2->getParent() == MBB;
690 }
691 
692 bool TargetInstrInfo::hasReassociableSibling(const MachineInstr &Inst,
693                                              bool &Commuted) const {
694   const MachineBasicBlock *MBB = Inst.getParent();
695   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
696   MachineInstr *MI1 = MRI.getUniqueVRegDef(Inst.getOperand(1).getReg());
697   MachineInstr *MI2 = MRI.getUniqueVRegDef(Inst.getOperand(2).getReg());
698   unsigned AssocOpcode = Inst.getOpcode();
699 
700   // If only one operand has the same opcode and it's the second source operand,
701   // the operands must be commuted.
702   Commuted = MI1->getOpcode() != AssocOpcode && MI2->getOpcode() == AssocOpcode;
703   if (Commuted)
704     std::swap(MI1, MI2);
705 
706   // 1. The previous instruction must be the same type as Inst.
707   // 2. The previous instruction must also be associative/commutative (this can
708   //    be different even for instructions with the same opcode if traits like
709   //    fast-math-flags are included).
710   // 3. The previous instruction must have virtual register definitions for its
711   //    operands in the same basic block as Inst.
712   // 4. The previous instruction's result must only be used by Inst.
713   return MI1->getOpcode() == AssocOpcode && isAssociativeAndCommutative(*MI1) &&
714          hasReassociableOperands(*MI1, MBB) &&
715          MRI.hasOneNonDBGUse(MI1->getOperand(0).getReg());
716 }
717 
718 // 1. The operation must be associative and commutative.
719 // 2. The instruction must have virtual register definitions for its
720 //    operands in the same basic block.
721 // 3. The instruction must have a reassociable sibling.
722 bool TargetInstrInfo::isReassociationCandidate(const MachineInstr &Inst,
723                                                bool &Commuted) const {
724   return isAssociativeAndCommutative(Inst) &&
725          hasReassociableOperands(Inst, Inst.getParent()) &&
726          hasReassociableSibling(Inst, Commuted);
727 }
728 
729 // The concept of the reassociation pass is that these operations can benefit
730 // from this kind of transformation:
731 //
732 // A = ? op ?
733 // B = A op X (Prev)
734 // C = B op Y (Root)
735 // -->
736 // A = ? op ?
737 // B = X op Y
738 // C = A op B
739 //
740 // breaking the dependency between A and B, allowing them to be executed in
741 // parallel (or back-to-back in a pipeline) instead of depending on each other.
742 
743 // FIXME: This has the potential to be expensive (compile time) while not
744 // improving the code at all. Some ways to limit the overhead:
745 // 1. Track successful transforms; bail out if hit rate gets too low.
746 // 2. Only enable at -O3 or some other non-default optimization level.
747 // 3. Pre-screen pattern candidates here: if an operand of the previous
748 //    instruction is known to not increase the critical path, then don't match
749 //    that pattern.
750 bool TargetInstrInfo::getMachineCombinerPatterns(
751     MachineInstr &Root,
752     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
753   bool Commute;
754   if (isReassociationCandidate(Root, Commute)) {
755     // We found a sequence of instructions that may be suitable for a
756     // reassociation of operands to increase ILP. Specify each commutation
757     // possibility for the Prev instruction in the sequence and let the
758     // machine combiner decide if changing the operands is worthwhile.
759     if (Commute) {
760       Patterns.push_back(MachineCombinerPattern::REASSOC_AX_YB);
761       Patterns.push_back(MachineCombinerPattern::REASSOC_XA_YB);
762     } else {
763       Patterns.push_back(MachineCombinerPattern::REASSOC_AX_BY);
764       Patterns.push_back(MachineCombinerPattern::REASSOC_XA_BY);
765     }
766     return true;
767   }
768 
769   return false;
770 }
771 
772 /// Return true when a code sequence can improve loop throughput.
773 bool
774 TargetInstrInfo::isThroughputPattern(MachineCombinerPattern Pattern) const {
775   return false;
776 }
777 
778 /// Attempt the reassociation transformation to reduce critical path length.
779 /// See the above comments before getMachineCombinerPatterns().
780 void TargetInstrInfo::reassociateOps(
781     MachineInstr &Root, MachineInstr &Prev,
782     MachineCombinerPattern Pattern,
783     SmallVectorImpl<MachineInstr *> &InsInstrs,
784     SmallVectorImpl<MachineInstr *> &DelInstrs,
785     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
786   MachineFunction *MF = Root.getMF();
787   MachineRegisterInfo &MRI = MF->getRegInfo();
788   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
789   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
790   const TargetRegisterClass *RC = Root.getRegClassConstraint(0, TII, TRI);
791 
792   // This array encodes the operand index for each parameter because the
793   // operands may be commuted. Each row corresponds to a pattern value,
794   // and each column specifies the index of A, B, X, Y.
795   unsigned OpIdx[4][4] = {
796     { 1, 1, 2, 2 },
797     { 1, 2, 2, 1 },
798     { 2, 1, 1, 2 },
799     { 2, 2, 1, 1 }
800   };
801 
802   int Row;
803   switch (Pattern) {
804   case MachineCombinerPattern::REASSOC_AX_BY: Row = 0; break;
805   case MachineCombinerPattern::REASSOC_AX_YB: Row = 1; break;
806   case MachineCombinerPattern::REASSOC_XA_BY: Row = 2; break;
807   case MachineCombinerPattern::REASSOC_XA_YB: Row = 3; break;
808   default: llvm_unreachable("unexpected MachineCombinerPattern");
809   }
810 
811   MachineOperand &OpA = Prev.getOperand(OpIdx[Row][0]);
812   MachineOperand &OpB = Root.getOperand(OpIdx[Row][1]);
813   MachineOperand &OpX = Prev.getOperand(OpIdx[Row][2]);
814   MachineOperand &OpY = Root.getOperand(OpIdx[Row][3]);
815   MachineOperand &OpC = Root.getOperand(0);
816 
817   Register RegA = OpA.getReg();
818   Register RegB = OpB.getReg();
819   Register RegX = OpX.getReg();
820   Register RegY = OpY.getReg();
821   Register RegC = OpC.getReg();
822 
823   if (Register::isVirtualRegister(RegA))
824     MRI.constrainRegClass(RegA, RC);
825   if (Register::isVirtualRegister(RegB))
826     MRI.constrainRegClass(RegB, RC);
827   if (Register::isVirtualRegister(RegX))
828     MRI.constrainRegClass(RegX, RC);
829   if (Register::isVirtualRegister(RegY))
830     MRI.constrainRegClass(RegY, RC);
831   if (Register::isVirtualRegister(RegC))
832     MRI.constrainRegClass(RegC, RC);
833 
834   // Create a new virtual register for the result of (X op Y) instead of
835   // recycling RegB because the MachineCombiner's computation of the critical
836   // path requires a new register definition rather than an existing one.
837   Register NewVR = MRI.createVirtualRegister(RC);
838   InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
839 
840   unsigned Opcode = Root.getOpcode();
841   bool KillA = OpA.isKill();
842   bool KillX = OpX.isKill();
843   bool KillY = OpY.isKill();
844 
845   // Create new instructions for insertion.
846   MachineInstrBuilder MIB1 =
847       BuildMI(*MF, Prev.getDebugLoc(), TII->get(Opcode), NewVR)
848           .addReg(RegX, getKillRegState(KillX))
849           .addReg(RegY, getKillRegState(KillY));
850   MachineInstrBuilder MIB2 =
851       BuildMI(*MF, Root.getDebugLoc(), TII->get(Opcode), RegC)
852           .addReg(RegA, getKillRegState(KillA))
853           .addReg(NewVR, getKillRegState(true));
854 
855   setSpecialOperandAttr(Root, Prev, *MIB1, *MIB2);
856 
857   // Record new instructions for insertion and old instructions for deletion.
858   InsInstrs.push_back(MIB1);
859   InsInstrs.push_back(MIB2);
860   DelInstrs.push_back(&Prev);
861   DelInstrs.push_back(&Root);
862 }
863 
864 void TargetInstrInfo::genAlternativeCodeSequence(
865     MachineInstr &Root, MachineCombinerPattern Pattern,
866     SmallVectorImpl<MachineInstr *> &InsInstrs,
867     SmallVectorImpl<MachineInstr *> &DelInstrs,
868     DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const {
869   MachineRegisterInfo &MRI = Root.getMF()->getRegInfo();
870 
871   // Select the previous instruction in the sequence based on the input pattern.
872   MachineInstr *Prev = nullptr;
873   switch (Pattern) {
874   case MachineCombinerPattern::REASSOC_AX_BY:
875   case MachineCombinerPattern::REASSOC_XA_BY:
876     Prev = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
877     break;
878   case MachineCombinerPattern::REASSOC_AX_YB:
879   case MachineCombinerPattern::REASSOC_XA_YB:
880     Prev = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
881     break;
882   default:
883     break;
884   }
885 
886   assert(Prev && "Unknown pattern for machine combiner");
887 
888   reassociateOps(Root, *Prev, Pattern, InsInstrs, DelInstrs, InstIdxForVirtReg);
889 }
890 
891 bool TargetInstrInfo::isReallyTriviallyReMaterializableGeneric(
892     const MachineInstr &MI, AAResults *AA) const {
893   const MachineFunction &MF = *MI.getMF();
894   const MachineRegisterInfo &MRI = MF.getRegInfo();
895 
896   // Remat clients assume operand 0 is the defined register.
897   if (!MI.getNumOperands() || !MI.getOperand(0).isReg())
898     return false;
899   Register DefReg = MI.getOperand(0).getReg();
900 
901   // A sub-register definition can only be rematerialized if the instruction
902   // doesn't read the other parts of the register.  Otherwise it is really a
903   // read-modify-write operation on the full virtual register which cannot be
904   // moved safely.
905   if (Register::isVirtualRegister(DefReg) && MI.getOperand(0).getSubReg() &&
906       MI.readsVirtualRegister(DefReg))
907     return false;
908 
909   // A load from a fixed stack slot can be rematerialized. This may be
910   // redundant with subsequent checks, but it's target-independent,
911   // simple, and a common case.
912   int FrameIdx = 0;
913   if (isLoadFromStackSlot(MI, FrameIdx) &&
914       MF.getFrameInfo().isImmutableObjectIndex(FrameIdx))
915     return true;
916 
917   // Avoid instructions obviously unsafe for remat.
918   if (MI.isNotDuplicable() || MI.mayStore() || MI.mayRaiseFPException() ||
919       MI.hasUnmodeledSideEffects())
920     return false;
921 
922   // Don't remat inline asm. We have no idea how expensive it is
923   // even if it's side effect free.
924   if (MI.isInlineAsm())
925     return false;
926 
927   // Avoid instructions which load from potentially varying memory.
928   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA))
929     return false;
930 
931   // If any of the registers accessed are non-constant, conservatively assume
932   // the instruction is not rematerializable.
933   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
934     const MachineOperand &MO = MI.getOperand(i);
935     if (!MO.isReg()) continue;
936     Register Reg = MO.getReg();
937     if (Reg == 0)
938       continue;
939 
940     // Check for a well-behaved physical register.
941     if (Register::isPhysicalRegister(Reg)) {
942       if (MO.isUse()) {
943         // If the physreg has no defs anywhere, it's just an ambient register
944         // and we can freely move its uses. Alternatively, if it's allocatable,
945         // it could get allocated to something with a def during allocation.
946         if (!MRI.isConstantPhysReg(Reg))
947           return false;
948       } else {
949         // A physreg def. We can't remat it.
950         return false;
951       }
952       continue;
953     }
954 
955     // Only allow one virtual-register def.  There may be multiple defs of the
956     // same virtual register, though.
957     if (MO.isDef() && Reg != DefReg)
958       return false;
959 
960     // Don't allow any virtual-register uses. Rematting an instruction with
961     // virtual register uses would length the live ranges of the uses, which
962     // is not necessarily a good idea, certainly not "trivial".
963     if (MO.isUse())
964       return false;
965   }
966 
967   // Everything checked out.
968   return true;
969 }
970 
971 int TargetInstrInfo::getSPAdjust(const MachineInstr &MI) const {
972   const MachineFunction *MF = MI.getMF();
973   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
974   bool StackGrowsDown =
975     TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
976 
977   unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
978   unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
979 
980   if (!isFrameInstr(MI))
981     return 0;
982 
983   int SPAdj = TFI->alignSPAdjust(getFrameSize(MI));
984 
985   if ((!StackGrowsDown && MI.getOpcode() == FrameSetupOpcode) ||
986       (StackGrowsDown && MI.getOpcode() == FrameDestroyOpcode))
987     SPAdj = -SPAdj;
988 
989   return SPAdj;
990 }
991 
992 /// isSchedulingBoundary - Test if the given instruction should be
993 /// considered a scheduling boundary. This primarily includes labels
994 /// and terminators.
995 bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
996                                            const MachineBasicBlock *MBB,
997                                            const MachineFunction &MF) const {
998   // Terminators and labels can't be scheduled around.
999   if (MI.isTerminator() || MI.isPosition())
1000     return true;
1001 
1002   // INLINEASM_BR can jump to another block
1003   if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
1004     return true;
1005 
1006   // Don't attempt to schedule around any instruction that defines
1007   // a stack-oriented pointer, as it's unlikely to be profitable. This
1008   // saves compile time, because it doesn't require every single
1009   // stack slot reference to depend on the instruction that does the
1010   // modification.
1011   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1012   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1013   return MI.modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI);
1014 }
1015 
1016 // Provide a global flag for disabling the PreRA hazard recognizer that targets
1017 // may choose to honor.
1018 bool TargetInstrInfo::usePreRAHazardRecognizer() const {
1019   return !DisableHazardRecognizer;
1020 }
1021 
1022 // Default implementation of CreateTargetRAHazardRecognizer.
1023 ScheduleHazardRecognizer *TargetInstrInfo::
1024 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1025                              const ScheduleDAG *DAG) const {
1026   // Dummy hazard recognizer allows all instructions to issue.
1027   return new ScheduleHazardRecognizer();
1028 }
1029 
1030 // Default implementation of CreateTargetMIHazardRecognizer.
1031 ScheduleHazardRecognizer *TargetInstrInfo::CreateTargetMIHazardRecognizer(
1032     const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
1033   return new ScoreboardHazardRecognizer(II, DAG, "machine-scheduler");
1034 }
1035 
1036 // Default implementation of CreateTargetPostRAHazardRecognizer.
1037 ScheduleHazardRecognizer *TargetInstrInfo::
1038 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
1039                                    const ScheduleDAG *DAG) const {
1040   return new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
1041 }
1042 
1043 // Default implementation of getMemOperandWithOffset.
1044 bool TargetInstrInfo::getMemOperandWithOffset(
1045     const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset,
1046     bool &OffsetIsScalable, const TargetRegisterInfo *TRI) const {
1047   SmallVector<const MachineOperand *, 4> BaseOps;
1048   unsigned Width;
1049   if (!getMemOperandsWithOffsetWidth(MI, BaseOps, Offset, OffsetIsScalable,
1050                                      Width, TRI) ||
1051       BaseOps.size() != 1)
1052     return false;
1053   BaseOp = BaseOps.front();
1054   return true;
1055 }
1056 
1057 //===----------------------------------------------------------------------===//
1058 //  SelectionDAG latency interface.
1059 //===----------------------------------------------------------------------===//
1060 
1061 int
1062 TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1063                                    SDNode *DefNode, unsigned DefIdx,
1064                                    SDNode *UseNode, unsigned UseIdx) const {
1065   if (!ItinData || ItinData->isEmpty())
1066     return -1;
1067 
1068   if (!DefNode->isMachineOpcode())
1069     return -1;
1070 
1071   unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
1072   if (!UseNode->isMachineOpcode())
1073     return ItinData->getOperandCycle(DefClass, DefIdx);
1074   unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
1075   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1076 }
1077 
1078 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1079                                      SDNode *N) const {
1080   if (!ItinData || ItinData->isEmpty())
1081     return 1;
1082 
1083   if (!N->isMachineOpcode())
1084     return 1;
1085 
1086   return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
1087 }
1088 
1089 //===----------------------------------------------------------------------===//
1090 //  MachineInstr latency interface.
1091 //===----------------------------------------------------------------------===//
1092 
1093 unsigned TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1094                                          const MachineInstr &MI) const {
1095   if (!ItinData || ItinData->isEmpty())
1096     return 1;
1097 
1098   unsigned Class = MI.getDesc().getSchedClass();
1099   int UOps = ItinData->Itineraries[Class].NumMicroOps;
1100   if (UOps >= 0)
1101     return UOps;
1102 
1103   // The # of u-ops is dynamically determined. The specific target should
1104   // override this function to return the right number.
1105   return 1;
1106 }
1107 
1108 /// Return the default expected latency for a def based on it's opcode.
1109 unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
1110                                             const MachineInstr &DefMI) const {
1111   if (DefMI.isTransient())
1112     return 0;
1113   if (DefMI.mayLoad())
1114     return SchedModel.LoadLatency;
1115   if (isHighLatencyDef(DefMI.getOpcode()))
1116     return SchedModel.HighLatency;
1117   return 1;
1118 }
1119 
1120 unsigned TargetInstrInfo::getPredicationCost(const MachineInstr &) const {
1121   return 0;
1122 }
1123 
1124 unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1125                                           const MachineInstr &MI,
1126                                           unsigned *PredCost) const {
1127   // Default to one cycle for no itinerary. However, an "empty" itinerary may
1128   // still have a MinLatency property, which getStageLatency checks.
1129   if (!ItinData)
1130     return MI.mayLoad() ? 2 : 1;
1131 
1132   return ItinData->getStageLatency(MI.getDesc().getSchedClass());
1133 }
1134 
1135 bool TargetInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
1136                                        const MachineInstr &DefMI,
1137                                        unsigned DefIdx) const {
1138   const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
1139   if (!ItinData || ItinData->isEmpty())
1140     return false;
1141 
1142   unsigned DefClass = DefMI.getDesc().getSchedClass();
1143   int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
1144   return (DefCycle != -1 && DefCycle <= 1);
1145 }
1146 
1147 Optional<ParamLoadedValue>
1148 TargetInstrInfo::describeLoadedValue(const MachineInstr &MI,
1149                                      Register Reg) const {
1150   const MachineFunction *MF = MI.getMF();
1151   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1152   DIExpression *Expr = DIExpression::get(MF->getFunction().getContext(), {});
1153   int64_t Offset;
1154   bool OffsetIsScalable;
1155 
1156   // To simplify the sub-register handling, verify that we only need to
1157   // consider physical registers.
1158   assert(MF->getProperties().hasProperty(
1159       MachineFunctionProperties::Property::NoVRegs));
1160 
1161   if (auto DestSrc = isCopyInstr(MI)) {
1162     Register DestReg = DestSrc->Destination->getReg();
1163 
1164     // If the copy destination is the forwarding reg, describe the forwarding
1165     // reg using the copy source as the backup location. Example:
1166     //
1167     //   x0 = MOV x7
1168     //   call callee(x0)      ; x0 described as x7
1169     if (Reg == DestReg)
1170       return ParamLoadedValue(*DestSrc->Source, Expr);
1171 
1172     // Cases where super- or sub-registers needs to be described should
1173     // be handled by the target's hook implementation.
1174     assert(!TRI->isSuperOrSubRegisterEq(Reg, DestReg) &&
1175            "TargetInstrInfo::describeLoadedValue can't describe super- or "
1176            "sub-regs for copy instructions");
1177     return None;
1178   } else if (auto RegImm = isAddImmediate(MI, Reg)) {
1179     Register SrcReg = RegImm->Reg;
1180     Offset = RegImm->Imm;
1181     Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset, Offset);
1182     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
1183   } else if (MI.hasOneMemOperand()) {
1184     // Only describe memory which provably does not escape the function. As
1185     // described in llvm.org/PR43343, escaped memory may be clobbered by the
1186     // callee (or by another thread).
1187     const auto &TII = MF->getSubtarget().getInstrInfo();
1188     const MachineFrameInfo &MFI = MF->getFrameInfo();
1189     const MachineMemOperand *MMO = MI.memoperands()[0];
1190     const PseudoSourceValue *PSV = MMO->getPseudoValue();
1191 
1192     // If the address points to "special" memory (e.g. a spill slot), it's
1193     // sufficient to check that it isn't aliased by any high-level IR value.
1194     if (!PSV || PSV->mayAlias(&MFI))
1195       return None;
1196 
1197     const MachineOperand *BaseOp;
1198     if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable,
1199                                       TRI))
1200       return None;
1201 
1202     // FIXME: Scalable offsets are not yet handled in the offset code below.
1203     if (OffsetIsScalable)
1204       return None;
1205 
1206     // TODO: Can currently only handle mem instructions with a single define.
1207     // An example from the x86 target:
1208     //    ...
1209     //    DIV64m $rsp, 1, $noreg, 24, $noreg, implicit-def dead $rax, implicit-def $rdx
1210     //    ...
1211     //
1212     if (MI.getNumExplicitDefs() != 1)
1213       return None;
1214 
1215     // TODO: In what way do we need to take Reg into consideration here?
1216 
1217     SmallVector<uint64_t, 8> Ops;
1218     DIExpression::appendOffset(Ops, Offset);
1219     Ops.push_back(dwarf::DW_OP_deref_size);
1220     Ops.push_back(MMO->getSize());
1221     Expr = DIExpression::prependOpcodes(Expr, Ops);
1222     return ParamLoadedValue(*BaseOp, Expr);
1223   }
1224 
1225   return None;
1226 }
1227 
1228 /// Both DefMI and UseMI must be valid.  By default, call directly to the
1229 /// itinerary. This may be overriden by the target.
1230 int TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1231                                        const MachineInstr &DefMI,
1232                                        unsigned DefIdx,
1233                                        const MachineInstr &UseMI,
1234                                        unsigned UseIdx) const {
1235   unsigned DefClass = DefMI.getDesc().getSchedClass();
1236   unsigned UseClass = UseMI.getDesc().getSchedClass();
1237   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1238 }
1239 
1240 /// If we can determine the operand latency from the def only, without itinerary
1241 /// lookup, do so. Otherwise return -1.
1242 int TargetInstrInfo::computeDefOperandLatency(
1243     const InstrItineraryData *ItinData, const MachineInstr &DefMI) const {
1244 
1245   // Let the target hook getInstrLatency handle missing itineraries.
1246   if (!ItinData)
1247     return getInstrLatency(ItinData, DefMI);
1248 
1249   if(ItinData->isEmpty())
1250     return defaultDefLatency(ItinData->SchedModel, DefMI);
1251 
1252   // ...operand lookup required
1253   return -1;
1254 }
1255 
1256 bool TargetInstrInfo::getRegSequenceInputs(
1257     const MachineInstr &MI, unsigned DefIdx,
1258     SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1259   assert((MI.isRegSequence() ||
1260           MI.isRegSequenceLike()) && "Instruction do not have the proper type");
1261 
1262   if (!MI.isRegSequence())
1263     return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
1264 
1265   // We are looking at:
1266   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1267   assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
1268   for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
1269        OpIdx += 2) {
1270     const MachineOperand &MOReg = MI.getOperand(OpIdx);
1271     if (MOReg.isUndef())
1272       continue;
1273     const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
1274     assert(MOSubIdx.isImm() &&
1275            "One of the subindex of the reg_sequence is not an immediate");
1276     // Record Reg:SubReg, SubIdx.
1277     InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
1278                                             (unsigned)MOSubIdx.getImm()));
1279   }
1280   return true;
1281 }
1282 
1283 bool TargetInstrInfo::getExtractSubregInputs(
1284     const MachineInstr &MI, unsigned DefIdx,
1285     RegSubRegPairAndIdx &InputReg) const {
1286   assert((MI.isExtractSubreg() ||
1287       MI.isExtractSubregLike()) && "Instruction do not have the proper type");
1288 
1289   if (!MI.isExtractSubreg())
1290     return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
1291 
1292   // We are looking at:
1293   // Def = EXTRACT_SUBREG v0.sub1, sub0.
1294   assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
1295   const MachineOperand &MOReg = MI.getOperand(1);
1296   if (MOReg.isUndef())
1297     return false;
1298   const MachineOperand &MOSubIdx = MI.getOperand(2);
1299   assert(MOSubIdx.isImm() &&
1300          "The subindex of the extract_subreg is not an immediate");
1301 
1302   InputReg.Reg = MOReg.getReg();
1303   InputReg.SubReg = MOReg.getSubReg();
1304   InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
1305   return true;
1306 }
1307 
1308 bool TargetInstrInfo::getInsertSubregInputs(
1309     const MachineInstr &MI, unsigned DefIdx,
1310     RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
1311   assert((MI.isInsertSubreg() ||
1312       MI.isInsertSubregLike()) && "Instruction do not have the proper type");
1313 
1314   if (!MI.isInsertSubreg())
1315     return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
1316 
1317   // We are looking at:
1318   // Def = INSERT_SEQUENCE v0, v1, sub0.
1319   assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
1320   const MachineOperand &MOBaseReg = MI.getOperand(1);
1321   const MachineOperand &MOInsertedReg = MI.getOperand(2);
1322   if (MOInsertedReg.isUndef())
1323     return false;
1324   const MachineOperand &MOSubIdx = MI.getOperand(3);
1325   assert(MOSubIdx.isImm() &&
1326          "One of the subindex of the reg_sequence is not an immediate");
1327   BaseReg.Reg = MOBaseReg.getReg();
1328   BaseReg.SubReg = MOBaseReg.getSubReg();
1329 
1330   InsertedReg.Reg = MOInsertedReg.getReg();
1331   InsertedReg.SubReg = MOInsertedReg.getSubReg();
1332   InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
1333   return true;
1334 }
1335 
1336 // Returns a MIRPrinter comment for this machine operand.
1337 std::string TargetInstrInfo::createMIROperandComment(
1338     const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
1339     const TargetRegisterInfo *TRI) const {
1340 
1341   if (!MI.isInlineAsm())
1342     return "";
1343 
1344   std::string Flags;
1345   raw_string_ostream OS(Flags);
1346 
1347   if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
1348     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1349     unsigned ExtraInfo = Op.getImm();
1350     bool First = true;
1351     for (StringRef Info : InlineAsm::getExtraInfoNames(ExtraInfo)) {
1352       if (!First)
1353         OS << " ";
1354       First = false;
1355       OS << Info;
1356     }
1357 
1358     return OS.str();
1359   }
1360 
1361   int FlagIdx = MI.findInlineAsmFlagIdx(OpIdx);
1362   if (FlagIdx < 0 || (unsigned)FlagIdx != OpIdx)
1363     return "";
1364 
1365   assert(Op.isImm() && "Expected flag operand to be an immediate");
1366   // Pretty print the inline asm operand descriptor.
1367   unsigned Flag = Op.getImm();
1368   unsigned Kind = InlineAsm::getKind(Flag);
1369   OS << InlineAsm::getKindName(Kind);
1370 
1371   unsigned RCID = 0;
1372   if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1373       InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1374     if (TRI) {
1375       OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1376     } else
1377       OS << ":RC" << RCID;
1378   }
1379 
1380   if (InlineAsm::isMemKind(Flag)) {
1381     unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1382     OS << ":" << InlineAsm::getMemConstraintName(MCID);
1383   }
1384 
1385   unsigned TiedTo = 0;
1386   if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1387     OS << " tiedto:$" << TiedTo;
1388 
1389   return OS.str();
1390 }
1391 
1392 TargetInstrInfo::PipelinerLoopInfo::~PipelinerLoopInfo() {}
1393