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   unsigned NumDefs = 0;
475   switch (MI.getOpcode()) {
476   case TargetOpcode::STACKMAP: {
477     // StackMapLiveValues are foldable
478     StartIdx = StackMapOpers(&MI).getVarIdx();
479     break;
480   }
481   case TargetOpcode::PATCHPOINT: {
482     // For PatchPoint, the call args are not foldable (even if reported in the
483     // stackmap e.g. via anyregcc).
484     StartIdx = PatchPointOpers(&MI).getVarIdx();
485     break;
486   }
487   case TargetOpcode::STATEPOINT: {
488     // For statepoints, fold deopt and gc arguments, but not call arguments.
489     StartIdx = StatepointOpers(&MI).getVarIdx();
490     NumDefs = MI.getNumDefs();
491     break;
492   }
493   default:
494     llvm_unreachable("unexpected stackmap opcode");
495   }
496 
497   unsigned DefToFoldIdx = MI.getNumOperands();
498 
499   // Return false if any operands requested for folding are not foldable (not
500   // part of the stackmap's live values).
501   for (unsigned Op : Ops) {
502     // Caller is expected to avoid passing in tied operands
503     assert(!MI.getOperand(Op).isTied());
504     if (Op < NumDefs) {
505       assert(DefToFoldIdx == MI.getNumOperands() && "Folding multiple defs");
506       DefToFoldIdx = Op;
507     } else if (Op < StartIdx) {
508       return nullptr;
509     }
510   }
511 
512   MachineInstr *NewMI =
513       MF.CreateMachineInstr(TII.get(MI.getOpcode()), MI.getDebugLoc(), true);
514   MachineInstrBuilder MIB(MF, NewMI);
515 
516   // No need to fold return, the meta data, and function arguments
517   for (unsigned i = 0; i < StartIdx; ++i)
518     if (i != DefToFoldIdx)
519       MIB.add(MI.getOperand(i));
520 
521   for (unsigned i = StartIdx, e = MI.getNumOperands(); i < e; ++i) {
522     MachineOperand &MO = MI.getOperand(i);
523     unsigned TiedTo = e;
524     (void)MI.isRegTiedToDefOperand(i, &TiedTo);
525 
526     if (is_contained(Ops, i)) {
527       assert(TiedTo == e && "Cannot fold tied operands");
528       unsigned SpillSize;
529       unsigned SpillOffset;
530       // Compute the spill slot size and offset.
531       const TargetRegisterClass *RC =
532         MF.getRegInfo().getRegClass(MO.getReg());
533       bool Valid =
534           TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF);
535       if (!Valid)
536         report_fatal_error("cannot spill patchpoint subregister operand");
537       MIB.addImm(StackMaps::IndirectMemRefOp);
538       MIB.addImm(SpillSize);
539       MIB.addFrameIndex(FrameIndex);
540       MIB.addImm(SpillOffset);
541     } else {
542       MIB.add(MO);
543       if (TiedTo < e) {
544         assert(TiedTo < NumDefs && "Bad tied operand");
545         if (TiedTo > DefToFoldIdx)
546           --TiedTo;
547         NewMI->tieOperands(TiedTo, NewMI->getNumOperands() - 1);
548       }
549     }
550   }
551   return NewMI;
552 }
553 
554 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
555                                                  ArrayRef<unsigned> Ops, int FI,
556                                                  LiveIntervals *LIS,
557                                                  VirtRegMap *VRM) const {
558   auto Flags = MachineMemOperand::MONone;
559   for (unsigned OpIdx : Ops)
560     Flags |= MI.getOperand(OpIdx).isDef() ? MachineMemOperand::MOStore
561                                           : MachineMemOperand::MOLoad;
562 
563   MachineBasicBlock *MBB = MI.getParent();
564   assert(MBB && "foldMemoryOperand needs an inserted instruction");
565   MachineFunction &MF = *MBB->getParent();
566 
567   // If we're not folding a load into a subreg, the size of the load is the
568   // size of the spill slot. But if we are, we need to figure out what the
569   // actual load size is.
570   int64_t MemSize = 0;
571   const MachineFrameInfo &MFI = MF.getFrameInfo();
572   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
573 
574   if (Flags & MachineMemOperand::MOStore) {
575     MemSize = MFI.getObjectSize(FI);
576   } else {
577     for (unsigned OpIdx : Ops) {
578       int64_t OpSize = MFI.getObjectSize(FI);
579 
580       if (auto SubReg = MI.getOperand(OpIdx).getSubReg()) {
581         unsigned SubRegSize = TRI->getSubRegIdxSize(SubReg);
582         if (SubRegSize > 0 && !(SubRegSize % 8))
583           OpSize = SubRegSize / 8;
584       }
585 
586       MemSize = std::max(MemSize, OpSize);
587     }
588   }
589 
590   assert(MemSize && "Did not expect a zero-sized stack slot");
591 
592   MachineInstr *NewMI = nullptr;
593 
594   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
595       MI.getOpcode() == TargetOpcode::PATCHPOINT ||
596       MI.getOpcode() == TargetOpcode::STATEPOINT) {
597     // Fold stackmap/patchpoint.
598     NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
599     if (NewMI)
600       MBB->insert(MI, NewMI);
601   } else {
602     // Ask the target to do the actual folding.
603     NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, FI, LIS, VRM);
604   }
605 
606   if (NewMI) {
607     NewMI->setMemRefs(MF, MI.memoperands());
608     // Add a memory operand, foldMemoryOperandImpl doesn't do that.
609     assert((!(Flags & MachineMemOperand::MOStore) ||
610             NewMI->mayStore()) &&
611            "Folded a def to a non-store!");
612     assert((!(Flags & MachineMemOperand::MOLoad) ||
613             NewMI->mayLoad()) &&
614            "Folded a use to a non-load!");
615     assert(MFI.getObjectOffset(FI) != -1);
616     MachineMemOperand *MMO =
617         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
618                                 Flags, MemSize, MFI.getObjectAlign(FI));
619     NewMI->addMemOperand(MF, MMO);
620 
621     // The pass "x86 speculative load hardening" always attaches symbols to
622     // call instructions. We need copy it form old instruction.
623     NewMI->cloneInstrSymbols(MF, MI);
624 
625     return NewMI;
626   }
627 
628   // Straight COPY may fold as load/store.
629   if (!MI.isCopy() || Ops.size() != 1)
630     return nullptr;
631 
632   const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
633   if (!RC)
634     return nullptr;
635 
636   const MachineOperand &MO = MI.getOperand(1 - Ops[0]);
637   MachineBasicBlock::iterator Pos = MI;
638 
639   if (Flags == MachineMemOperand::MOStore)
640     storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
641   else
642     loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
643   return &*--Pos;
644 }
645 
646 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
647                                                  ArrayRef<unsigned> Ops,
648                                                  MachineInstr &LoadMI,
649                                                  LiveIntervals *LIS) const {
650   assert(LoadMI.canFoldAsLoad() && "LoadMI isn't foldable!");
651 #ifndef NDEBUG
652   for (unsigned OpIdx : Ops)
653     assert(MI.getOperand(OpIdx).isUse() && "Folding load into def!");
654 #endif
655 
656   MachineBasicBlock &MBB = *MI.getParent();
657   MachineFunction &MF = *MBB.getParent();
658 
659   // Ask the target to do the actual folding.
660   MachineInstr *NewMI = nullptr;
661   int FrameIndex = 0;
662 
663   if ((MI.getOpcode() == TargetOpcode::STACKMAP ||
664        MI.getOpcode() == TargetOpcode::PATCHPOINT ||
665        MI.getOpcode() == TargetOpcode::STATEPOINT) &&
666       isLoadFromStackSlot(LoadMI, FrameIndex)) {
667     // Fold stackmap/patchpoint.
668     NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
669     if (NewMI)
670       NewMI = &*MBB.insert(MI, NewMI);
671   } else {
672     // Ask the target to do the actual folding.
673     NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, LoadMI, LIS);
674   }
675 
676   if (!NewMI)
677     return nullptr;
678 
679   // Copy the memoperands from the load to the folded instruction.
680   if (MI.memoperands_empty()) {
681     NewMI->setMemRefs(MF, LoadMI.memoperands());
682   } else {
683     // Handle the rare case of folding multiple loads.
684     NewMI->setMemRefs(MF, MI.memoperands());
685     for (MachineInstr::mmo_iterator I = LoadMI.memoperands_begin(),
686                                     E = LoadMI.memoperands_end();
687          I != E; ++I) {
688       NewMI->addMemOperand(MF, *I);
689     }
690   }
691   return NewMI;
692 }
693 
694 bool TargetInstrInfo::hasReassociableOperands(
695     const MachineInstr &Inst, const MachineBasicBlock *MBB) const {
696   const MachineOperand &Op1 = Inst.getOperand(1);
697   const MachineOperand &Op2 = Inst.getOperand(2);
698   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
699 
700   // We need virtual register definitions for the operands that we will
701   // reassociate.
702   MachineInstr *MI1 = nullptr;
703   MachineInstr *MI2 = nullptr;
704   if (Op1.isReg() && Register::isVirtualRegister(Op1.getReg()))
705     MI1 = MRI.getUniqueVRegDef(Op1.getReg());
706   if (Op2.isReg() && Register::isVirtualRegister(Op2.getReg()))
707     MI2 = MRI.getUniqueVRegDef(Op2.getReg());
708 
709   // And they need to be in the trace (otherwise, they won't have a depth).
710   return MI1 && MI2 && MI1->getParent() == MBB && MI2->getParent() == MBB;
711 }
712 
713 bool TargetInstrInfo::hasReassociableSibling(const MachineInstr &Inst,
714                                              bool &Commuted) const {
715   const MachineBasicBlock *MBB = Inst.getParent();
716   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
717   MachineInstr *MI1 = MRI.getUniqueVRegDef(Inst.getOperand(1).getReg());
718   MachineInstr *MI2 = MRI.getUniqueVRegDef(Inst.getOperand(2).getReg());
719   unsigned AssocOpcode = Inst.getOpcode();
720 
721   // If only one operand has the same opcode and it's the second source operand,
722   // the operands must be commuted.
723   Commuted = MI1->getOpcode() != AssocOpcode && MI2->getOpcode() == AssocOpcode;
724   if (Commuted)
725     std::swap(MI1, MI2);
726 
727   // 1. The previous instruction must be the same type as Inst.
728   // 2. The previous instruction must also be associative/commutative (this can
729   //    be different even for instructions with the same opcode if traits like
730   //    fast-math-flags are included).
731   // 3. The previous instruction must have virtual register definitions for its
732   //    operands in the same basic block as Inst.
733   // 4. The previous instruction's result must only be used by Inst.
734   return MI1->getOpcode() == AssocOpcode && isAssociativeAndCommutative(*MI1) &&
735          hasReassociableOperands(*MI1, MBB) &&
736          MRI.hasOneNonDBGUse(MI1->getOperand(0).getReg());
737 }
738 
739 // 1. The operation must be associative and commutative.
740 // 2. The instruction must have virtual register definitions for its
741 //    operands in the same basic block.
742 // 3. The instruction must have a reassociable sibling.
743 bool TargetInstrInfo::isReassociationCandidate(const MachineInstr &Inst,
744                                                bool &Commuted) const {
745   return isAssociativeAndCommutative(Inst) &&
746          hasReassociableOperands(Inst, Inst.getParent()) &&
747          hasReassociableSibling(Inst, Commuted);
748 }
749 
750 // The concept of the reassociation pass is that these operations can benefit
751 // from this kind of transformation:
752 //
753 // A = ? op ?
754 // B = A op X (Prev)
755 // C = B op Y (Root)
756 // -->
757 // A = ? op ?
758 // B = X op Y
759 // C = A op B
760 //
761 // breaking the dependency between A and B, allowing them to be executed in
762 // parallel (or back-to-back in a pipeline) instead of depending on each other.
763 
764 // FIXME: This has the potential to be expensive (compile time) while not
765 // improving the code at all. Some ways to limit the overhead:
766 // 1. Track successful transforms; bail out if hit rate gets too low.
767 // 2. Only enable at -O3 or some other non-default optimization level.
768 // 3. Pre-screen pattern candidates here: if an operand of the previous
769 //    instruction is known to not increase the critical path, then don't match
770 //    that pattern.
771 bool TargetInstrInfo::getMachineCombinerPatterns(
772     MachineInstr &Root,
773     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
774   bool Commute;
775   if (isReassociationCandidate(Root, Commute)) {
776     // We found a sequence of instructions that may be suitable for a
777     // reassociation of operands to increase ILP. Specify each commutation
778     // possibility for the Prev instruction in the sequence and let the
779     // machine combiner decide if changing the operands is worthwhile.
780     if (Commute) {
781       Patterns.push_back(MachineCombinerPattern::REASSOC_AX_YB);
782       Patterns.push_back(MachineCombinerPattern::REASSOC_XA_YB);
783     } else {
784       Patterns.push_back(MachineCombinerPattern::REASSOC_AX_BY);
785       Patterns.push_back(MachineCombinerPattern::REASSOC_XA_BY);
786     }
787     return true;
788   }
789 
790   return false;
791 }
792 
793 /// Return true when a code sequence can improve loop throughput.
794 bool
795 TargetInstrInfo::isThroughputPattern(MachineCombinerPattern Pattern) const {
796   return false;
797 }
798 
799 /// Attempt the reassociation transformation to reduce critical path length.
800 /// See the above comments before getMachineCombinerPatterns().
801 void TargetInstrInfo::reassociateOps(
802     MachineInstr &Root, MachineInstr &Prev,
803     MachineCombinerPattern Pattern,
804     SmallVectorImpl<MachineInstr *> &InsInstrs,
805     SmallVectorImpl<MachineInstr *> &DelInstrs,
806     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
807   MachineFunction *MF = Root.getMF();
808   MachineRegisterInfo &MRI = MF->getRegInfo();
809   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
810   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
811   const TargetRegisterClass *RC = Root.getRegClassConstraint(0, TII, TRI);
812 
813   // This array encodes the operand index for each parameter because the
814   // operands may be commuted. Each row corresponds to a pattern value,
815   // and each column specifies the index of A, B, X, Y.
816   unsigned OpIdx[4][4] = {
817     { 1, 1, 2, 2 },
818     { 1, 2, 2, 1 },
819     { 2, 1, 1, 2 },
820     { 2, 2, 1, 1 }
821   };
822 
823   int Row;
824   switch (Pattern) {
825   case MachineCombinerPattern::REASSOC_AX_BY: Row = 0; break;
826   case MachineCombinerPattern::REASSOC_AX_YB: Row = 1; break;
827   case MachineCombinerPattern::REASSOC_XA_BY: Row = 2; break;
828   case MachineCombinerPattern::REASSOC_XA_YB: Row = 3; break;
829   default: llvm_unreachable("unexpected MachineCombinerPattern");
830   }
831 
832   MachineOperand &OpA = Prev.getOperand(OpIdx[Row][0]);
833   MachineOperand &OpB = Root.getOperand(OpIdx[Row][1]);
834   MachineOperand &OpX = Prev.getOperand(OpIdx[Row][2]);
835   MachineOperand &OpY = Root.getOperand(OpIdx[Row][3]);
836   MachineOperand &OpC = Root.getOperand(0);
837 
838   Register RegA = OpA.getReg();
839   Register RegB = OpB.getReg();
840   Register RegX = OpX.getReg();
841   Register RegY = OpY.getReg();
842   Register RegC = OpC.getReg();
843 
844   if (Register::isVirtualRegister(RegA))
845     MRI.constrainRegClass(RegA, RC);
846   if (Register::isVirtualRegister(RegB))
847     MRI.constrainRegClass(RegB, RC);
848   if (Register::isVirtualRegister(RegX))
849     MRI.constrainRegClass(RegX, RC);
850   if (Register::isVirtualRegister(RegY))
851     MRI.constrainRegClass(RegY, RC);
852   if (Register::isVirtualRegister(RegC))
853     MRI.constrainRegClass(RegC, RC);
854 
855   // Create a new virtual register for the result of (X op Y) instead of
856   // recycling RegB because the MachineCombiner's computation of the critical
857   // path requires a new register definition rather than an existing one.
858   Register NewVR = MRI.createVirtualRegister(RC);
859   InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
860 
861   unsigned Opcode = Root.getOpcode();
862   bool KillA = OpA.isKill();
863   bool KillX = OpX.isKill();
864   bool KillY = OpY.isKill();
865 
866   // Create new instructions for insertion.
867   MachineInstrBuilder MIB1 =
868       BuildMI(*MF, Prev.getDebugLoc(), TII->get(Opcode), NewVR)
869           .addReg(RegX, getKillRegState(KillX))
870           .addReg(RegY, getKillRegState(KillY));
871   MachineInstrBuilder MIB2 =
872       BuildMI(*MF, Root.getDebugLoc(), TII->get(Opcode), RegC)
873           .addReg(RegA, getKillRegState(KillA))
874           .addReg(NewVR, getKillRegState(true));
875 
876   setSpecialOperandAttr(Root, Prev, *MIB1, *MIB2);
877 
878   // Record new instructions for insertion and old instructions for deletion.
879   InsInstrs.push_back(MIB1);
880   InsInstrs.push_back(MIB2);
881   DelInstrs.push_back(&Prev);
882   DelInstrs.push_back(&Root);
883 }
884 
885 void TargetInstrInfo::genAlternativeCodeSequence(
886     MachineInstr &Root, MachineCombinerPattern Pattern,
887     SmallVectorImpl<MachineInstr *> &InsInstrs,
888     SmallVectorImpl<MachineInstr *> &DelInstrs,
889     DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const {
890   MachineRegisterInfo &MRI = Root.getMF()->getRegInfo();
891 
892   // Select the previous instruction in the sequence based on the input pattern.
893   MachineInstr *Prev = nullptr;
894   switch (Pattern) {
895   case MachineCombinerPattern::REASSOC_AX_BY:
896   case MachineCombinerPattern::REASSOC_XA_BY:
897     Prev = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
898     break;
899   case MachineCombinerPattern::REASSOC_AX_YB:
900   case MachineCombinerPattern::REASSOC_XA_YB:
901     Prev = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
902     break;
903   default:
904     break;
905   }
906 
907   assert(Prev && "Unknown pattern for machine combiner");
908 
909   reassociateOps(Root, *Prev, Pattern, InsInstrs, DelInstrs, InstIdxForVirtReg);
910 }
911 
912 bool TargetInstrInfo::isReallyTriviallyReMaterializableGeneric(
913     const MachineInstr &MI, AAResults *AA) const {
914   const MachineFunction &MF = *MI.getMF();
915   const MachineRegisterInfo &MRI = MF.getRegInfo();
916 
917   // Remat clients assume operand 0 is the defined register.
918   if (!MI.getNumOperands() || !MI.getOperand(0).isReg())
919     return false;
920   Register DefReg = MI.getOperand(0).getReg();
921 
922   // A sub-register definition can only be rematerialized if the instruction
923   // doesn't read the other parts of the register.  Otherwise it is really a
924   // read-modify-write operation on the full virtual register which cannot be
925   // moved safely.
926   if (Register::isVirtualRegister(DefReg) && MI.getOperand(0).getSubReg() &&
927       MI.readsVirtualRegister(DefReg))
928     return false;
929 
930   // A load from a fixed stack slot can be rematerialized. This may be
931   // redundant with subsequent checks, but it's target-independent,
932   // simple, and a common case.
933   int FrameIdx = 0;
934   if (isLoadFromStackSlot(MI, FrameIdx) &&
935       MF.getFrameInfo().isImmutableObjectIndex(FrameIdx))
936     return true;
937 
938   // Avoid instructions obviously unsafe for remat.
939   if (MI.isNotDuplicable() || MI.mayStore() || MI.mayRaiseFPException() ||
940       MI.hasUnmodeledSideEffects())
941     return false;
942 
943   // Don't remat inline asm. We have no idea how expensive it is
944   // even if it's side effect free.
945   if (MI.isInlineAsm())
946     return false;
947 
948   // Avoid instructions which load from potentially varying memory.
949   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA))
950     return false;
951 
952   // If any of the registers accessed are non-constant, conservatively assume
953   // the instruction is not rematerializable.
954   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
955     const MachineOperand &MO = MI.getOperand(i);
956     if (!MO.isReg()) continue;
957     Register Reg = MO.getReg();
958     if (Reg == 0)
959       continue;
960 
961     // Check for a well-behaved physical register.
962     if (Register::isPhysicalRegister(Reg)) {
963       if (MO.isUse()) {
964         // If the physreg has no defs anywhere, it's just an ambient register
965         // and we can freely move its uses. Alternatively, if it's allocatable,
966         // it could get allocated to something with a def during allocation.
967         if (!MRI.isConstantPhysReg(Reg))
968           return false;
969       } else {
970         // A physreg def. We can't remat it.
971         return false;
972       }
973       continue;
974     }
975 
976     // Only allow one virtual-register def.  There may be multiple defs of the
977     // same virtual register, though.
978     if (MO.isDef() && Reg != DefReg)
979       return false;
980 
981     // Don't allow any virtual-register uses. Rematting an instruction with
982     // virtual register uses would length the live ranges of the uses, which
983     // is not necessarily a good idea, certainly not "trivial".
984     if (MO.isUse())
985       return false;
986   }
987 
988   // Everything checked out.
989   return true;
990 }
991 
992 int TargetInstrInfo::getSPAdjust(const MachineInstr &MI) const {
993   const MachineFunction *MF = MI.getMF();
994   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
995   bool StackGrowsDown =
996     TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
997 
998   unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
999   unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
1000 
1001   if (!isFrameInstr(MI))
1002     return 0;
1003 
1004   int SPAdj = TFI->alignSPAdjust(getFrameSize(MI));
1005 
1006   if ((!StackGrowsDown && MI.getOpcode() == FrameSetupOpcode) ||
1007       (StackGrowsDown && MI.getOpcode() == FrameDestroyOpcode))
1008     SPAdj = -SPAdj;
1009 
1010   return SPAdj;
1011 }
1012 
1013 /// isSchedulingBoundary - Test if the given instruction should be
1014 /// considered a scheduling boundary. This primarily includes labels
1015 /// and terminators.
1016 bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1017                                            const MachineBasicBlock *MBB,
1018                                            const MachineFunction &MF) const {
1019   // Terminators and labels can't be scheduled around.
1020   if (MI.isTerminator() || MI.isPosition())
1021     return true;
1022 
1023   // INLINEASM_BR can jump to another block
1024   if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
1025     return true;
1026 
1027   // Don't attempt to schedule around any instruction that defines
1028   // a stack-oriented pointer, as it's unlikely to be profitable. This
1029   // saves compile time, because it doesn't require every single
1030   // stack slot reference to depend on the instruction that does the
1031   // modification.
1032   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1033   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1034   return MI.modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI);
1035 }
1036 
1037 // Provide a global flag for disabling the PreRA hazard recognizer that targets
1038 // may choose to honor.
1039 bool TargetInstrInfo::usePreRAHazardRecognizer() const {
1040   return !DisableHazardRecognizer;
1041 }
1042 
1043 // Default implementation of CreateTargetRAHazardRecognizer.
1044 ScheduleHazardRecognizer *TargetInstrInfo::
1045 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1046                              const ScheduleDAG *DAG) const {
1047   // Dummy hazard recognizer allows all instructions to issue.
1048   return new ScheduleHazardRecognizer();
1049 }
1050 
1051 // Default implementation of CreateTargetMIHazardRecognizer.
1052 ScheduleHazardRecognizer *TargetInstrInfo::CreateTargetMIHazardRecognizer(
1053     const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
1054   return new ScoreboardHazardRecognizer(II, DAG, "machine-scheduler");
1055 }
1056 
1057 // Default implementation of CreateTargetPostRAHazardRecognizer.
1058 ScheduleHazardRecognizer *TargetInstrInfo::
1059 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
1060                                    const ScheduleDAG *DAG) const {
1061   return new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
1062 }
1063 
1064 // Default implementation of getMemOperandWithOffset.
1065 bool TargetInstrInfo::getMemOperandWithOffset(
1066     const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset,
1067     bool &OffsetIsScalable, const TargetRegisterInfo *TRI) const {
1068   SmallVector<const MachineOperand *, 4> BaseOps;
1069   unsigned Width;
1070   if (!getMemOperandsWithOffsetWidth(MI, BaseOps, Offset, OffsetIsScalable,
1071                                      Width, TRI) ||
1072       BaseOps.size() != 1)
1073     return false;
1074   BaseOp = BaseOps.front();
1075   return true;
1076 }
1077 
1078 //===----------------------------------------------------------------------===//
1079 //  SelectionDAG latency interface.
1080 //===----------------------------------------------------------------------===//
1081 
1082 int
1083 TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1084                                    SDNode *DefNode, unsigned DefIdx,
1085                                    SDNode *UseNode, unsigned UseIdx) const {
1086   if (!ItinData || ItinData->isEmpty())
1087     return -1;
1088 
1089   if (!DefNode->isMachineOpcode())
1090     return -1;
1091 
1092   unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
1093   if (!UseNode->isMachineOpcode())
1094     return ItinData->getOperandCycle(DefClass, DefIdx);
1095   unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
1096   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1097 }
1098 
1099 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1100                                      SDNode *N) const {
1101   if (!ItinData || ItinData->isEmpty())
1102     return 1;
1103 
1104   if (!N->isMachineOpcode())
1105     return 1;
1106 
1107   return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
1108 }
1109 
1110 //===----------------------------------------------------------------------===//
1111 //  MachineInstr latency interface.
1112 //===----------------------------------------------------------------------===//
1113 
1114 unsigned TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1115                                          const MachineInstr &MI) const {
1116   if (!ItinData || ItinData->isEmpty())
1117     return 1;
1118 
1119   unsigned Class = MI.getDesc().getSchedClass();
1120   int UOps = ItinData->Itineraries[Class].NumMicroOps;
1121   if (UOps >= 0)
1122     return UOps;
1123 
1124   // The # of u-ops is dynamically determined. The specific target should
1125   // override this function to return the right number.
1126   return 1;
1127 }
1128 
1129 /// Return the default expected latency for a def based on it's opcode.
1130 unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
1131                                             const MachineInstr &DefMI) const {
1132   if (DefMI.isTransient())
1133     return 0;
1134   if (DefMI.mayLoad())
1135     return SchedModel.LoadLatency;
1136   if (isHighLatencyDef(DefMI.getOpcode()))
1137     return SchedModel.HighLatency;
1138   return 1;
1139 }
1140 
1141 unsigned TargetInstrInfo::getPredicationCost(const MachineInstr &) const {
1142   return 0;
1143 }
1144 
1145 unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1146                                           const MachineInstr &MI,
1147                                           unsigned *PredCost) const {
1148   // Default to one cycle for no itinerary. However, an "empty" itinerary may
1149   // still have a MinLatency property, which getStageLatency checks.
1150   if (!ItinData)
1151     return MI.mayLoad() ? 2 : 1;
1152 
1153   return ItinData->getStageLatency(MI.getDesc().getSchedClass());
1154 }
1155 
1156 bool TargetInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
1157                                        const MachineInstr &DefMI,
1158                                        unsigned DefIdx) const {
1159   const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
1160   if (!ItinData || ItinData->isEmpty())
1161     return false;
1162 
1163   unsigned DefClass = DefMI.getDesc().getSchedClass();
1164   int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
1165   return (DefCycle != -1 && DefCycle <= 1);
1166 }
1167 
1168 Optional<ParamLoadedValue>
1169 TargetInstrInfo::describeLoadedValue(const MachineInstr &MI,
1170                                      Register Reg) const {
1171   const MachineFunction *MF = MI.getMF();
1172   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1173   DIExpression *Expr = DIExpression::get(MF->getFunction().getContext(), {});
1174   int64_t Offset;
1175   bool OffsetIsScalable;
1176 
1177   // To simplify the sub-register handling, verify that we only need to
1178   // consider physical registers.
1179   assert(MF->getProperties().hasProperty(
1180       MachineFunctionProperties::Property::NoVRegs));
1181 
1182   if (auto DestSrc = isCopyInstr(MI)) {
1183     Register DestReg = DestSrc->Destination->getReg();
1184 
1185     // If the copy destination is the forwarding reg, describe the forwarding
1186     // reg using the copy source as the backup location. Example:
1187     //
1188     //   x0 = MOV x7
1189     //   call callee(x0)      ; x0 described as x7
1190     if (Reg == DestReg)
1191       return ParamLoadedValue(*DestSrc->Source, Expr);
1192 
1193     // Cases where super- or sub-registers needs to be described should
1194     // be handled by the target's hook implementation.
1195     assert(!TRI->isSuperOrSubRegisterEq(Reg, DestReg) &&
1196            "TargetInstrInfo::describeLoadedValue can't describe super- or "
1197            "sub-regs for copy instructions");
1198     return None;
1199   } else if (auto RegImm = isAddImmediate(MI, Reg)) {
1200     Register SrcReg = RegImm->Reg;
1201     Offset = RegImm->Imm;
1202     Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset, Offset);
1203     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
1204   } else if (MI.hasOneMemOperand()) {
1205     // Only describe memory which provably does not escape the function. As
1206     // described in llvm.org/PR43343, escaped memory may be clobbered by the
1207     // callee (or by another thread).
1208     const auto &TII = MF->getSubtarget().getInstrInfo();
1209     const MachineFrameInfo &MFI = MF->getFrameInfo();
1210     const MachineMemOperand *MMO = MI.memoperands()[0];
1211     const PseudoSourceValue *PSV = MMO->getPseudoValue();
1212 
1213     // If the address points to "special" memory (e.g. a spill slot), it's
1214     // sufficient to check that it isn't aliased by any high-level IR value.
1215     if (!PSV || PSV->mayAlias(&MFI))
1216       return None;
1217 
1218     const MachineOperand *BaseOp;
1219     if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable,
1220                                       TRI))
1221       return None;
1222 
1223     // FIXME: Scalable offsets are not yet handled in the offset code below.
1224     if (OffsetIsScalable)
1225       return None;
1226 
1227     // TODO: Can currently only handle mem instructions with a single define.
1228     // An example from the x86 target:
1229     //    ...
1230     //    DIV64m $rsp, 1, $noreg, 24, $noreg, implicit-def dead $rax, implicit-def $rdx
1231     //    ...
1232     //
1233     if (MI.getNumExplicitDefs() != 1)
1234       return None;
1235 
1236     // TODO: In what way do we need to take Reg into consideration here?
1237 
1238     SmallVector<uint64_t, 8> Ops;
1239     DIExpression::appendOffset(Ops, Offset);
1240     Ops.push_back(dwarf::DW_OP_deref_size);
1241     Ops.push_back(MMO->getSize());
1242     Expr = DIExpression::prependOpcodes(Expr, Ops);
1243     return ParamLoadedValue(*BaseOp, Expr);
1244   }
1245 
1246   return None;
1247 }
1248 
1249 /// Both DefMI and UseMI must be valid.  By default, call directly to the
1250 /// itinerary. This may be overriden by the target.
1251 int TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1252                                        const MachineInstr &DefMI,
1253                                        unsigned DefIdx,
1254                                        const MachineInstr &UseMI,
1255                                        unsigned UseIdx) const {
1256   unsigned DefClass = DefMI.getDesc().getSchedClass();
1257   unsigned UseClass = UseMI.getDesc().getSchedClass();
1258   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1259 }
1260 
1261 /// If we can determine the operand latency from the def only, without itinerary
1262 /// lookup, do so. Otherwise return -1.
1263 int TargetInstrInfo::computeDefOperandLatency(
1264     const InstrItineraryData *ItinData, const MachineInstr &DefMI) const {
1265 
1266   // Let the target hook getInstrLatency handle missing itineraries.
1267   if (!ItinData)
1268     return getInstrLatency(ItinData, DefMI);
1269 
1270   if(ItinData->isEmpty())
1271     return defaultDefLatency(ItinData->SchedModel, DefMI);
1272 
1273   // ...operand lookup required
1274   return -1;
1275 }
1276 
1277 bool TargetInstrInfo::getRegSequenceInputs(
1278     const MachineInstr &MI, unsigned DefIdx,
1279     SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1280   assert((MI.isRegSequence() ||
1281           MI.isRegSequenceLike()) && "Instruction do not have the proper type");
1282 
1283   if (!MI.isRegSequence())
1284     return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
1285 
1286   // We are looking at:
1287   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1288   assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
1289   for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
1290        OpIdx += 2) {
1291     const MachineOperand &MOReg = MI.getOperand(OpIdx);
1292     if (MOReg.isUndef())
1293       continue;
1294     const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
1295     assert(MOSubIdx.isImm() &&
1296            "One of the subindex of the reg_sequence is not an immediate");
1297     // Record Reg:SubReg, SubIdx.
1298     InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
1299                                             (unsigned)MOSubIdx.getImm()));
1300   }
1301   return true;
1302 }
1303 
1304 bool TargetInstrInfo::getExtractSubregInputs(
1305     const MachineInstr &MI, unsigned DefIdx,
1306     RegSubRegPairAndIdx &InputReg) const {
1307   assert((MI.isExtractSubreg() ||
1308       MI.isExtractSubregLike()) && "Instruction do not have the proper type");
1309 
1310   if (!MI.isExtractSubreg())
1311     return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
1312 
1313   // We are looking at:
1314   // Def = EXTRACT_SUBREG v0.sub1, sub0.
1315   assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
1316   const MachineOperand &MOReg = MI.getOperand(1);
1317   if (MOReg.isUndef())
1318     return false;
1319   const MachineOperand &MOSubIdx = MI.getOperand(2);
1320   assert(MOSubIdx.isImm() &&
1321          "The subindex of the extract_subreg is not an immediate");
1322 
1323   InputReg.Reg = MOReg.getReg();
1324   InputReg.SubReg = MOReg.getSubReg();
1325   InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
1326   return true;
1327 }
1328 
1329 bool TargetInstrInfo::getInsertSubregInputs(
1330     const MachineInstr &MI, unsigned DefIdx,
1331     RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
1332   assert((MI.isInsertSubreg() ||
1333       MI.isInsertSubregLike()) && "Instruction do not have the proper type");
1334 
1335   if (!MI.isInsertSubreg())
1336     return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
1337 
1338   // We are looking at:
1339   // Def = INSERT_SEQUENCE v0, v1, sub0.
1340   assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
1341   const MachineOperand &MOBaseReg = MI.getOperand(1);
1342   const MachineOperand &MOInsertedReg = MI.getOperand(2);
1343   if (MOInsertedReg.isUndef())
1344     return false;
1345   const MachineOperand &MOSubIdx = MI.getOperand(3);
1346   assert(MOSubIdx.isImm() &&
1347          "One of the subindex of the reg_sequence is not an immediate");
1348   BaseReg.Reg = MOBaseReg.getReg();
1349   BaseReg.SubReg = MOBaseReg.getSubReg();
1350 
1351   InsertedReg.Reg = MOInsertedReg.getReg();
1352   InsertedReg.SubReg = MOInsertedReg.getSubReg();
1353   InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
1354   return true;
1355 }
1356 
1357 // Returns a MIRPrinter comment for this machine operand.
1358 std::string TargetInstrInfo::createMIROperandComment(
1359     const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
1360     const TargetRegisterInfo *TRI) const {
1361 
1362   if (!MI.isInlineAsm())
1363     return "";
1364 
1365   std::string Flags;
1366   raw_string_ostream OS(Flags);
1367 
1368   if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
1369     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1370     unsigned ExtraInfo = Op.getImm();
1371     bool First = true;
1372     for (StringRef Info : InlineAsm::getExtraInfoNames(ExtraInfo)) {
1373       if (!First)
1374         OS << " ";
1375       First = false;
1376       OS << Info;
1377     }
1378 
1379     return OS.str();
1380   }
1381 
1382   int FlagIdx = MI.findInlineAsmFlagIdx(OpIdx);
1383   if (FlagIdx < 0 || (unsigned)FlagIdx != OpIdx)
1384     return "";
1385 
1386   assert(Op.isImm() && "Expected flag operand to be an immediate");
1387   // Pretty print the inline asm operand descriptor.
1388   unsigned Flag = Op.getImm();
1389   unsigned Kind = InlineAsm::getKind(Flag);
1390   OS << InlineAsm::getKindName(Kind);
1391 
1392   unsigned RCID = 0;
1393   if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1394       InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1395     if (TRI) {
1396       OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1397     } else
1398       OS << ":RC" << RCID;
1399   }
1400 
1401   if (InlineAsm::isMemKind(Flag)) {
1402     unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1403     OS << ":" << InlineAsm::getMemConstraintName(MCID);
1404   }
1405 
1406   unsigned TiedTo = 0;
1407   if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1408     OS << " tiedto:$" << TiedTo;
1409 
1410   return OS.str();
1411 }
1412 
1413 TargetInstrInfo::PipelinerLoopInfo::~PipelinerLoopInfo() {}
1414