• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
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 // Methods common to all machine instructions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/MachineInstr.h"
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/Loads.h"
25 #include "llvm/Analysis/MemoryLocation.h"
26 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineInstrBundle.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/CodeGen/StackMaps.h"
38 #include "llvm/CodeGen/TargetInstrInfo.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/Config/llvm-config.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DebugInfoMetadata.h"
44 #include "llvm/IR/DebugLoc.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/InstrTypes.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/IR/ModuleSlotTracker.h"
54 #include "llvm/IR/Operator.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/IR/Value.h"
57 #include "llvm/MC/MCInstrDesc.h"
58 #include "llvm/MC/MCRegisterInfo.h"
59 #include "llvm/MC/MCSymbol.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Compiler.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/FormattedStream.h"
66 #include "llvm/Support/LowLevelTypeImpl.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetIntrinsicInfo.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include <algorithm>
72 #include <cassert>
73 #include <cstddef>
74 #include <cstdint>
75 #include <cstring>
76 #include <iterator>
77 #include <utility>
78 
79 using namespace llvm;
80 
getMFIfAvailable(const MachineInstr & MI)81 static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
82   if (const MachineBasicBlock *MBB = MI.getParent())
83     if (const MachineFunction *MF = MBB->getParent())
84       return MF;
85   return nullptr;
86 }
87 
88 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
89 // it.
tryToGetTargetInfo(const MachineInstr & MI,const TargetRegisterInfo * & TRI,const MachineRegisterInfo * & MRI,const TargetIntrinsicInfo * & IntrinsicInfo,const TargetInstrInfo * & TII)90 static void tryToGetTargetInfo(const MachineInstr &MI,
91                                const TargetRegisterInfo *&TRI,
92                                const MachineRegisterInfo *&MRI,
93                                const TargetIntrinsicInfo *&IntrinsicInfo,
94                                const TargetInstrInfo *&TII) {
95 
96   if (const MachineFunction *MF = getMFIfAvailable(MI)) {
97     TRI = MF->getSubtarget().getRegisterInfo();
98     MRI = &MF->getRegInfo();
99     IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
100     TII = MF->getSubtarget().getInstrInfo();
101   }
102 }
103 
addImplicitDefUseOperands(MachineFunction & MF)104 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
105   if (MCID->ImplicitDefs)
106     for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
107            ++ImpDefs)
108       addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
109   if (MCID->ImplicitUses)
110     for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
111            ++ImpUses)
112       addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
113 }
114 
115 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
116 /// implicit operands. It reserves space for the number of operands specified by
117 /// the MCInstrDesc.
MachineInstr(MachineFunction & MF,const MCInstrDesc & tid,DebugLoc dl,bool NoImp)118 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
119                            DebugLoc dl, bool NoImp)
120     : MCID(&tid), debugLoc(std::move(dl)), DebugInstrNum(0) {
121   assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
122 
123   // Reserve space for the expected number of operands.
124   if (unsigned NumOps = MCID->getNumOperands() +
125     MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
126     CapOperands = OperandCapacity::get(NumOps);
127     Operands = MF.allocateOperandArray(CapOperands);
128   }
129 
130   if (!NoImp)
131     addImplicitDefUseOperands(MF);
132 }
133 
134 /// MachineInstr ctor - Copies MachineInstr arg exactly.
135 /// Does not copy the number from debug instruction numbering, to preserve
136 /// uniqueness.
MachineInstr(MachineFunction & MF,const MachineInstr & MI)137 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
138     : MCID(&MI.getDesc()), Info(MI.Info), debugLoc(MI.getDebugLoc()),
139       DebugInstrNum(0) {
140   assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
141 
142   CapOperands = OperandCapacity::get(MI.getNumOperands());
143   Operands = MF.allocateOperandArray(CapOperands);
144 
145   // Copy operands.
146   for (const MachineOperand &MO : MI.operands())
147     addOperand(MF, MO);
148 
149   // Copy all the sensible flags.
150   setFlags(MI.Flags);
151 }
152 
moveBefore(MachineInstr * MovePos)153 void MachineInstr::moveBefore(MachineInstr *MovePos) {
154   MovePos->getParent()->splice(MovePos, getParent(), getIterator());
155 }
156 
157 /// getRegInfo - If this instruction is embedded into a MachineFunction,
158 /// return the MachineRegisterInfo object for the current function, otherwise
159 /// return null.
getRegInfo()160 MachineRegisterInfo *MachineInstr::getRegInfo() {
161   if (MachineBasicBlock *MBB = getParent())
162     return &MBB->getParent()->getRegInfo();
163   return nullptr;
164 }
165 
166 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
167 /// this instruction from their respective use lists.  This requires that the
168 /// operands already be on their use lists.
RemoveRegOperandsFromUseLists(MachineRegisterInfo & MRI)169 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
170   for (MachineOperand &MO : operands())
171     if (MO.isReg())
172       MRI.removeRegOperandFromUseList(&MO);
173 }
174 
175 /// AddRegOperandsToUseLists - Add all of the register operands in
176 /// this instruction from their respective use lists.  This requires that the
177 /// operands not be on their use lists yet.
AddRegOperandsToUseLists(MachineRegisterInfo & MRI)178 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
179   for (MachineOperand &MO : operands())
180     if (MO.isReg())
181       MRI.addRegOperandToUseList(&MO);
182 }
183 
addOperand(const MachineOperand & Op)184 void MachineInstr::addOperand(const MachineOperand &Op) {
185   MachineBasicBlock *MBB = getParent();
186   assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
187   MachineFunction *MF = MBB->getParent();
188   assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
189   addOperand(*MF, Op);
190 }
191 
192 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
193 /// ranges. If MRI is non-null also update use-def chains.
moveOperands(MachineOperand * Dst,MachineOperand * Src,unsigned NumOps,MachineRegisterInfo * MRI)194 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
195                          unsigned NumOps, MachineRegisterInfo *MRI) {
196   if (MRI)
197     return MRI->moveOperands(Dst, Src, NumOps);
198   // MachineOperand is a trivially copyable type so we can just use memmove.
199   assert(Dst && Src && "Unknown operands");
200   std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
201 }
202 
203 /// addOperand - Add the specified operand to the instruction.  If it is an
204 /// implicit operand, it is added to the end of the operand list.  If it is
205 /// an explicit operand it is added at the end of the explicit operand list
206 /// (before the first implicit operand).
addOperand(MachineFunction & MF,const MachineOperand & Op)207 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
208   assert(MCID && "Cannot add operands before providing an instr descriptor");
209 
210   // Check if we're adding one of our existing operands.
211   if (&Op >= Operands && &Op < Operands + NumOperands) {
212     // This is unusual: MI->addOperand(MI->getOperand(i)).
213     // If adding Op requires reallocating or moving existing operands around,
214     // the Op reference could go stale. Support it by copying Op.
215     MachineOperand CopyOp(Op);
216     return addOperand(MF, CopyOp);
217   }
218 
219   // Find the insert location for the new operand.  Implicit registers go at
220   // the end, everything else goes before the implicit regs.
221   //
222   // FIXME: Allow mixed explicit and implicit operands on inline asm.
223   // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
224   // implicit-defs, but they must not be moved around.  See the FIXME in
225   // InstrEmitter.cpp.
226   unsigned OpNo = getNumOperands();
227   bool isImpReg = Op.isReg() && Op.isImplicit();
228   if (!isImpReg && !isInlineAsm()) {
229     while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
230       --OpNo;
231       assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
232     }
233   }
234 
235 #ifndef NDEBUG
236   bool isDebugOp = Op.getType() == MachineOperand::MO_Metadata ||
237                    Op.getType() == MachineOperand::MO_MCSymbol;
238   // OpNo now points as the desired insertion point.  Unless this is a variadic
239   // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
240   // RegMask operands go between the explicit and implicit operands.
241   assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
242           OpNo < MCID->getNumOperands() || isDebugOp) &&
243          "Trying to add an operand to a machine instr that is already done!");
244 #endif
245 
246   MachineRegisterInfo *MRI = getRegInfo();
247 
248   // Determine if the Operands array needs to be reallocated.
249   // Save the old capacity and operand array.
250   OperandCapacity OldCap = CapOperands;
251   MachineOperand *OldOperands = Operands;
252   if (!OldOperands || OldCap.getSize() == getNumOperands()) {
253     CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
254     Operands = MF.allocateOperandArray(CapOperands);
255     // Move the operands before the insertion point.
256     if (OpNo)
257       moveOperands(Operands, OldOperands, OpNo, MRI);
258   }
259 
260   // Move the operands following the insertion point.
261   if (OpNo != NumOperands)
262     moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
263                  MRI);
264   ++NumOperands;
265 
266   // Deallocate the old operand array.
267   if (OldOperands != Operands && OldOperands)
268     MF.deallocateOperandArray(OldCap, OldOperands);
269 
270   // Copy Op into place. It still needs to be inserted into the MRI use lists.
271   MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
272   NewMO->ParentMI = this;
273 
274   // When adding a register operand, tell MRI about it.
275   if (NewMO->isReg()) {
276     // Ensure isOnRegUseList() returns false, regardless of Op's status.
277     NewMO->Contents.Reg.Prev = nullptr;
278     // Ignore existing ties. This is not a property that can be copied.
279     NewMO->TiedTo = 0;
280     // Add the new operand to MRI, but only for instructions in an MBB.
281     if (MRI)
282       MRI->addRegOperandToUseList(NewMO);
283     // The MCID operand information isn't accurate until we start adding
284     // explicit operands. The implicit operands are added first, then the
285     // explicits are inserted before them.
286     if (!isImpReg) {
287       // Tie uses to defs as indicated in MCInstrDesc.
288       if (NewMO->isUse()) {
289         int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
290         if (DefIdx != -1)
291           tieOperands(DefIdx, OpNo);
292       }
293       // If the register operand is flagged as early, mark the operand as such.
294       if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
295         NewMO->setIsEarlyClobber(true);
296     }
297   }
298 }
299 
300 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
301 /// fewer operand than it started with.
302 ///
RemoveOperand(unsigned OpNo)303 void MachineInstr::RemoveOperand(unsigned OpNo) {
304   assert(OpNo < getNumOperands() && "Invalid operand number");
305   untieRegOperand(OpNo);
306 
307 #ifndef NDEBUG
308   // Moving tied operands would break the ties.
309   for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
310     if (Operands[i].isReg())
311       assert(!Operands[i].isTied() && "Cannot move tied operands");
312 #endif
313 
314   MachineRegisterInfo *MRI = getRegInfo();
315   if (MRI && Operands[OpNo].isReg())
316     MRI->removeRegOperandFromUseList(Operands + OpNo);
317 
318   // Don't call the MachineOperand destructor. A lot of this code depends on
319   // MachineOperand having a trivial destructor anyway, and adding a call here
320   // wouldn't make it 'destructor-correct'.
321 
322   if (unsigned N = NumOperands - 1 - OpNo)
323     moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
324   --NumOperands;
325 }
326 
setExtraInfo(MachineFunction & MF,ArrayRef<MachineMemOperand * > MMOs,MCSymbol * PreInstrSymbol,MCSymbol * PostInstrSymbol,MDNode * HeapAllocMarker)327 void MachineInstr::setExtraInfo(MachineFunction &MF,
328                                 ArrayRef<MachineMemOperand *> MMOs,
329                                 MCSymbol *PreInstrSymbol,
330                                 MCSymbol *PostInstrSymbol,
331                                 MDNode *HeapAllocMarker) {
332   bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
333   bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
334   bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
335   int NumPointers =
336       MMOs.size() + HasPreInstrSymbol + HasPostInstrSymbol + HasHeapAllocMarker;
337 
338   // Drop all extra info if there is none.
339   if (NumPointers <= 0) {
340     Info.clear();
341     return;
342   }
343 
344   // If more than one pointer, then store out of line. Store heap alloc markers
345   // out of line because PointerSumType cannot hold more than 4 tag types with
346   // 32-bit pointers.
347   // FIXME: Maybe we should make the symbols in the extra info mutable?
348   else if (NumPointers > 1 || HasHeapAllocMarker) {
349     Info.set<EIIK_OutOfLine>(MF.createMIExtraInfo(
350         MMOs, PreInstrSymbol, PostInstrSymbol, HeapAllocMarker));
351     return;
352   }
353 
354   // Otherwise store the single pointer inline.
355   if (HasPreInstrSymbol)
356     Info.set<EIIK_PreInstrSymbol>(PreInstrSymbol);
357   else if (HasPostInstrSymbol)
358     Info.set<EIIK_PostInstrSymbol>(PostInstrSymbol);
359   else
360     Info.set<EIIK_MMO>(MMOs[0]);
361 }
362 
dropMemRefs(MachineFunction & MF)363 void MachineInstr::dropMemRefs(MachineFunction &MF) {
364   if (memoperands_empty())
365     return;
366 
367   setExtraInfo(MF, {}, getPreInstrSymbol(), getPostInstrSymbol(),
368                getHeapAllocMarker());
369 }
370 
setMemRefs(MachineFunction & MF,ArrayRef<MachineMemOperand * > MMOs)371 void MachineInstr::setMemRefs(MachineFunction &MF,
372                               ArrayRef<MachineMemOperand *> MMOs) {
373   if (MMOs.empty()) {
374     dropMemRefs(MF);
375     return;
376   }
377 
378   setExtraInfo(MF, MMOs, getPreInstrSymbol(), getPostInstrSymbol(),
379                getHeapAllocMarker());
380 }
381 
addMemOperand(MachineFunction & MF,MachineMemOperand * MO)382 void MachineInstr::addMemOperand(MachineFunction &MF,
383                                  MachineMemOperand *MO) {
384   SmallVector<MachineMemOperand *, 2> MMOs;
385   MMOs.append(memoperands_begin(), memoperands_end());
386   MMOs.push_back(MO);
387   setMemRefs(MF, MMOs);
388 }
389 
cloneMemRefs(MachineFunction & MF,const MachineInstr & MI)390 void MachineInstr::cloneMemRefs(MachineFunction &MF, const MachineInstr &MI) {
391   if (this == &MI)
392     // Nothing to do for a self-clone!
393     return;
394 
395   assert(&MF == MI.getMF() &&
396          "Invalid machine functions when cloning memory refrences!");
397   // See if we can just steal the extra info already allocated for the
398   // instruction. We can do this whenever the pre- and post-instruction symbols
399   // are the same (including null).
400   if (getPreInstrSymbol() == MI.getPreInstrSymbol() &&
401       getPostInstrSymbol() == MI.getPostInstrSymbol() &&
402       getHeapAllocMarker() == MI.getHeapAllocMarker()) {
403     Info = MI.Info;
404     return;
405   }
406 
407   // Otherwise, fall back on a copy-based clone.
408   setMemRefs(MF, MI.memoperands());
409 }
410 
411 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
412 /// identical.
hasIdenticalMMOs(ArrayRef<MachineMemOperand * > LHS,ArrayRef<MachineMemOperand * > RHS)413 static bool hasIdenticalMMOs(ArrayRef<MachineMemOperand *> LHS,
414                              ArrayRef<MachineMemOperand *> RHS) {
415   if (LHS.size() != RHS.size())
416     return false;
417 
418   auto LHSPointees = make_pointee_range(LHS);
419   auto RHSPointees = make_pointee_range(RHS);
420   return std::equal(LHSPointees.begin(), LHSPointees.end(),
421                     RHSPointees.begin());
422 }
423 
cloneMergedMemRefs(MachineFunction & MF,ArrayRef<const MachineInstr * > MIs)424 void MachineInstr::cloneMergedMemRefs(MachineFunction &MF,
425                                       ArrayRef<const MachineInstr *> MIs) {
426   // Try handling easy numbers of MIs with simpler mechanisms.
427   if (MIs.empty()) {
428     dropMemRefs(MF);
429     return;
430   }
431   if (MIs.size() == 1) {
432     cloneMemRefs(MF, *MIs[0]);
433     return;
434   }
435   // Because an empty memoperands list provides *no* information and must be
436   // handled conservatively (assuming the instruction can do anything), the only
437   // way to merge with it is to drop all other memoperands.
438   if (MIs[0]->memoperands_empty()) {
439     dropMemRefs(MF);
440     return;
441   }
442 
443   // Handle the general case.
444   SmallVector<MachineMemOperand *, 2> MergedMMOs;
445   // Start with the first instruction.
446   assert(&MF == MIs[0]->getMF() &&
447          "Invalid machine functions when cloning memory references!");
448   MergedMMOs.append(MIs[0]->memoperands_begin(), MIs[0]->memoperands_end());
449   // Now walk all the other instructions and accumulate any different MMOs.
450   for (const MachineInstr &MI : make_pointee_range(MIs.slice(1))) {
451     assert(&MF == MI.getMF() &&
452            "Invalid machine functions when cloning memory references!");
453 
454     // Skip MIs with identical operands to the first. This is a somewhat
455     // arbitrary hack but will catch common cases without being quadratic.
456     // TODO: We could fully implement merge semantics here if needed.
457     if (hasIdenticalMMOs(MIs[0]->memoperands(), MI.memoperands()))
458       continue;
459 
460     // Because an empty memoperands list provides *no* information and must be
461     // handled conservatively (assuming the instruction can do anything), the
462     // only way to merge with it is to drop all other memoperands.
463     if (MI.memoperands_empty()) {
464       dropMemRefs(MF);
465       return;
466     }
467 
468     // Otherwise accumulate these into our temporary buffer of the merged state.
469     MergedMMOs.append(MI.memoperands_begin(), MI.memoperands_end());
470   }
471 
472   setMemRefs(MF, MergedMMOs);
473 }
474 
setPreInstrSymbol(MachineFunction & MF,MCSymbol * Symbol)475 void MachineInstr::setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
476   // Do nothing if old and new symbols are the same.
477   if (Symbol == getPreInstrSymbol())
478     return;
479 
480   // If there was only one symbol and we're removing it, just clear info.
481   if (!Symbol && Info.is<EIIK_PreInstrSymbol>()) {
482     Info.clear();
483     return;
484   }
485 
486   setExtraInfo(MF, memoperands(), Symbol, getPostInstrSymbol(),
487                getHeapAllocMarker());
488 }
489 
setPostInstrSymbol(MachineFunction & MF,MCSymbol * Symbol)490 void MachineInstr::setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
491   // Do nothing if old and new symbols are the same.
492   if (Symbol == getPostInstrSymbol())
493     return;
494 
495   // If there was only one symbol and we're removing it, just clear info.
496   if (!Symbol && Info.is<EIIK_PostInstrSymbol>()) {
497     Info.clear();
498     return;
499   }
500 
501   setExtraInfo(MF, memoperands(), getPreInstrSymbol(), Symbol,
502                getHeapAllocMarker());
503 }
504 
setHeapAllocMarker(MachineFunction & MF,MDNode * Marker)505 void MachineInstr::setHeapAllocMarker(MachineFunction &MF, MDNode *Marker) {
506   // Do nothing if old and new symbols are the same.
507   if (Marker == getHeapAllocMarker())
508     return;
509 
510   setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(),
511                Marker);
512 }
513 
cloneInstrSymbols(MachineFunction & MF,const MachineInstr & MI)514 void MachineInstr::cloneInstrSymbols(MachineFunction &MF,
515                                      const MachineInstr &MI) {
516   if (this == &MI)
517     // Nothing to do for a self-clone!
518     return;
519 
520   assert(&MF == MI.getMF() &&
521          "Invalid machine functions when cloning instruction symbols!");
522 
523   setPreInstrSymbol(MF, MI.getPreInstrSymbol());
524   setPostInstrSymbol(MF, MI.getPostInstrSymbol());
525   setHeapAllocMarker(MF, MI.getHeapAllocMarker());
526 }
527 
mergeFlagsWith(const MachineInstr & Other) const528 uint16_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
529   // For now, the just return the union of the flags. If the flags get more
530   // complicated over time, we might need more logic here.
531   return getFlags() | Other.getFlags();
532 }
533 
copyFlagsFromInstruction(const Instruction & I)534 uint16_t MachineInstr::copyFlagsFromInstruction(const Instruction &I) {
535   uint16_t MIFlags = 0;
536   // Copy the wrapping flags.
537   if (const OverflowingBinaryOperator *OB =
538           dyn_cast<OverflowingBinaryOperator>(&I)) {
539     if (OB->hasNoSignedWrap())
540       MIFlags |= MachineInstr::MIFlag::NoSWrap;
541     if (OB->hasNoUnsignedWrap())
542       MIFlags |= MachineInstr::MIFlag::NoUWrap;
543   }
544 
545   // Copy the exact flag.
546   if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I))
547     if (PE->isExact())
548       MIFlags |= MachineInstr::MIFlag::IsExact;
549 
550   // Copy the fast-math flags.
551   if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) {
552     const FastMathFlags Flags = FP->getFastMathFlags();
553     if (Flags.noNaNs())
554       MIFlags |= MachineInstr::MIFlag::FmNoNans;
555     if (Flags.noInfs())
556       MIFlags |= MachineInstr::MIFlag::FmNoInfs;
557     if (Flags.noSignedZeros())
558       MIFlags |= MachineInstr::MIFlag::FmNsz;
559     if (Flags.allowReciprocal())
560       MIFlags |= MachineInstr::MIFlag::FmArcp;
561     if (Flags.allowContract())
562       MIFlags |= MachineInstr::MIFlag::FmContract;
563     if (Flags.approxFunc())
564       MIFlags |= MachineInstr::MIFlag::FmAfn;
565     if (Flags.allowReassoc())
566       MIFlags |= MachineInstr::MIFlag::FmReassoc;
567   }
568 
569   return MIFlags;
570 }
571 
copyIRFlags(const Instruction & I)572 void MachineInstr::copyIRFlags(const Instruction &I) {
573   Flags = copyFlagsFromInstruction(I);
574 }
575 
hasPropertyInBundle(uint64_t Mask,QueryType Type) const576 bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const {
577   assert(!isBundledWithPred() && "Must be called on bundle header");
578   for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
579     if (MII->getDesc().getFlags() & Mask) {
580       if (Type == AnyInBundle)
581         return true;
582     } else {
583       if (Type == AllInBundle && !MII->isBundle())
584         return false;
585     }
586     // This was the last instruction in the bundle.
587     if (!MII->isBundledWithSucc())
588       return Type == AllInBundle;
589   }
590 }
591 
isIdenticalTo(const MachineInstr & Other,MICheckType Check) const592 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
593                                  MICheckType Check) const {
594   // If opcodes or number of operands are not the same then the two
595   // instructions are obviously not identical.
596   if (Other.getOpcode() != getOpcode() ||
597       Other.getNumOperands() != getNumOperands())
598     return false;
599 
600   if (isBundle()) {
601     // We have passed the test above that both instructions have the same
602     // opcode, so we know that both instructions are bundles here. Let's compare
603     // MIs inside the bundle.
604     assert(Other.isBundle() && "Expected that both instructions are bundles.");
605     MachineBasicBlock::const_instr_iterator I1 = getIterator();
606     MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
607     // Loop until we analysed the last intruction inside at least one of the
608     // bundles.
609     while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
610       ++I1;
611       ++I2;
612       if (!I1->isIdenticalTo(*I2, Check))
613         return false;
614     }
615     // If we've reached the end of just one of the two bundles, but not both,
616     // the instructions are not identical.
617     if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
618       return false;
619   }
620 
621   // Check operands to make sure they match.
622   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
623     const MachineOperand &MO = getOperand(i);
624     const MachineOperand &OMO = Other.getOperand(i);
625     if (!MO.isReg()) {
626       if (!MO.isIdenticalTo(OMO))
627         return false;
628       continue;
629     }
630 
631     // Clients may or may not want to ignore defs when testing for equality.
632     // For example, machine CSE pass only cares about finding common
633     // subexpressions, so it's safe to ignore virtual register defs.
634     if (MO.isDef()) {
635       if (Check == IgnoreDefs)
636         continue;
637       else if (Check == IgnoreVRegDefs) {
638         if (!Register::isVirtualRegister(MO.getReg()) ||
639             !Register::isVirtualRegister(OMO.getReg()))
640           if (!MO.isIdenticalTo(OMO))
641             return false;
642       } else {
643         if (!MO.isIdenticalTo(OMO))
644           return false;
645         if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
646           return false;
647       }
648     } else {
649       if (!MO.isIdenticalTo(OMO))
650         return false;
651       if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
652         return false;
653     }
654   }
655   // If DebugLoc does not match then two debug instructions are not identical.
656   if (isDebugInstr())
657     if (getDebugLoc() && Other.getDebugLoc() &&
658         getDebugLoc() != Other.getDebugLoc())
659       return false;
660   return true;
661 }
662 
getMF() const663 const MachineFunction *MachineInstr::getMF() const {
664   return getParent()->getParent();
665 }
666 
removeFromParent()667 MachineInstr *MachineInstr::removeFromParent() {
668   assert(getParent() && "Not embedded in a basic block!");
669   return getParent()->remove(this);
670 }
671 
removeFromBundle()672 MachineInstr *MachineInstr::removeFromBundle() {
673   assert(getParent() && "Not embedded in a basic block!");
674   return getParent()->remove_instr(this);
675 }
676 
eraseFromParent()677 void MachineInstr::eraseFromParent() {
678   assert(getParent() && "Not embedded in a basic block!");
679   getParent()->erase(this);
680 }
681 
eraseFromParentAndMarkDBGValuesForRemoval()682 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
683   assert(getParent() && "Not embedded in a basic block!");
684   MachineBasicBlock *MBB = getParent();
685   MachineFunction *MF = MBB->getParent();
686   assert(MF && "Not embedded in a function!");
687 
688   MachineInstr *MI = (MachineInstr *)this;
689   MachineRegisterInfo &MRI = MF->getRegInfo();
690 
691   for (const MachineOperand &MO : MI->operands()) {
692     if (!MO.isReg() || !MO.isDef())
693       continue;
694     Register Reg = MO.getReg();
695     if (!Reg.isVirtual())
696       continue;
697     MRI.markUsesInDebugValueAsUndef(Reg);
698   }
699   MI->eraseFromParent();
700 }
701 
eraseFromBundle()702 void MachineInstr::eraseFromBundle() {
703   assert(getParent() && "Not embedded in a basic block!");
704   getParent()->erase_instr(this);
705 }
706 
isCandidateForCallSiteEntry(QueryType Type) const707 bool MachineInstr::isCandidateForCallSiteEntry(QueryType Type) const {
708   if (!isCall(Type))
709     return false;
710   switch (getOpcode()) {
711   case TargetOpcode::PATCHABLE_EVENT_CALL:
712   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
713   case TargetOpcode::PATCHPOINT:
714   case TargetOpcode::STACKMAP:
715   case TargetOpcode::STATEPOINT:
716   case TargetOpcode::FENTRY_CALL:
717     return false;
718   }
719   return true;
720 }
721 
shouldUpdateCallSiteInfo() const722 bool MachineInstr::shouldUpdateCallSiteInfo() const {
723   if (isBundle())
724     return isCandidateForCallSiteEntry(MachineInstr::AnyInBundle);
725   return isCandidateForCallSiteEntry();
726 }
727 
getNumExplicitOperands() const728 unsigned MachineInstr::getNumExplicitOperands() const {
729   unsigned NumOperands = MCID->getNumOperands();
730   if (!MCID->isVariadic())
731     return NumOperands;
732 
733   for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) {
734     const MachineOperand &MO = getOperand(I);
735     // The operands must always be in the following order:
736     // - explicit reg defs,
737     // - other explicit operands (reg uses, immediates, etc.),
738     // - implicit reg defs
739     // - implicit reg uses
740     if (MO.isReg() && MO.isImplicit())
741       break;
742     ++NumOperands;
743   }
744   return NumOperands;
745 }
746 
getNumExplicitDefs() const747 unsigned MachineInstr::getNumExplicitDefs() const {
748   unsigned NumDefs = MCID->getNumDefs();
749   if (!MCID->isVariadic())
750     return NumDefs;
751 
752   for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) {
753     const MachineOperand &MO = getOperand(I);
754     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
755       break;
756     ++NumDefs;
757   }
758   return NumDefs;
759 }
760 
bundleWithPred()761 void MachineInstr::bundleWithPred() {
762   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
763   setFlag(BundledPred);
764   MachineBasicBlock::instr_iterator Pred = getIterator();
765   --Pred;
766   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
767   Pred->setFlag(BundledSucc);
768 }
769 
bundleWithSucc()770 void MachineInstr::bundleWithSucc() {
771   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
772   setFlag(BundledSucc);
773   MachineBasicBlock::instr_iterator Succ = getIterator();
774   ++Succ;
775   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
776   Succ->setFlag(BundledPred);
777 }
778 
unbundleFromPred()779 void MachineInstr::unbundleFromPred() {
780   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
781   clearFlag(BundledPred);
782   MachineBasicBlock::instr_iterator Pred = getIterator();
783   --Pred;
784   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
785   Pred->clearFlag(BundledSucc);
786 }
787 
unbundleFromSucc()788 void MachineInstr::unbundleFromSucc() {
789   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
790   clearFlag(BundledSucc);
791   MachineBasicBlock::instr_iterator Succ = getIterator();
792   ++Succ;
793   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
794   Succ->clearFlag(BundledPred);
795 }
796 
isStackAligningInlineAsm() const797 bool MachineInstr::isStackAligningInlineAsm() const {
798   if (isInlineAsm()) {
799     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
800     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
801       return true;
802   }
803   return false;
804 }
805 
getInlineAsmDialect() const806 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
807   assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
808   unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
809   return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
810 }
811 
findInlineAsmFlagIdx(unsigned OpIdx,unsigned * GroupNo) const812 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
813                                        unsigned *GroupNo) const {
814   assert(isInlineAsm() && "Expected an inline asm instruction");
815   assert(OpIdx < getNumOperands() && "OpIdx out of range");
816 
817   // Ignore queries about the initial operands.
818   if (OpIdx < InlineAsm::MIOp_FirstOperand)
819     return -1;
820 
821   unsigned Group = 0;
822   unsigned NumOps;
823   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
824        i += NumOps) {
825     const MachineOperand &FlagMO = getOperand(i);
826     // If we reach the implicit register operands, stop looking.
827     if (!FlagMO.isImm())
828       return -1;
829     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
830     if (i + NumOps > OpIdx) {
831       if (GroupNo)
832         *GroupNo = Group;
833       return i;
834     }
835     ++Group;
836   }
837   return -1;
838 }
839 
getDebugLabel() const840 const DILabel *MachineInstr::getDebugLabel() const {
841   assert(isDebugLabel() && "not a DBG_LABEL");
842   return cast<DILabel>(getOperand(0).getMetadata());
843 }
844 
getDebugVariableOp() const845 const MachineOperand &MachineInstr::getDebugVariableOp() const {
846   assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE");
847   return getOperand(2);
848 }
849 
getDebugVariableOp()850 MachineOperand &MachineInstr::getDebugVariableOp() {
851   assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE");
852   return getOperand(2);
853 }
854 
getDebugVariable() const855 const DILocalVariable *MachineInstr::getDebugVariable() const {
856   assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE");
857   return cast<DILocalVariable>(getOperand(2).getMetadata());
858 }
859 
getDebugExpressionOp()860 MachineOperand &MachineInstr::getDebugExpressionOp() {
861   assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE");
862   return getOperand(3);
863 }
864 
getDebugExpression() const865 const DIExpression *MachineInstr::getDebugExpression() const {
866   assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE");
867   return cast<DIExpression>(getOperand(3).getMetadata());
868 }
869 
isDebugEntryValue() const870 bool MachineInstr::isDebugEntryValue() const {
871   return isDebugValue() && getDebugExpression()->isEntryValue();
872 }
873 
874 const TargetRegisterClass*
getRegClassConstraint(unsigned OpIdx,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI) const875 MachineInstr::getRegClassConstraint(unsigned OpIdx,
876                                     const TargetInstrInfo *TII,
877                                     const TargetRegisterInfo *TRI) const {
878   assert(getParent() && "Can't have an MBB reference here!");
879   assert(getMF() && "Can't have an MF reference here!");
880   const MachineFunction &MF = *getMF();
881 
882   // Most opcodes have fixed constraints in their MCInstrDesc.
883   if (!isInlineAsm())
884     return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
885 
886   if (!getOperand(OpIdx).isReg())
887     return nullptr;
888 
889   // For tied uses on inline asm, get the constraint from the def.
890   unsigned DefIdx;
891   if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
892     OpIdx = DefIdx;
893 
894   // Inline asm stores register class constraints in the flag word.
895   int FlagIdx = findInlineAsmFlagIdx(OpIdx);
896   if (FlagIdx < 0)
897     return nullptr;
898 
899   unsigned Flag = getOperand(FlagIdx).getImm();
900   unsigned RCID;
901   if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
902        InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
903        InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
904       InlineAsm::hasRegClassConstraint(Flag, RCID))
905     return TRI->getRegClass(RCID);
906 
907   // Assume that all registers in a memory operand are pointers.
908   if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
909     return TRI->getPointerRegClass(MF);
910 
911   return nullptr;
912 }
913 
getRegClassConstraintEffectForVReg(Register Reg,const TargetRegisterClass * CurRC,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI,bool ExploreBundle) const914 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
915     Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
916     const TargetRegisterInfo *TRI, bool ExploreBundle) const {
917   // Check every operands inside the bundle if we have
918   // been asked to.
919   if (ExploreBundle)
920     for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
921          ++OpndIt)
922       CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
923           OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
924   else
925     // Otherwise, just check the current operands.
926     for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
927       CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
928   return CurRC;
929 }
930 
getRegClassConstraintEffectForVRegImpl(unsigned OpIdx,Register Reg,const TargetRegisterClass * CurRC,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI) const931 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
932     unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
933     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
934   assert(CurRC && "Invalid initial register class");
935   // Check if Reg is constrained by some of its use/def from MI.
936   const MachineOperand &MO = getOperand(OpIdx);
937   if (!MO.isReg() || MO.getReg() != Reg)
938     return CurRC;
939   // If yes, accumulate the constraints through the operand.
940   return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
941 }
942 
getRegClassConstraintEffect(unsigned OpIdx,const TargetRegisterClass * CurRC,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI) const943 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
944     unsigned OpIdx, const TargetRegisterClass *CurRC,
945     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
946   const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
947   const MachineOperand &MO = getOperand(OpIdx);
948   assert(MO.isReg() &&
949          "Cannot get register constraints for non-register operand");
950   assert(CurRC && "Invalid initial register class");
951   if (unsigned SubIdx = MO.getSubReg()) {
952     if (OpRC)
953       CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
954     else
955       CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
956   } else if (OpRC)
957     CurRC = TRI->getCommonSubClass(CurRC, OpRC);
958   return CurRC;
959 }
960 
961 /// Return the number of instructions inside the MI bundle, not counting the
962 /// header instruction.
getBundleSize() const963 unsigned MachineInstr::getBundleSize() const {
964   MachineBasicBlock::const_instr_iterator I = getIterator();
965   unsigned Size = 0;
966   while (I->isBundledWithSucc()) {
967     ++Size;
968     ++I;
969   }
970   return Size;
971 }
972 
973 /// Returns true if the MachineInstr has an implicit-use operand of exactly
974 /// the given register (not considering sub/super-registers).
hasRegisterImplicitUseOperand(Register Reg) const975 bool MachineInstr::hasRegisterImplicitUseOperand(Register Reg) const {
976   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
977     const MachineOperand &MO = getOperand(i);
978     if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
979       return true;
980   }
981   return false;
982 }
983 
984 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
985 /// the specific register or -1 if it is not found. It further tightens
986 /// the search criteria to a use that kills the register if isKill is true.
findRegisterUseOperandIdx(Register Reg,bool isKill,const TargetRegisterInfo * TRI) const987 int MachineInstr::findRegisterUseOperandIdx(
988     Register Reg, bool isKill, const TargetRegisterInfo *TRI) const {
989   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
990     const MachineOperand &MO = getOperand(i);
991     if (!MO.isReg() || !MO.isUse())
992       continue;
993     Register MOReg = MO.getReg();
994     if (!MOReg)
995       continue;
996     if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg)))
997       if (!isKill || MO.isKill())
998         return i;
999   }
1000   return -1;
1001 }
1002 
1003 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1004 /// indicating if this instruction reads or writes Reg. This also considers
1005 /// partial defines.
1006 std::pair<bool,bool>
readsWritesVirtualRegister(Register Reg,SmallVectorImpl<unsigned> * Ops) const1007 MachineInstr::readsWritesVirtualRegister(Register Reg,
1008                                          SmallVectorImpl<unsigned> *Ops) const {
1009   bool PartDef = false; // Partial redefine.
1010   bool FullDef = false; // Full define.
1011   bool Use = false;
1012 
1013   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1014     const MachineOperand &MO = getOperand(i);
1015     if (!MO.isReg() || MO.getReg() != Reg)
1016       continue;
1017     if (Ops)
1018       Ops->push_back(i);
1019     if (MO.isUse())
1020       Use |= !MO.isUndef();
1021     else if (MO.getSubReg() && !MO.isUndef())
1022       // A partial def undef doesn't count as reading the register.
1023       PartDef = true;
1024     else
1025       FullDef = true;
1026   }
1027   // A partial redefine uses Reg unless there is also a full define.
1028   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1029 }
1030 
1031 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1032 /// the specified register or -1 if it is not found. If isDead is true, defs
1033 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1034 /// also checks if there is a def of a super-register.
1035 int
findRegisterDefOperandIdx(Register Reg,bool isDead,bool Overlap,const TargetRegisterInfo * TRI) const1036 MachineInstr::findRegisterDefOperandIdx(Register Reg, bool isDead, bool Overlap,
1037                                         const TargetRegisterInfo *TRI) const {
1038   bool isPhys = Register::isPhysicalRegister(Reg);
1039   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1040     const MachineOperand &MO = getOperand(i);
1041     // Accept regmask operands when Overlap is set.
1042     // Ignore them when looking for a specific def operand (Overlap == false).
1043     if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1044       return i;
1045     if (!MO.isReg() || !MO.isDef())
1046       continue;
1047     Register MOReg = MO.getReg();
1048     bool Found = (MOReg == Reg);
1049     if (!Found && TRI && isPhys && Register::isPhysicalRegister(MOReg)) {
1050       if (Overlap)
1051         Found = TRI->regsOverlap(MOReg, Reg);
1052       else
1053         Found = TRI->isSubRegister(MOReg, Reg);
1054     }
1055     if (Found && (!isDead || MO.isDead()))
1056       return i;
1057   }
1058   return -1;
1059 }
1060 
1061 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1062 /// operand list that is used to represent the predicate. It returns -1 if
1063 /// none is found.
findFirstPredOperandIdx() const1064 int MachineInstr::findFirstPredOperandIdx() const {
1065   // Don't call MCID.findFirstPredOperandIdx() because this variant
1066   // is sometimes called on an instruction that's not yet complete, and
1067   // so the number of operands is less than the MCID indicates. In
1068   // particular, the PTX target does this.
1069   const MCInstrDesc &MCID = getDesc();
1070   if (MCID.isPredicable()) {
1071     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1072       if (MCID.OpInfo[i].isPredicate())
1073         return i;
1074   }
1075 
1076   return -1;
1077 }
1078 
1079 // MachineOperand::TiedTo is 4 bits wide.
1080 const unsigned TiedMax = 15;
1081 
1082 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1083 ///
1084 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1085 /// field. TiedTo can have these values:
1086 ///
1087 /// 0:              Operand is not tied to anything.
1088 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1089 /// TiedMax:        Tied to an operand >= TiedMax-1.
1090 ///
1091 /// The tied def must be one of the first TiedMax operands on a normal
1092 /// instruction. INLINEASM instructions allow more tied defs.
1093 ///
tieOperands(unsigned DefIdx,unsigned UseIdx)1094 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1095   MachineOperand &DefMO = getOperand(DefIdx);
1096   MachineOperand &UseMO = getOperand(UseIdx);
1097   assert(DefMO.isDef() && "DefIdx must be a def operand");
1098   assert(UseMO.isUse() && "UseIdx must be a use operand");
1099   assert(!DefMO.isTied() && "Def is already tied to another use");
1100   assert(!UseMO.isTied() && "Use is already tied to another def");
1101 
1102   if (DefIdx < TiedMax)
1103     UseMO.TiedTo = DefIdx + 1;
1104   else {
1105     // Inline asm can use the group descriptors to find tied operands,
1106     // statepoint tied operands are trivial to match (1-1 reg def with reg use),
1107     // but on normal instruction, the tied def must be within the first TiedMax
1108     // operands.
1109     assert((isInlineAsm() || getOpcode() == TargetOpcode::STATEPOINT) &&
1110            "DefIdx out of range");
1111     UseMO.TiedTo = TiedMax;
1112   }
1113 
1114   // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1115   DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1116 }
1117 
1118 /// Given the index of a tied register operand, find the operand it is tied to.
1119 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1120 /// which must exist.
findTiedOperandIdx(unsigned OpIdx) const1121 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1122   const MachineOperand &MO = getOperand(OpIdx);
1123   assert(MO.isTied() && "Operand isn't tied");
1124 
1125   // Normally TiedTo is in range.
1126   if (MO.TiedTo < TiedMax)
1127     return MO.TiedTo - 1;
1128 
1129   // Uses on normal instructions can be out of range.
1130   if (!isInlineAsm() && getOpcode() != TargetOpcode::STATEPOINT) {
1131     // Normal tied defs must be in the 0..TiedMax-1 range.
1132     if (MO.isUse())
1133       return TiedMax - 1;
1134     // MO is a def. Search for the tied use.
1135     for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1136       const MachineOperand &UseMO = getOperand(i);
1137       if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1138         return i;
1139     }
1140     llvm_unreachable("Can't find tied use");
1141   }
1142 
1143   if (getOpcode() == TargetOpcode::STATEPOINT) {
1144     // In STATEPOINT defs correspond 1-1 to GC pointer operands passed
1145     // on registers.
1146     StatepointOpers SO(this);
1147     unsigned CurUseIdx = SO.getFirstGCPtrIdx();
1148     assert(CurUseIdx != -1U && "only gc pointer statepoint operands can be tied");
1149     unsigned NumDefs = getNumDefs();
1150     for (unsigned CurDefIdx = 0; CurDefIdx < NumDefs; ++CurDefIdx) {
1151       while (!getOperand(CurUseIdx).isReg())
1152         CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx);
1153       if (OpIdx == CurDefIdx)
1154         return CurUseIdx;
1155       if (OpIdx == CurUseIdx)
1156         return CurDefIdx;
1157       CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx);
1158     }
1159     llvm_unreachable("Can't find tied use");
1160   }
1161 
1162   // Now deal with inline asm by parsing the operand group descriptor flags.
1163   // Find the beginning of each operand group.
1164   SmallVector<unsigned, 8> GroupIdx;
1165   unsigned OpIdxGroup = ~0u;
1166   unsigned NumOps;
1167   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1168        i += NumOps) {
1169     const MachineOperand &FlagMO = getOperand(i);
1170     assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1171     unsigned CurGroup = GroupIdx.size();
1172     GroupIdx.push_back(i);
1173     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1174     // OpIdx belongs to this operand group.
1175     if (OpIdx > i && OpIdx < i + NumOps)
1176       OpIdxGroup = CurGroup;
1177     unsigned TiedGroup;
1178     if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1179       continue;
1180     // Operands in this group are tied to operands in TiedGroup which must be
1181     // earlier. Find the number of operands between the two groups.
1182     unsigned Delta = i - GroupIdx[TiedGroup];
1183 
1184     // OpIdx is a use tied to TiedGroup.
1185     if (OpIdxGroup == CurGroup)
1186       return OpIdx - Delta;
1187 
1188     // OpIdx is a def tied to this use group.
1189     if (OpIdxGroup == TiedGroup)
1190       return OpIdx + Delta;
1191   }
1192   llvm_unreachable("Invalid tied operand on inline asm");
1193 }
1194 
1195 /// clearKillInfo - Clears kill flags on all operands.
1196 ///
clearKillInfo()1197 void MachineInstr::clearKillInfo() {
1198   for (MachineOperand &MO : operands()) {
1199     if (MO.isReg() && MO.isUse())
1200       MO.setIsKill(false);
1201   }
1202 }
1203 
substituteRegister(Register FromReg,Register ToReg,unsigned SubIdx,const TargetRegisterInfo & RegInfo)1204 void MachineInstr::substituteRegister(Register FromReg, Register ToReg,
1205                                       unsigned SubIdx,
1206                                       const TargetRegisterInfo &RegInfo) {
1207   if (Register::isPhysicalRegister(ToReg)) {
1208     if (SubIdx)
1209       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1210     for (MachineOperand &MO : operands()) {
1211       if (!MO.isReg() || MO.getReg() != FromReg)
1212         continue;
1213       MO.substPhysReg(ToReg, RegInfo);
1214     }
1215   } else {
1216     for (MachineOperand &MO : operands()) {
1217       if (!MO.isReg() || MO.getReg() != FromReg)
1218         continue;
1219       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1220     }
1221   }
1222 }
1223 
1224 /// isSafeToMove - Return true if it is safe to move this instruction. If
1225 /// SawStore is set to true, it means that there is a store (or call) between
1226 /// the instruction's location and its intended destination.
isSafeToMove(AAResults * AA,bool & SawStore) const1227 bool MachineInstr::isSafeToMove(AAResults *AA, bool &SawStore) const {
1228   // Ignore stuff that we obviously can't move.
1229   //
1230   // Treat volatile loads as stores. This is not strictly necessary for
1231   // volatiles, but it is required for atomic loads. It is not allowed to move
1232   // a load across an atomic load with Ordering > Monotonic.
1233   if (mayStore() || isCall() || isPHI() ||
1234       (mayLoad() && hasOrderedMemoryRef())) {
1235     SawStore = true;
1236     return false;
1237   }
1238 
1239   if (isPosition() || isDebugInstr() || isTerminator() ||
1240       mayRaiseFPException() || hasUnmodeledSideEffects())
1241     return false;
1242 
1243   // See if this instruction does a load.  If so, we have to guarantee that the
1244   // loaded value doesn't change between the load and the its intended
1245   // destination. The check for isInvariantLoad gives the target the chance to
1246   // classify the load as always returning a constant, e.g. a constant pool
1247   // load.
1248   if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1249     // Otherwise, this is a real load.  If there is a store between the load and
1250     // end of block, we can't move it.
1251     return !SawStore;
1252 
1253   return true;
1254 }
1255 
mayAlias(AAResults * AA,const MachineInstr & Other,bool UseTBAA) const1256 bool MachineInstr::mayAlias(AAResults *AA, const MachineInstr &Other,
1257                             bool UseTBAA) const {
1258   const MachineFunction *MF = getMF();
1259   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1260   const MachineFrameInfo &MFI = MF->getFrameInfo();
1261 
1262   // Execulde call instruction which may alter the memory but can not be handled
1263   // by this function.
1264   if (isCall() || Other.isCall())
1265     return true;
1266 
1267   // If neither instruction stores to memory, they can't alias in any
1268   // meaningful way, even if they read from the same address.
1269   if (!mayStore() && !Other.mayStore())
1270     return false;
1271 
1272   // Both instructions must be memory operations to be able to alias.
1273   if (!mayLoadOrStore() || !Other.mayLoadOrStore())
1274     return false;
1275 
1276   // Let the target decide if memory accesses cannot possibly overlap.
1277   if (TII->areMemAccessesTriviallyDisjoint(*this, Other))
1278     return false;
1279 
1280   // Memory operations without memory operands may access anything. Be
1281   // conservative and assume `MayAlias`.
1282   if (memoperands_empty() || Other.memoperands_empty())
1283     return true;
1284 
1285   // Skip if there are too many memory operands.
1286   auto NumChecks = getNumMemOperands() * Other.getNumMemOperands();
1287   if (NumChecks > TII->getMemOperandAACheckLimit())
1288     return true;
1289 
1290   auto HasAlias = [MFI, AA, UseTBAA](const MachineMemOperand *MMOa,
1291                                      const MachineMemOperand *MMOb) {
1292     // The following interface to AA is fashioned after DAGCombiner::isAlias
1293     // and operates with MachineMemOperand offset with some important
1294     // assumptions:
1295     //   - LLVM fundamentally assumes flat address spaces.
1296     //   - MachineOperand offset can *only* result from legalization and
1297     //     cannot affect queries other than the trivial case of overlap
1298     //     checking.
1299     //   - These offsets never wrap and never step outside
1300     //     of allocated objects.
1301     //   - There should never be any negative offsets here.
1302     //
1303     // FIXME: Modify API to hide this math from "user"
1304     // Even before we go to AA we can reason locally about some
1305     // memory objects. It can save compile time, and possibly catch some
1306     // corner cases not currently covered.
1307 
1308     int64_t OffsetA = MMOa->getOffset();
1309     int64_t OffsetB = MMOb->getOffset();
1310     int64_t MinOffset = std::min(OffsetA, OffsetB);
1311 
1312     uint64_t WidthA = MMOa->getSize();
1313     uint64_t WidthB = MMOb->getSize();
1314     bool KnownWidthA = WidthA != MemoryLocation::UnknownSize;
1315     bool KnownWidthB = WidthB != MemoryLocation::UnknownSize;
1316 
1317     const Value *ValA = MMOa->getValue();
1318     const Value *ValB = MMOb->getValue();
1319     bool SameVal = (ValA && ValB && (ValA == ValB));
1320     if (!SameVal) {
1321       const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
1322       const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
1323       if (PSVa && ValB && !PSVa->mayAlias(&MFI))
1324         return false;
1325       if (PSVb && ValA && !PSVb->mayAlias(&MFI))
1326         return false;
1327       if (PSVa && PSVb && (PSVa == PSVb))
1328         SameVal = true;
1329     }
1330 
1331     if (SameVal) {
1332       if (!KnownWidthA || !KnownWidthB)
1333         return true;
1334       int64_t MaxOffset = std::max(OffsetA, OffsetB);
1335       int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
1336       return (MinOffset + LowWidth > MaxOffset);
1337     }
1338 
1339     if (!AA)
1340       return true;
1341 
1342     if (!ValA || !ValB)
1343       return true;
1344 
1345     assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
1346     assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
1347 
1348     int64_t OverlapA = KnownWidthA ? WidthA + OffsetA - MinOffset
1349                                    : MemoryLocation::UnknownSize;
1350     int64_t OverlapB = KnownWidthB ? WidthB + OffsetB - MinOffset
1351                                    : MemoryLocation::UnknownSize;
1352 
1353     AliasResult AAResult =
1354         AA->alias(MemoryLocation(ValA, OverlapA,
1355                                  UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1356                   MemoryLocation(ValB, OverlapB,
1357                                  UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1358 
1359     return (AAResult != NoAlias);
1360   };
1361 
1362   // Check each pair of memory operands from both instructions, which can't
1363   // alias only if all pairs won't alias.
1364   for (auto *MMOa : memoperands())
1365     for (auto *MMOb : Other.memoperands())
1366       if (HasAlias(MMOa, MMOb))
1367         return true;
1368 
1369   return false;
1370 }
1371 
1372 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1373 /// or volatile memory reference, or if the information describing the memory
1374 /// reference is not available. Return false if it is known to have no ordered
1375 /// memory references.
hasOrderedMemoryRef() const1376 bool MachineInstr::hasOrderedMemoryRef() const {
1377   // An instruction known never to access memory won't have a volatile access.
1378   if (!mayStore() &&
1379       !mayLoad() &&
1380       !isCall() &&
1381       !hasUnmodeledSideEffects())
1382     return false;
1383 
1384   // Otherwise, if the instruction has no memory reference information,
1385   // conservatively assume it wasn't preserved.
1386   if (memoperands_empty())
1387     return true;
1388 
1389   // Check if any of our memory operands are ordered.
1390   return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1391     return !MMO->isUnordered();
1392   });
1393 }
1394 
1395 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1396 /// trap and is loading from a location whose value is invariant across a run of
1397 /// this function.
isDereferenceableInvariantLoad(AAResults * AA) const1398 bool MachineInstr::isDereferenceableInvariantLoad(AAResults *AA) const {
1399   // If the instruction doesn't load at all, it isn't an invariant load.
1400   if (!mayLoad())
1401     return false;
1402 
1403   // If the instruction has lost its memoperands, conservatively assume that
1404   // it may not be an invariant load.
1405   if (memoperands_empty())
1406     return false;
1407 
1408   const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1409 
1410   for (MachineMemOperand *MMO : memoperands()) {
1411     if (!MMO->isUnordered())
1412       // If the memory operand has ordering side effects, we can't move the
1413       // instruction.  Such an instruction is technically an invariant load,
1414       // but the caller code would need updated to expect that.
1415       return false;
1416     if (MMO->isStore()) return false;
1417     if (MMO->isInvariant() && MMO->isDereferenceable())
1418       continue;
1419 
1420     // A load from a constant PseudoSourceValue is invariant.
1421     if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1422       if (PSV->isConstant(&MFI))
1423         continue;
1424 
1425     if (const Value *V = MMO->getValue()) {
1426       // If we have an AliasAnalysis, ask it whether the memory is constant.
1427       if (AA &&
1428           AA->pointsToConstantMemory(
1429               MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1430         continue;
1431     }
1432 
1433     // Otherwise assume conservatively.
1434     return false;
1435   }
1436 
1437   // Everything checks out.
1438   return true;
1439 }
1440 
1441 /// isConstantValuePHI - If the specified instruction is a PHI that always
1442 /// merges together the same virtual register, return the register, otherwise
1443 /// return 0.
isConstantValuePHI() const1444 unsigned MachineInstr::isConstantValuePHI() const {
1445   if (!isPHI())
1446     return 0;
1447   assert(getNumOperands() >= 3 &&
1448          "It's illegal to have a PHI without source operands");
1449 
1450   Register Reg = getOperand(1).getReg();
1451   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1452     if (getOperand(i).getReg() != Reg)
1453       return 0;
1454   return Reg;
1455 }
1456 
hasUnmodeledSideEffects() const1457 bool MachineInstr::hasUnmodeledSideEffects() const {
1458   if (hasProperty(MCID::UnmodeledSideEffects))
1459     return true;
1460   if (isInlineAsm()) {
1461     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1462     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1463       return true;
1464   }
1465 
1466   return false;
1467 }
1468 
isLoadFoldBarrier() const1469 bool MachineInstr::isLoadFoldBarrier() const {
1470   return mayStore() || isCall() || hasUnmodeledSideEffects();
1471 }
1472 
1473 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1474 ///
allDefsAreDead() const1475 bool MachineInstr::allDefsAreDead() const {
1476   for (const MachineOperand &MO : operands()) {
1477     if (!MO.isReg() || MO.isUse())
1478       continue;
1479     if (!MO.isDead())
1480       return false;
1481   }
1482   return true;
1483 }
1484 
1485 /// copyImplicitOps - Copy implicit register operands from specified
1486 /// instruction to this instruction.
copyImplicitOps(MachineFunction & MF,const MachineInstr & MI)1487 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1488                                    const MachineInstr &MI) {
1489   for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1490        i != e; ++i) {
1491     const MachineOperand &MO = MI.getOperand(i);
1492     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1493       addOperand(MF, MO);
1494   }
1495 }
1496 
hasComplexRegisterTies() const1497 bool MachineInstr::hasComplexRegisterTies() const {
1498   const MCInstrDesc &MCID = getDesc();
1499   if (MCID.Opcode == TargetOpcode::STATEPOINT)
1500     return true;
1501   for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1502     const auto &Operand = getOperand(I);
1503     if (!Operand.isReg() || Operand.isDef())
1504       // Ignore the defined registers as MCID marks only the uses as tied.
1505       continue;
1506     int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
1507     int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
1508     if (ExpectedTiedIdx != TiedIdx)
1509       return true;
1510   }
1511   return false;
1512 }
1513 
getTypeToPrint(unsigned OpIdx,SmallBitVector & PrintedTypes,const MachineRegisterInfo & MRI) const1514 LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1515                                  const MachineRegisterInfo &MRI) const {
1516   const MachineOperand &Op = getOperand(OpIdx);
1517   if (!Op.isReg())
1518     return LLT{};
1519 
1520   if (isVariadic() || OpIdx >= getNumExplicitOperands())
1521     return MRI.getType(Op.getReg());
1522 
1523   auto &OpInfo = getDesc().OpInfo[OpIdx];
1524   if (!OpInfo.isGenericType())
1525     return MRI.getType(Op.getReg());
1526 
1527   if (PrintedTypes[OpInfo.getGenericTypeIndex()])
1528     return LLT{};
1529 
1530   LLT TypeToPrint = MRI.getType(Op.getReg());
1531   // Don't mark the type index printed if it wasn't actually printed: maybe
1532   // another operand with the same type index has an actual type attached:
1533   if (TypeToPrint.isValid())
1534     PrintedTypes.set(OpInfo.getGenericTypeIndex());
1535   return TypeToPrint;
1536 }
1537 
1538 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const1539 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1540   dbgs() << "  ";
1541   print(dbgs());
1542 }
1543 
dumprImpl(const MachineRegisterInfo & MRI,unsigned Depth,unsigned MaxDepth,SmallPtrSetImpl<const MachineInstr * > & AlreadySeenInstrs) const1544 LLVM_DUMP_METHOD void MachineInstr::dumprImpl(
1545     const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
1546     SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const {
1547   if (Depth >= MaxDepth)
1548     return;
1549   if (!AlreadySeenInstrs.insert(this).second)
1550     return;
1551   // PadToColumn always inserts at least one space.
1552   // Don't mess up the alignment if we don't want any space.
1553   if (Depth)
1554     fdbgs().PadToColumn(Depth * 2);
1555   print(fdbgs());
1556   for (const MachineOperand &MO : operands()) {
1557     if (!MO.isReg() || MO.isDef())
1558       continue;
1559     Register Reg = MO.getReg();
1560     if (Reg.isPhysical())
1561       continue;
1562     const MachineInstr *NewMI = MRI.getUniqueVRegDef(Reg);
1563     if (NewMI == nullptr)
1564       continue;
1565     NewMI->dumprImpl(MRI, Depth + 1, MaxDepth, AlreadySeenInstrs);
1566   }
1567 }
1568 
dumpr(const MachineRegisterInfo & MRI,unsigned MaxDepth) const1569 LLVM_DUMP_METHOD void MachineInstr::dumpr(const MachineRegisterInfo &MRI,
1570                                           unsigned MaxDepth) const {
1571   SmallPtrSet<const MachineInstr *, 16> AlreadySeenInstrs;
1572   dumprImpl(MRI, 0, MaxDepth, AlreadySeenInstrs);
1573 }
1574 #endif
1575 
print(raw_ostream & OS,bool IsStandalone,bool SkipOpers,bool SkipDebugLoc,bool AddNewLine,const TargetInstrInfo * TII) const1576 void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
1577                          bool SkipDebugLoc, bool AddNewLine,
1578                          const TargetInstrInfo *TII) const {
1579   const Module *M = nullptr;
1580   const Function *F = nullptr;
1581   if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1582     F = &MF->getFunction();
1583     M = F->getParent();
1584     if (!TII)
1585       TII = MF->getSubtarget().getInstrInfo();
1586   }
1587 
1588   ModuleSlotTracker MST(M);
1589   if (F)
1590     MST.incorporateFunction(*F);
1591   print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, AddNewLine, TII);
1592 }
1593 
print(raw_ostream & OS,ModuleSlotTracker & MST,bool IsStandalone,bool SkipOpers,bool SkipDebugLoc,bool AddNewLine,const TargetInstrInfo * TII) const1594 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1595                          bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
1596                          bool AddNewLine, const TargetInstrInfo *TII) const {
1597   // We can be a bit tidier if we know the MachineFunction.
1598   const TargetRegisterInfo *TRI = nullptr;
1599   const MachineRegisterInfo *MRI = nullptr;
1600   const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1601   tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
1602 
1603   if (isCFIInstruction())
1604     assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
1605 
1606   SmallBitVector PrintedTypes(8);
1607   bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
1608   auto getTiedOperandIdx = [&](unsigned OpIdx) {
1609     if (!ShouldPrintRegisterTies)
1610       return 0U;
1611     const MachineOperand &MO = getOperand(OpIdx);
1612     if (MO.isReg() && MO.isTied() && !MO.isDef())
1613       return findTiedOperandIdx(OpIdx);
1614     return 0U;
1615   };
1616   unsigned StartOp = 0;
1617   unsigned e = getNumOperands();
1618 
1619   // Print explicitly defined operands on the left of an assignment syntax.
1620   while (StartOp < e) {
1621     const MachineOperand &MO = getOperand(StartOp);
1622     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
1623       break;
1624 
1625     if (StartOp != 0)
1626       OS << ", ";
1627 
1628     LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
1629     unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
1630     MO.print(OS, MST, TypeToPrint, StartOp, /*PrintDef=*/false, IsStandalone,
1631              ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1632     ++StartOp;
1633   }
1634 
1635   if (StartOp != 0)
1636     OS << " = ";
1637 
1638   if (getFlag(MachineInstr::FrameSetup))
1639     OS << "frame-setup ";
1640   if (getFlag(MachineInstr::FrameDestroy))
1641     OS << "frame-destroy ";
1642   if (getFlag(MachineInstr::FmNoNans))
1643     OS << "nnan ";
1644   if (getFlag(MachineInstr::FmNoInfs))
1645     OS << "ninf ";
1646   if (getFlag(MachineInstr::FmNsz))
1647     OS << "nsz ";
1648   if (getFlag(MachineInstr::FmArcp))
1649     OS << "arcp ";
1650   if (getFlag(MachineInstr::FmContract))
1651     OS << "contract ";
1652   if (getFlag(MachineInstr::FmAfn))
1653     OS << "afn ";
1654   if (getFlag(MachineInstr::FmReassoc))
1655     OS << "reassoc ";
1656   if (getFlag(MachineInstr::NoUWrap))
1657     OS << "nuw ";
1658   if (getFlag(MachineInstr::NoSWrap))
1659     OS << "nsw ";
1660   if (getFlag(MachineInstr::IsExact))
1661     OS << "exact ";
1662   if (getFlag(MachineInstr::NoFPExcept))
1663     OS << "nofpexcept ";
1664   if (getFlag(MachineInstr::NoMerge))
1665     OS << "nomerge ";
1666 
1667   // Print the opcode name.
1668   if (TII)
1669     OS << TII->getName(getOpcode());
1670   else
1671     OS << "UNKNOWN";
1672 
1673   if (SkipOpers)
1674     return;
1675 
1676   // Print the rest of the operands.
1677   bool FirstOp = true;
1678   unsigned AsmDescOp = ~0u;
1679   unsigned AsmOpCount = 0;
1680 
1681   if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1682     // Print asm string.
1683     OS << " ";
1684     const unsigned OpIdx = InlineAsm::MIOp_AsmString;
1685     LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
1686     unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
1687     getOperand(OpIdx).print(OS, MST, TypeToPrint, OpIdx, /*PrintDef=*/true, IsStandalone,
1688                             ShouldPrintRegisterTies, TiedOperandIdx, TRI,
1689                             IntrinsicInfo);
1690 
1691     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1692     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1693     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1694       OS << " [sideeffect]";
1695     if (ExtraInfo & InlineAsm::Extra_MayLoad)
1696       OS << " [mayload]";
1697     if (ExtraInfo & InlineAsm::Extra_MayStore)
1698       OS << " [maystore]";
1699     if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1700       OS << " [isconvergent]";
1701     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1702       OS << " [alignstack]";
1703     if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1704       OS << " [attdialect]";
1705     if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1706       OS << " [inteldialect]";
1707 
1708     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1709     FirstOp = false;
1710   }
1711 
1712   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1713     const MachineOperand &MO = getOperand(i);
1714 
1715     if (FirstOp) FirstOp = false; else OS << ",";
1716     OS << " ";
1717 
1718     if (isDebugValue() && MO.isMetadata()) {
1719       // Pretty print DBG_VALUE instructions.
1720       auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1721       if (DIV && !DIV->getName().empty())
1722         OS << "!\"" << DIV->getName() << '\"';
1723       else {
1724         LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1725         unsigned TiedOperandIdx = getTiedOperandIdx(i);
1726         MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1727                  ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1728       }
1729     } else if (isDebugLabel() && MO.isMetadata()) {
1730       // Pretty print DBG_LABEL instructions.
1731       auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
1732       if (DIL && !DIL->getName().empty())
1733         OS << "\"" << DIL->getName() << '\"';
1734       else {
1735         LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1736         unsigned TiedOperandIdx = getTiedOperandIdx(i);
1737         MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1738                  ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1739       }
1740     } else if (i == AsmDescOp && MO.isImm()) {
1741       // Pretty print the inline asm operand descriptor.
1742       OS << '$' << AsmOpCount++;
1743       unsigned Flag = MO.getImm();
1744       OS << ":[";
1745       OS << InlineAsm::getKindName(InlineAsm::getKind(Flag));
1746 
1747       unsigned RCID = 0;
1748       if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1749           InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1750         if (TRI) {
1751           OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1752         } else
1753           OS << ":RC" << RCID;
1754       }
1755 
1756       if (InlineAsm::isMemKind(Flag)) {
1757         unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1758         OS << ":" << InlineAsm::getMemConstraintName(MCID);
1759       }
1760 
1761       unsigned TiedTo = 0;
1762       if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1763         OS << " tiedto:$" << TiedTo;
1764 
1765       OS << ']';
1766 
1767       // Compute the index of the next operand descriptor.
1768       AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1769     } else {
1770       LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1771       unsigned TiedOperandIdx = getTiedOperandIdx(i);
1772       if (MO.isImm() && isOperandSubregIdx(i))
1773         MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
1774       else
1775         MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1776                  ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1777     }
1778   }
1779 
1780   // Print any optional symbols attached to this instruction as-if they were
1781   // operands.
1782   if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
1783     if (!FirstOp) {
1784       FirstOp = false;
1785       OS << ',';
1786     }
1787     OS << " pre-instr-symbol ";
1788     MachineOperand::printSymbol(OS, *PreInstrSymbol);
1789   }
1790   if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
1791     if (!FirstOp) {
1792       FirstOp = false;
1793       OS << ',';
1794     }
1795     OS << " post-instr-symbol ";
1796     MachineOperand::printSymbol(OS, *PostInstrSymbol);
1797   }
1798   if (MDNode *HeapAllocMarker = getHeapAllocMarker()) {
1799     if (!FirstOp) {
1800       FirstOp = false;
1801       OS << ',';
1802     }
1803     OS << " heap-alloc-marker ";
1804     HeapAllocMarker->printAsOperand(OS, MST);
1805   }
1806 
1807   if (DebugInstrNum) {
1808     if (!FirstOp)
1809       OS << ",";
1810     OS << " debug-instr-number " << DebugInstrNum;
1811   }
1812 
1813   if (!SkipDebugLoc) {
1814     if (const DebugLoc &DL = getDebugLoc()) {
1815       if (!FirstOp)
1816         OS << ',';
1817       OS << " debug-location ";
1818       DL->printAsOperand(OS, MST);
1819     }
1820   }
1821 
1822   if (!memoperands_empty()) {
1823     SmallVector<StringRef, 0> SSNs;
1824     const LLVMContext *Context = nullptr;
1825     std::unique_ptr<LLVMContext> CtxPtr;
1826     const MachineFrameInfo *MFI = nullptr;
1827     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1828       MFI = &MF->getFrameInfo();
1829       Context = &MF->getFunction().getContext();
1830     } else {
1831       CtxPtr = std::make_unique<LLVMContext>();
1832       Context = CtxPtr.get();
1833     }
1834 
1835     OS << " :: ";
1836     bool NeedComma = false;
1837     for (const MachineMemOperand *Op : memoperands()) {
1838       if (NeedComma)
1839         OS << ", ";
1840       Op->print(OS, MST, SSNs, *Context, MFI, TII);
1841       NeedComma = true;
1842     }
1843   }
1844 
1845   if (SkipDebugLoc)
1846     return;
1847 
1848   bool HaveSemi = false;
1849 
1850   // Print debug location information.
1851   if (const DebugLoc &DL = getDebugLoc()) {
1852     if (!HaveSemi) {
1853       OS << ';';
1854       HaveSemi = true;
1855     }
1856     OS << ' ';
1857     DL.print(OS);
1858   }
1859 
1860   // Print extra comments for DEBUG_VALUE.
1861   if (isDebugValue() && getDebugVariableOp().isMetadata()) {
1862     if (!HaveSemi) {
1863       OS << ";";
1864       HaveSemi = true;
1865     }
1866     auto *DV = getDebugVariable();
1867     OS << " line no:" <<  DV->getLine();
1868     if (isIndirectDebugValue())
1869       OS << " indirect";
1870   }
1871   // TODO: DBG_LABEL
1872 
1873   if (AddNewLine)
1874     OS << '\n';
1875 }
1876 
addRegisterKilled(Register IncomingReg,const TargetRegisterInfo * RegInfo,bool AddIfNotFound)1877 bool MachineInstr::addRegisterKilled(Register IncomingReg,
1878                                      const TargetRegisterInfo *RegInfo,
1879                                      bool AddIfNotFound) {
1880   bool isPhysReg = Register::isPhysicalRegister(IncomingReg);
1881   bool hasAliases = isPhysReg &&
1882     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1883   bool Found = false;
1884   SmallVector<unsigned,4> DeadOps;
1885   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1886     MachineOperand &MO = getOperand(i);
1887     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1888       continue;
1889 
1890     // DEBUG_VALUE nodes do not contribute to code generation and should
1891     // always be ignored. Failure to do so may result in trying to modify
1892     // KILL flags on DEBUG_VALUE nodes.
1893     if (MO.isDebug())
1894       continue;
1895 
1896     Register Reg = MO.getReg();
1897     if (!Reg)
1898       continue;
1899 
1900     if (Reg == IncomingReg) {
1901       if (!Found) {
1902         if (MO.isKill())
1903           // The register is already marked kill.
1904           return true;
1905         if (isPhysReg && isRegTiedToDefOperand(i))
1906           // Two-address uses of physregs must not be marked kill.
1907           return true;
1908         MO.setIsKill();
1909         Found = true;
1910       }
1911     } else if (hasAliases && MO.isKill() && Register::isPhysicalRegister(Reg)) {
1912       // A super-register kill already exists.
1913       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1914         return true;
1915       if (RegInfo->isSubRegister(IncomingReg, Reg))
1916         DeadOps.push_back(i);
1917     }
1918   }
1919 
1920   // Trim unneeded kill operands.
1921   while (!DeadOps.empty()) {
1922     unsigned OpIdx = DeadOps.back();
1923     if (getOperand(OpIdx).isImplicit() &&
1924         (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
1925       RemoveOperand(OpIdx);
1926     else
1927       getOperand(OpIdx).setIsKill(false);
1928     DeadOps.pop_back();
1929   }
1930 
1931   // If not found, this means an alias of one of the operands is killed. Add a
1932   // new implicit operand if required.
1933   if (!Found && AddIfNotFound) {
1934     addOperand(MachineOperand::CreateReg(IncomingReg,
1935                                          false /*IsDef*/,
1936                                          true  /*IsImp*/,
1937                                          true  /*IsKill*/));
1938     return true;
1939   }
1940   return Found;
1941 }
1942 
clearRegisterKills(Register Reg,const TargetRegisterInfo * RegInfo)1943 void MachineInstr::clearRegisterKills(Register Reg,
1944                                       const TargetRegisterInfo *RegInfo) {
1945   if (!Register::isPhysicalRegister(Reg))
1946     RegInfo = nullptr;
1947   for (MachineOperand &MO : operands()) {
1948     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1949       continue;
1950     Register OpReg = MO.getReg();
1951     if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
1952       MO.setIsKill(false);
1953   }
1954 }
1955 
addRegisterDead(Register Reg,const TargetRegisterInfo * RegInfo,bool AddIfNotFound)1956 bool MachineInstr::addRegisterDead(Register Reg,
1957                                    const TargetRegisterInfo *RegInfo,
1958                                    bool AddIfNotFound) {
1959   bool isPhysReg = Register::isPhysicalRegister(Reg);
1960   bool hasAliases = isPhysReg &&
1961     MCRegAliasIterator(Reg, RegInfo, false).isValid();
1962   bool Found = false;
1963   SmallVector<unsigned,4> DeadOps;
1964   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1965     MachineOperand &MO = getOperand(i);
1966     if (!MO.isReg() || !MO.isDef())
1967       continue;
1968     Register MOReg = MO.getReg();
1969     if (!MOReg)
1970       continue;
1971 
1972     if (MOReg == Reg) {
1973       MO.setIsDead();
1974       Found = true;
1975     } else if (hasAliases && MO.isDead() &&
1976                Register::isPhysicalRegister(MOReg)) {
1977       // There exists a super-register that's marked dead.
1978       if (RegInfo->isSuperRegister(Reg, MOReg))
1979         return true;
1980       if (RegInfo->isSubRegister(Reg, MOReg))
1981         DeadOps.push_back(i);
1982     }
1983   }
1984 
1985   // Trim unneeded dead operands.
1986   while (!DeadOps.empty()) {
1987     unsigned OpIdx = DeadOps.back();
1988     if (getOperand(OpIdx).isImplicit() &&
1989         (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
1990       RemoveOperand(OpIdx);
1991     else
1992       getOperand(OpIdx).setIsDead(false);
1993     DeadOps.pop_back();
1994   }
1995 
1996   // If not found, this means an alias of one of the operands is dead. Add a
1997   // new implicit operand if required.
1998   if (Found || !AddIfNotFound)
1999     return Found;
2000 
2001   addOperand(MachineOperand::CreateReg(Reg,
2002                                        true  /*IsDef*/,
2003                                        true  /*IsImp*/,
2004                                        false /*IsKill*/,
2005                                        true  /*IsDead*/));
2006   return true;
2007 }
2008 
clearRegisterDeads(Register Reg)2009 void MachineInstr::clearRegisterDeads(Register Reg) {
2010   for (MachineOperand &MO : operands()) {
2011     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2012       continue;
2013     MO.setIsDead(false);
2014   }
2015 }
2016 
setRegisterDefReadUndef(Register Reg,bool IsUndef)2017 void MachineInstr::setRegisterDefReadUndef(Register Reg, bool IsUndef) {
2018   for (MachineOperand &MO : operands()) {
2019     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2020       continue;
2021     MO.setIsUndef(IsUndef);
2022   }
2023 }
2024 
addRegisterDefined(Register Reg,const TargetRegisterInfo * RegInfo)2025 void MachineInstr::addRegisterDefined(Register Reg,
2026                                       const TargetRegisterInfo *RegInfo) {
2027   if (Register::isPhysicalRegister(Reg)) {
2028     MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo);
2029     if (MO)
2030       return;
2031   } else {
2032     for (const MachineOperand &MO : operands()) {
2033       if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2034           MO.getSubReg() == 0)
2035         return;
2036     }
2037   }
2038   addOperand(MachineOperand::CreateReg(Reg,
2039                                        true  /*IsDef*/,
2040                                        true  /*IsImp*/));
2041 }
2042 
setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,const TargetRegisterInfo & TRI)2043 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
2044                                          const TargetRegisterInfo &TRI) {
2045   bool HasRegMask = false;
2046   for (MachineOperand &MO : operands()) {
2047     if (MO.isRegMask()) {
2048       HasRegMask = true;
2049       continue;
2050     }
2051     if (!MO.isReg() || !MO.isDef()) continue;
2052     Register Reg = MO.getReg();
2053     if (!Reg.isPhysical())
2054       continue;
2055     // If there are no uses, including partial uses, the def is dead.
2056     if (llvm::none_of(UsedRegs,
2057                       [&](MCRegister Use) { return TRI.regsOverlap(Use, Reg); }))
2058       MO.setIsDead();
2059   }
2060 
2061   // This is a call with a register mask operand.
2062   // Mask clobbers are always dead, so add defs for the non-dead defines.
2063   if (HasRegMask)
2064     for (ArrayRef<Register>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2065          I != E; ++I)
2066       addRegisterDefined(*I, &TRI);
2067 }
2068 
2069 unsigned
getHashValue(const MachineInstr * const & MI)2070 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2071   // Build up a buffer of hash code components.
2072   SmallVector<size_t, 16> HashComponents;
2073   HashComponents.reserve(MI->getNumOperands() + 1);
2074   HashComponents.push_back(MI->getOpcode());
2075   for (const MachineOperand &MO : MI->operands()) {
2076     if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg()))
2077       continue;  // Skip virtual register defs.
2078 
2079     HashComponents.push_back(hash_value(MO));
2080   }
2081   return hash_combine_range(HashComponents.begin(), HashComponents.end());
2082 }
2083 
emitError(StringRef Msg) const2084 void MachineInstr::emitError(StringRef Msg) const {
2085   // Find the source location cookie.
2086   unsigned LocCookie = 0;
2087   const MDNode *LocMD = nullptr;
2088   for (unsigned i = getNumOperands(); i != 0; --i) {
2089     if (getOperand(i-1).isMetadata() &&
2090         (LocMD = getOperand(i-1).getMetadata()) &&
2091         LocMD->getNumOperands() != 0) {
2092       if (const ConstantInt *CI =
2093               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2094         LocCookie = CI->getZExtValue();
2095         break;
2096       }
2097     }
2098   }
2099 
2100   if (const MachineBasicBlock *MBB = getParent())
2101     if (const MachineFunction *MF = MBB->getParent())
2102       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2103   report_fatal_error(Msg);
2104 }
2105 
BuildMI(MachineFunction & MF,const DebugLoc & DL,const MCInstrDesc & MCID,bool IsIndirect,Register Reg,const MDNode * Variable,const MDNode * Expr)2106 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2107                                   const MCInstrDesc &MCID, bool IsIndirect,
2108                                   Register Reg, const MDNode *Variable,
2109                                   const MDNode *Expr) {
2110   assert(isa<DILocalVariable>(Variable) && "not a variable");
2111   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2112   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2113          "Expected inlined-at fields to agree");
2114   auto MIB = BuildMI(MF, DL, MCID).addReg(Reg, RegState::Debug);
2115   if (IsIndirect)
2116     MIB.addImm(0U);
2117   else
2118     MIB.addReg(0U, RegState::Debug);
2119   return MIB.addMetadata(Variable).addMetadata(Expr);
2120 }
2121 
BuildMI(MachineFunction & MF,const DebugLoc & DL,const MCInstrDesc & MCID,bool IsIndirect,MachineOperand & MO,const MDNode * Variable,const MDNode * Expr)2122 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2123                                   const MCInstrDesc &MCID, bool IsIndirect,
2124                                   MachineOperand &MO, const MDNode *Variable,
2125                                   const MDNode *Expr) {
2126   assert(isa<DILocalVariable>(Variable) && "not a variable");
2127   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2128   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2129          "Expected inlined-at fields to agree");
2130   if (MO.isReg())
2131     return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr);
2132 
2133   auto MIB = BuildMI(MF, DL, MCID).add(MO);
2134   if (IsIndirect)
2135     MIB.addImm(0U);
2136   else
2137     MIB.addReg(0U, RegState::Debug);
2138   return MIB.addMetadata(Variable).addMetadata(Expr);
2139  }
2140 
BuildMI(MachineBasicBlock & BB,MachineBasicBlock::iterator I,const DebugLoc & DL,const MCInstrDesc & MCID,bool IsIndirect,Register Reg,const MDNode * Variable,const MDNode * Expr)2141 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2142                                   MachineBasicBlock::iterator I,
2143                                   const DebugLoc &DL, const MCInstrDesc &MCID,
2144                                   bool IsIndirect, Register Reg,
2145                                   const MDNode *Variable, const MDNode *Expr) {
2146   MachineFunction &MF = *BB.getParent();
2147   MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
2148   BB.insert(I, MI);
2149   return MachineInstrBuilder(MF, MI);
2150 }
2151 
BuildMI(MachineBasicBlock & BB,MachineBasicBlock::iterator I,const DebugLoc & DL,const MCInstrDesc & MCID,bool IsIndirect,MachineOperand & MO,const MDNode * Variable,const MDNode * Expr)2152 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2153                                   MachineBasicBlock::iterator I,
2154                                   const DebugLoc &DL, const MCInstrDesc &MCID,
2155                                   bool IsIndirect, MachineOperand &MO,
2156                                   const MDNode *Variable, const MDNode *Expr) {
2157   MachineFunction &MF = *BB.getParent();
2158   MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr);
2159   BB.insert(I, MI);
2160   return MachineInstrBuilder(MF, *MI);
2161 }
2162 
2163 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
2164 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
computeExprForSpill(const MachineInstr & MI)2165 static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
2166   assert(MI.getOperand(0).isReg() && "can't spill non-register");
2167   assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
2168          "Expected inlined-at fields to agree");
2169 
2170   const DIExpression *Expr = MI.getDebugExpression();
2171   if (MI.isIndirectDebugValue()) {
2172     assert(MI.getDebugOffset().getImm() == 0 &&
2173            "DBG_VALUE with nonzero offset");
2174     Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
2175   }
2176   return Expr;
2177 }
2178 
buildDbgValueForSpill(MachineBasicBlock & BB,MachineBasicBlock::iterator I,const MachineInstr & Orig,int FrameIndex)2179 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2180                                           MachineBasicBlock::iterator I,
2181                                           const MachineInstr &Orig,
2182                                           int FrameIndex) {
2183   const DIExpression *Expr = computeExprForSpill(Orig);
2184   return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
2185       .addFrameIndex(FrameIndex)
2186       .addImm(0U)
2187       .addMetadata(Orig.getDebugVariable())
2188       .addMetadata(Expr);
2189 }
2190 
updateDbgValueForSpill(MachineInstr & Orig,int FrameIndex)2191 void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
2192   const DIExpression *Expr = computeExprForSpill(Orig);
2193   Orig.getDebugOperand(0).ChangeToFrameIndex(FrameIndex);
2194   Orig.getDebugOffset().ChangeToImmediate(0U);
2195   Orig.getDebugExpressionOp().setMetadata(Expr);
2196 }
2197 
collectDebugValues(SmallVectorImpl<MachineInstr * > & DbgValues)2198 void MachineInstr::collectDebugValues(
2199                                 SmallVectorImpl<MachineInstr *> &DbgValues) {
2200   MachineInstr &MI = *this;
2201   if (!MI.getOperand(0).isReg())
2202     return;
2203 
2204   MachineBasicBlock::iterator DI = MI; ++DI;
2205   for (MachineBasicBlock::iterator DE = MI.getParent()->end();
2206        DI != DE; ++DI) {
2207     if (!DI->isDebugValue())
2208       return;
2209     if (DI->getDebugOperandForReg(MI.getOperand(0).getReg()))
2210       DbgValues.push_back(&*DI);
2211   }
2212 }
2213 
changeDebugValuesDefReg(Register Reg)2214 void MachineInstr::changeDebugValuesDefReg(Register Reg) {
2215   // Collect matching debug values.
2216   SmallVector<MachineInstr *, 2> DbgValues;
2217 
2218   if (!getOperand(0).isReg())
2219     return;
2220 
2221   Register DefReg = getOperand(0).getReg();
2222   auto *MRI = getRegInfo();
2223   for (auto &MO : MRI->use_operands(DefReg)) {
2224     auto *DI = MO.getParent();
2225     if (!DI->isDebugValue())
2226       continue;
2227     if (DI->getDebugOperandForReg(DefReg)) {
2228       DbgValues.push_back(DI);
2229     }
2230   }
2231 
2232   // Propagate Reg to debug value instructions.
2233   for (auto *DBI : DbgValues)
2234     DBI->getDebugOperandForReg(DefReg)->setReg(Reg);
2235 }
2236 
2237 using MMOList = SmallVector<const MachineMemOperand *, 2>;
2238 
getSpillSlotSize(const MMOList & Accesses,const MachineFrameInfo & MFI)2239 static unsigned getSpillSlotSize(const MMOList &Accesses,
2240                                  const MachineFrameInfo &MFI) {
2241   unsigned Size = 0;
2242   for (auto A : Accesses)
2243     if (MFI.isSpillSlotObjectIndex(
2244             cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
2245                 ->getFrameIndex()))
2246       Size += A->getSize();
2247   return Size;
2248 }
2249 
2250 Optional<unsigned>
getSpillSize(const TargetInstrInfo * TII) const2251 MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
2252   int FI;
2253   if (TII->isStoreToStackSlotPostFE(*this, FI)) {
2254     const MachineFrameInfo &MFI = getMF()->getFrameInfo();
2255     if (MFI.isSpillSlotObjectIndex(FI))
2256       return (*memoperands_begin())->getSize();
2257   }
2258   return None;
2259 }
2260 
2261 Optional<unsigned>
getFoldedSpillSize(const TargetInstrInfo * TII) const2262 MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
2263   MMOList Accesses;
2264   if (TII->hasStoreToStackSlot(*this, Accesses))
2265     return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
2266   return None;
2267 }
2268 
2269 Optional<unsigned>
getRestoreSize(const TargetInstrInfo * TII) const2270 MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
2271   int FI;
2272   if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
2273     const MachineFrameInfo &MFI = getMF()->getFrameInfo();
2274     if (MFI.isSpillSlotObjectIndex(FI))
2275       return (*memoperands_begin())->getSize();
2276   }
2277   return None;
2278 }
2279 
2280 Optional<unsigned>
getFoldedRestoreSize(const TargetInstrInfo * TII) const2281 MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
2282   MMOList Accesses;
2283   if (TII->hasLoadFromStackSlot(*this, Accesses))
2284     return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
2285   return None;
2286 }
2287 
getDebugInstrNum()2288 unsigned MachineInstr::getDebugInstrNum() {
2289   if (DebugInstrNum == 0)
2290     DebugInstrNum = getParent()->getParent()->getNewDebugInstrNum();
2291   return DebugInstrNum;
2292 }
2293