xref: /llvm-project/llvm/lib/CodeGen/MachineInstr.cpp (revision 036b94dad3fd736738931ced55e2f70525415e6f)
1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Methods common to all machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/ADT/FoldingSet.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineMemOperand.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/InlineAsm.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/MC/MCInstrDesc.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetIntrinsicInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
48 using namespace llvm;
49 
50 static cl::opt<bool> PrintWholeRegMask(
51     "print-whole-regmask",
52     cl::desc("Print the full contents of regmask operands in IR dumps"),
53     cl::init(true), cl::Hidden);
54 
55 //===----------------------------------------------------------------------===//
56 // MachineOperand Implementation
57 //===----------------------------------------------------------------------===//
58 
59 void MachineOperand::setReg(unsigned Reg) {
60   if (getReg() == Reg) return; // No change.
61 
62   // Otherwise, we have to change the register.  If this operand is embedded
63   // into a machine function, we need to update the old and new register's
64   // use/def lists.
65   if (MachineInstr *MI = getParent())
66     if (MachineBasicBlock *MBB = MI->getParent())
67       if (MachineFunction *MF = MBB->getParent()) {
68         MachineRegisterInfo &MRI = MF->getRegInfo();
69         MRI.removeRegOperandFromUseList(this);
70         SmallContents.RegNo = Reg;
71         MRI.addRegOperandToUseList(this);
72         return;
73       }
74 
75   // Otherwise, just change the register, no problem.  :)
76   SmallContents.RegNo = Reg;
77 }
78 
79 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
80                                   const TargetRegisterInfo &TRI) {
81   assert(TargetRegisterInfo::isVirtualRegister(Reg));
82   if (SubIdx && getSubReg())
83     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
84   setReg(Reg);
85   if (SubIdx)
86     setSubReg(SubIdx);
87 }
88 
89 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
90   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
91   if (getSubReg()) {
92     Reg = TRI.getSubReg(Reg, getSubReg());
93     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
94     // That won't happen in legal code.
95     setSubReg(0);
96     if (isDef())
97       setIsUndef(false);
98   }
99   setReg(Reg);
100 }
101 
102 /// Change a def to a use, or a use to a def.
103 void MachineOperand::setIsDef(bool Val) {
104   assert(isReg() && "Wrong MachineOperand accessor");
105   assert((!Val || !isDebug()) && "Marking a debug operation as def");
106   if (IsDef == Val)
107     return;
108   // MRI may keep uses and defs in different list positions.
109   if (MachineInstr *MI = getParent())
110     if (MachineBasicBlock *MBB = MI->getParent())
111       if (MachineFunction *MF = MBB->getParent()) {
112         MachineRegisterInfo &MRI = MF->getRegInfo();
113         MRI.removeRegOperandFromUseList(this);
114         IsDef = Val;
115         MRI.addRegOperandToUseList(this);
116         return;
117       }
118   IsDef = Val;
119 }
120 
121 // If this operand is currently a register operand, and if this is in a
122 // function, deregister the operand from the register's use/def list.
123 void MachineOperand::removeRegFromUses() {
124   if (!isReg() || !isOnRegUseList())
125     return;
126 
127   if (MachineInstr *MI = getParent()) {
128     if (MachineBasicBlock *MBB = MI->getParent()) {
129       if (MachineFunction *MF = MBB->getParent())
130         MF->getRegInfo().removeRegOperandFromUseList(this);
131     }
132   }
133 }
134 
135 /// ChangeToImmediate - Replace this operand with a new immediate operand of
136 /// the specified value.  If an operand is known to be an immediate already,
137 /// the setImm method should be used.
138 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
139   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
140 
141   removeRegFromUses();
142 
143   OpKind = MO_Immediate;
144   Contents.ImmVal = ImmVal;
145 }
146 
147 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
148   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
149 
150   removeRegFromUses();
151 
152   OpKind = MO_FPImmediate;
153   Contents.CFP = FPImm;
154 }
155 
156 void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
157   assert((!isReg() || !isTied()) &&
158          "Cannot change a tied operand into an external symbol");
159 
160   removeRegFromUses();
161 
162   OpKind = MO_ExternalSymbol;
163   Contents.OffsetedInfo.Val.SymbolName = SymName;
164   setOffset(0); // Offset is always 0.
165   setTargetFlags(TargetFlags);
166 }
167 
168 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
169   assert((!isReg() || !isTied()) &&
170          "Cannot change a tied operand into an MCSymbol");
171 
172   removeRegFromUses();
173 
174   OpKind = MO_MCSymbol;
175   Contents.Sym = Sym;
176 }
177 
178 /// ChangeToRegister - Replace this operand with a new register operand of
179 /// the specified value.  If an operand is known to be an register already,
180 /// the setReg method should be used.
181 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
182                                       bool isKill, bool isDead, bool isUndef,
183                                       bool isDebug) {
184   MachineRegisterInfo *RegInfo = nullptr;
185   if (MachineInstr *MI = getParent())
186     if (MachineBasicBlock *MBB = MI->getParent())
187       if (MachineFunction *MF = MBB->getParent())
188         RegInfo = &MF->getRegInfo();
189   // If this operand is already a register operand, remove it from the
190   // register's use/def lists.
191   bool WasReg = isReg();
192   if (RegInfo && WasReg)
193     RegInfo->removeRegOperandFromUseList(this);
194 
195   // Change this to a register and set the reg#.
196   OpKind = MO_Register;
197   SmallContents.RegNo = Reg;
198   SubReg_TargetFlags = 0;
199   IsDef = isDef;
200   IsImp = isImp;
201   IsKill = isKill;
202   IsDead = isDead;
203   IsUndef = isUndef;
204   IsInternalRead = false;
205   IsEarlyClobber = false;
206   IsDebug = isDebug;
207   // Ensure isOnRegUseList() returns false.
208   Contents.Reg.Prev = nullptr;
209   // Preserve the tie when the operand was already a register.
210   if (!WasReg)
211     TiedTo = 0;
212 
213   // If this operand is embedded in a function, add the operand to the
214   // register's use/def list.
215   if (RegInfo)
216     RegInfo->addRegOperandToUseList(this);
217 }
218 
219 /// isIdenticalTo - Return true if this operand is identical to the specified
220 /// operand. Note that this should stay in sync with the hash_value overload
221 /// below.
222 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
223   if (getType() != Other.getType() ||
224       getTargetFlags() != Other.getTargetFlags())
225     return false;
226 
227   switch (getType()) {
228   case MachineOperand::MO_Register:
229     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
230            getSubReg() == Other.getSubReg();
231   case MachineOperand::MO_Immediate:
232     return getImm() == Other.getImm();
233   case MachineOperand::MO_CImmediate:
234     return getCImm() == Other.getCImm();
235   case MachineOperand::MO_FPImmediate:
236     return getFPImm() == Other.getFPImm();
237   case MachineOperand::MO_MachineBasicBlock:
238     return getMBB() == Other.getMBB();
239   case MachineOperand::MO_FrameIndex:
240     return getIndex() == Other.getIndex();
241   case MachineOperand::MO_ConstantPoolIndex:
242   case MachineOperand::MO_TargetIndex:
243     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
244   case MachineOperand::MO_JumpTableIndex:
245     return getIndex() == Other.getIndex();
246   case MachineOperand::MO_GlobalAddress:
247     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
248   case MachineOperand::MO_ExternalSymbol:
249     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
250            getOffset() == Other.getOffset();
251   case MachineOperand::MO_BlockAddress:
252     return getBlockAddress() == Other.getBlockAddress() &&
253            getOffset() == Other.getOffset();
254   case MachineOperand::MO_RegisterMask:
255   case MachineOperand::MO_RegisterLiveOut:
256     return getRegMask() == Other.getRegMask();
257   case MachineOperand::MO_MCSymbol:
258     return getMCSymbol() == Other.getMCSymbol();
259   case MachineOperand::MO_CFIIndex:
260     return getCFIIndex() == Other.getCFIIndex();
261   case MachineOperand::MO_Metadata:
262     return getMetadata() == Other.getMetadata();
263   case MachineOperand::MO_IntrinsicID:
264     return getIntrinsicID() == Other.getIntrinsicID();
265   case MachineOperand::MO_Predicate:
266     return getPredicate() == Other.getPredicate();
267   }
268   llvm_unreachable("Invalid machine operand type");
269 }
270 
271 // Note: this must stay exactly in sync with isIdenticalTo above.
272 hash_code llvm::hash_value(const MachineOperand &MO) {
273   switch (MO.getType()) {
274   case MachineOperand::MO_Register:
275     // Register operands don't have target flags.
276     return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
277   case MachineOperand::MO_Immediate:
278     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
279   case MachineOperand::MO_CImmediate:
280     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
281   case MachineOperand::MO_FPImmediate:
282     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
283   case MachineOperand::MO_MachineBasicBlock:
284     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
285   case MachineOperand::MO_FrameIndex:
286     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
287   case MachineOperand::MO_ConstantPoolIndex:
288   case MachineOperand::MO_TargetIndex:
289     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
290                         MO.getOffset());
291   case MachineOperand::MO_JumpTableIndex:
292     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
293   case MachineOperand::MO_ExternalSymbol:
294     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
295                         MO.getSymbolName());
296   case MachineOperand::MO_GlobalAddress:
297     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
298                         MO.getOffset());
299   case MachineOperand::MO_BlockAddress:
300     return hash_combine(MO.getType(), MO.getTargetFlags(),
301                         MO.getBlockAddress(), MO.getOffset());
302   case MachineOperand::MO_RegisterMask:
303   case MachineOperand::MO_RegisterLiveOut:
304     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
305   case MachineOperand::MO_Metadata:
306     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
307   case MachineOperand::MO_MCSymbol:
308     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
309   case MachineOperand::MO_CFIIndex:
310     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
311   case MachineOperand::MO_IntrinsicID:
312     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
313   case MachineOperand::MO_Predicate:
314     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
315   }
316   llvm_unreachable("Invalid machine operand type");
317 }
318 
319 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
320                            const TargetIntrinsicInfo *IntrinsicInfo) const {
321   ModuleSlotTracker DummyMST(nullptr);
322   print(OS, DummyMST, TRI, IntrinsicInfo);
323 }
324 
325 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
326                            const TargetRegisterInfo *TRI,
327                            const TargetIntrinsicInfo *IntrinsicInfo) const {
328   switch (getType()) {
329   case MachineOperand::MO_Register:
330     OS << PrintReg(getReg(), TRI, getSubReg());
331 
332     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
333         isInternalRead() || isEarlyClobber() || isTied()) {
334       OS << '<';
335       bool NeedComma = false;
336       if (isDef()) {
337         if (NeedComma) OS << ',';
338         if (isEarlyClobber())
339           OS << "earlyclobber,";
340         if (isImplicit())
341           OS << "imp-";
342         OS << "def";
343         NeedComma = true;
344         // <def,read-undef> only makes sense when getSubReg() is set.
345         // Don't clutter the output otherwise.
346         if (isUndef() && getSubReg())
347           OS << ",read-undef";
348       } else if (isImplicit()) {
349         OS << "imp-use";
350         NeedComma = true;
351       }
352 
353       if (isKill()) {
354         if (NeedComma) OS << ',';
355         OS << "kill";
356         NeedComma = true;
357       }
358       if (isDead()) {
359         if (NeedComma) OS << ',';
360         OS << "dead";
361         NeedComma = true;
362       }
363       if (isUndef() && isUse()) {
364         if (NeedComma) OS << ',';
365         OS << "undef";
366         NeedComma = true;
367       }
368       if (isInternalRead()) {
369         if (NeedComma) OS << ',';
370         OS << "internal";
371         NeedComma = true;
372       }
373       if (isTied()) {
374         if (NeedComma) OS << ',';
375         OS << "tied";
376         if (TiedTo != 15)
377           OS << unsigned(TiedTo - 1);
378       }
379       OS << '>';
380     }
381     break;
382   case MachineOperand::MO_Immediate:
383     OS << getImm();
384     break;
385   case MachineOperand::MO_CImmediate:
386     getCImm()->getValue().print(OS, false);
387     break;
388   case MachineOperand::MO_FPImmediate:
389     if (getFPImm()->getType()->isFloatTy()) {
390       OS << getFPImm()->getValueAPF().convertToFloat();
391     } else if (getFPImm()->getType()->isHalfTy()) {
392       APFloat APF = getFPImm()->getValueAPF();
393       bool Unused;
394       APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &Unused);
395       OS << "half " << APF.convertToFloat();
396     } else {
397       OS << getFPImm()->getValueAPF().convertToDouble();
398     }
399     break;
400   case MachineOperand::MO_MachineBasicBlock:
401     OS << "<BB#" << getMBB()->getNumber() << ">";
402     break;
403   case MachineOperand::MO_FrameIndex:
404     OS << "<fi#" << getIndex() << '>';
405     break;
406   case MachineOperand::MO_ConstantPoolIndex:
407     OS << "<cp#" << getIndex();
408     if (getOffset()) OS << "+" << getOffset();
409     OS << '>';
410     break;
411   case MachineOperand::MO_TargetIndex:
412     OS << "<ti#" << getIndex();
413     if (getOffset()) OS << "+" << getOffset();
414     OS << '>';
415     break;
416   case MachineOperand::MO_JumpTableIndex:
417     OS << "<jt#" << getIndex() << '>';
418     break;
419   case MachineOperand::MO_GlobalAddress:
420     OS << "<ga:";
421     getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
422     if (getOffset()) OS << "+" << getOffset();
423     OS << '>';
424     break;
425   case MachineOperand::MO_ExternalSymbol:
426     OS << "<es:" << getSymbolName();
427     if (getOffset()) OS << "+" << getOffset();
428     OS << '>';
429     break;
430   case MachineOperand::MO_BlockAddress:
431     OS << '<';
432     getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
433     if (getOffset()) OS << "+" << getOffset();
434     OS << '>';
435     break;
436   case MachineOperand::MO_RegisterMask: {
437     unsigned NumRegsInMask = 0;
438     unsigned NumRegsEmitted = 0;
439     OS << "<regmask";
440     for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
441       unsigned MaskWord = i / 32;
442       unsigned MaskBit = i % 32;
443       if (getRegMask()[MaskWord] & (1 << MaskBit)) {
444         if (PrintWholeRegMask || NumRegsEmitted <= 10) {
445           OS << " " << PrintReg(i, TRI);
446           NumRegsEmitted++;
447         }
448         NumRegsInMask++;
449       }
450     }
451     if (NumRegsEmitted != NumRegsInMask)
452       OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
453     OS << ">";
454     break;
455   }
456   case MachineOperand::MO_RegisterLiveOut:
457     OS << "<regliveout>";
458     break;
459   case MachineOperand::MO_Metadata:
460     OS << '<';
461     getMetadata()->printAsOperand(OS, MST);
462     OS << '>';
463     break;
464   case MachineOperand::MO_MCSymbol:
465     OS << "<MCSym=" << *getMCSymbol() << '>';
466     break;
467   case MachineOperand::MO_CFIIndex:
468     OS << "<call frame instruction>";
469     break;
470   case MachineOperand::MO_IntrinsicID: {
471     Intrinsic::ID ID = getIntrinsicID();
472     if (ID < Intrinsic::num_intrinsics)
473       OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << ')';
474     else if (IntrinsicInfo)
475       OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << ')';
476     else
477       OS << "<intrinsic:" << ID << '>';
478     break;
479   }
480   case MachineOperand::MO_Predicate: {
481     auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
482     OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
483        << CmpInst::getPredicateName(Pred) << '>';
484   }
485   }
486   if (unsigned TF = getTargetFlags())
487     OS << "[TF=" << TF << ']';
488 }
489 
490 //===----------------------------------------------------------------------===//
491 // MachineMemOperand Implementation
492 //===----------------------------------------------------------------------===//
493 
494 /// getAddrSpace - Return the LLVM IR address space number that this pointer
495 /// points into.
496 unsigned MachinePointerInfo::getAddrSpace() const {
497   if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
498   return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
499 }
500 
501 /// getConstantPool - Return a MachinePointerInfo record that refers to the
502 /// constant pool.
503 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
504   return MachinePointerInfo(MF.getPSVManager().getConstantPool());
505 }
506 
507 /// getFixedStack - Return a MachinePointerInfo record that refers to the
508 /// the specified FrameIndex.
509 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
510                                                      int FI, int64_t Offset) {
511   return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
512 }
513 
514 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
515   return MachinePointerInfo(MF.getPSVManager().getJumpTable());
516 }
517 
518 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
519   return MachinePointerInfo(MF.getPSVManager().getGOT());
520 }
521 
522 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
523                                                 int64_t Offset) {
524   return MachinePointerInfo(MF.getPSVManager().getStack(), Offset);
525 }
526 
527 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
528                                      uint64_t s, unsigned int a,
529                                      const AAMDNodes &AAInfo,
530                                      const MDNode *Ranges)
531     : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
532       AAInfo(AAInfo), Ranges(Ranges) {
533   assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
534           isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
535          "invalid pointer value");
536   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
537   assert((isLoad() || isStore()) && "Not a load/store!");
538 }
539 
540 /// Profile - Gather unique data for the object.
541 ///
542 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
543   ID.AddInteger(getOffset());
544   ID.AddInteger(Size);
545   ID.AddPointer(getOpaqueValue());
546   ID.AddInteger(getFlags());
547   ID.AddInteger(getBaseAlignment());
548 }
549 
550 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
551   // The Value and Offset may differ due to CSE. But the flags and size
552   // should be the same.
553   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
554   assert(MMO->getSize() == getSize() && "Size mismatch!");
555 
556   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
557     // Update the alignment value.
558     BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
559     // Also update the base and offset, because the new alignment may
560     // not be applicable with the old ones.
561     PtrInfo = MMO->PtrInfo;
562   }
563 }
564 
565 /// getAlignment - Return the minimum known alignment in bytes of the
566 /// actual memory reference.
567 uint64_t MachineMemOperand::getAlignment() const {
568   return MinAlign(getBaseAlignment(), getOffset());
569 }
570 
571 void MachineMemOperand::print(raw_ostream &OS) const {
572   ModuleSlotTracker DummyMST(nullptr);
573   print(OS, DummyMST);
574 }
575 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
576   assert((isLoad() || isStore()) &&
577          "SV has to be a load, store or both.");
578 
579   if (isVolatile())
580     OS << "Volatile ";
581 
582   if (isLoad())
583     OS << "LD";
584   if (isStore())
585     OS << "ST";
586   OS << getSize();
587 
588   // Print the address information.
589   OS << "[";
590   if (const Value *V = getValue())
591     V->printAsOperand(OS, /*PrintType=*/false, MST);
592   else if (const PseudoSourceValue *PSV = getPseudoValue())
593     PSV->printCustom(OS);
594   else
595     OS << "<unknown>";
596 
597   unsigned AS = getAddrSpace();
598   if (AS != 0)
599     OS << "(addrspace=" << AS << ')';
600 
601   // If the alignment of the memory reference itself differs from the alignment
602   // of the base pointer, print the base alignment explicitly, next to the base
603   // pointer.
604   if (getBaseAlignment() != getAlignment())
605     OS << "(align=" << getBaseAlignment() << ")";
606 
607   if (getOffset() != 0)
608     OS << "+" << getOffset();
609   OS << "]";
610 
611   // Print the alignment of the reference.
612   if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
613     OS << "(align=" << getAlignment() << ")";
614 
615   // Print TBAA info.
616   if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
617     OS << "(tbaa=";
618     if (TBAAInfo->getNumOperands() > 0)
619       TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
620     else
621       OS << "<unknown>";
622     OS << ")";
623   }
624 
625   // Print AA scope info.
626   if (const MDNode *ScopeInfo = getAAInfo().Scope) {
627     OS << "(alias.scope=";
628     if (ScopeInfo->getNumOperands() > 0)
629       for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
630         ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
631         if (i != ie-1)
632           OS << ",";
633       }
634     else
635       OS << "<unknown>";
636     OS << ")";
637   }
638 
639   // Print AA noalias scope info.
640   if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
641     OS << "(noalias=";
642     if (NoAliasInfo->getNumOperands() > 0)
643       for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
644         NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
645         if (i != ie-1)
646           OS << ",";
647       }
648     else
649       OS << "<unknown>";
650     OS << ")";
651   }
652 
653   // Print nontemporal info.
654   if (isNonTemporal())
655     OS << "(nontemporal)";
656 
657   if (isInvariant())
658     OS << "(invariant)";
659 }
660 
661 //===----------------------------------------------------------------------===//
662 // MachineInstr Implementation
663 //===----------------------------------------------------------------------===//
664 
665 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
666   if (MCID->ImplicitDefs)
667     for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
668            ++ImpDefs)
669       addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
670   if (MCID->ImplicitUses)
671     for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
672            ++ImpUses)
673       addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
674 }
675 
676 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
677 /// implicit operands. It reserves space for the number of operands specified by
678 /// the MCInstrDesc.
679 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
680                            DebugLoc dl, bool NoImp)
681     : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0), Flags(0),
682       AsmPrinterFlags(0), NumMemRefs(0), MemRefs(nullptr),
683       debugLoc(std::move(dl))
684 #ifdef LLVM_BUILD_GLOBAL_ISEL
685       ,
686       Tys(0)
687 #endif
688 {
689   assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
690 
691   // Reserve space for the expected number of operands.
692   if (unsigned NumOps = MCID->getNumOperands() +
693     MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
694     CapOperands = OperandCapacity::get(NumOps);
695     Operands = MF.allocateOperandArray(CapOperands);
696   }
697 
698   if (!NoImp)
699     addImplicitDefUseOperands(MF);
700 }
701 
702 /// MachineInstr ctor - Copies MachineInstr arg exactly
703 ///
704 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
705     : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
706       Flags(0), AsmPrinterFlags(0), NumMemRefs(MI.NumMemRefs),
707       MemRefs(MI.MemRefs), debugLoc(MI.getDebugLoc())
708 #ifdef LLVM_BUILD_GLOBAL_ISEL
709       ,
710       Tys(0)
711 #endif
712 {
713   assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
714 
715   CapOperands = OperandCapacity::get(MI.getNumOperands());
716   Operands = MF.allocateOperandArray(CapOperands);
717 
718   // Copy operands.
719   for (const MachineOperand &MO : MI.operands())
720     addOperand(MF, MO);
721 
722   // Copy all the sensible flags.
723   setFlags(MI.Flags);
724 }
725 
726 /// getRegInfo - If this instruction is embedded into a MachineFunction,
727 /// return the MachineRegisterInfo object for the current function, otherwise
728 /// return null.
729 MachineRegisterInfo *MachineInstr::getRegInfo() {
730   if (MachineBasicBlock *MBB = getParent())
731     return &MBB->getParent()->getRegInfo();
732   return nullptr;
733 }
734 
735 // Implement dummy setter and getter for type when
736 // global-isel is not built.
737 // The proper implementation is WIP and is tracked here:
738 // PR26576.
739 #ifndef LLVM_BUILD_GLOBAL_ISEL
740 unsigned MachineInstr::getNumTypes() const { return 0; }
741 
742 void MachineInstr::setType(LLT Ty, unsigned Idx) {}
743 
744 LLT MachineInstr::getType(unsigned Idx) const { return LLT{}; }
745 
746 void MachineInstr::removeTypes() {}
747 
748 #else
749 unsigned MachineInstr::getNumTypes() const { return Tys.size(); }
750 
751 void MachineInstr::setType(LLT Ty, unsigned Idx) {
752   assert((!Ty.isValid() || isPreISelGenericOpcode(getOpcode())) &&
753          "Non generic instructions are not supposed to be typed");
754   if (Tys.size() < Idx + 1)
755     Tys.resize(Idx+1);
756   Tys[Idx] = Ty;
757 }
758 
759 LLT MachineInstr::getType(unsigned Idx) const { return Tys[Idx]; }
760 
761 void MachineInstr::removeTypes() {
762   Tys.clear();
763 }
764 #endif // LLVM_BUILD_GLOBAL_ISEL
765 
766 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
767 /// this instruction from their respective use lists.  This requires that the
768 /// operands already be on their use lists.
769 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
770   for (MachineOperand &MO : operands())
771     if (MO.isReg())
772       MRI.removeRegOperandFromUseList(&MO);
773 }
774 
775 /// AddRegOperandsToUseLists - Add all of the register operands in
776 /// this instruction from their respective use lists.  This requires that the
777 /// operands not be on their use lists yet.
778 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
779   for (MachineOperand &MO : operands())
780     if (MO.isReg())
781       MRI.addRegOperandToUseList(&MO);
782 }
783 
784 void MachineInstr::addOperand(const MachineOperand &Op) {
785   MachineBasicBlock *MBB = getParent();
786   assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
787   MachineFunction *MF = MBB->getParent();
788   assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
789   addOperand(*MF, Op);
790 }
791 
792 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
793 /// ranges. If MRI is non-null also update use-def chains.
794 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
795                          unsigned NumOps, MachineRegisterInfo *MRI) {
796   if (MRI)
797     return MRI->moveOperands(Dst, Src, NumOps);
798 
799   // MachineOperand is a trivially copyable type so we can just use memmove.
800   std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
801 }
802 
803 /// addOperand - Add the specified operand to the instruction.  If it is an
804 /// implicit operand, it is added to the end of the operand list.  If it is
805 /// an explicit operand it is added at the end of the explicit operand list
806 /// (before the first implicit operand).
807 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
808   assert(MCID && "Cannot add operands before providing an instr descriptor");
809 
810   // Check if we're adding one of our existing operands.
811   if (&Op >= Operands && &Op < Operands + NumOperands) {
812     // This is unusual: MI->addOperand(MI->getOperand(i)).
813     // If adding Op requires reallocating or moving existing operands around,
814     // the Op reference could go stale. Support it by copying Op.
815     MachineOperand CopyOp(Op);
816     return addOperand(MF, CopyOp);
817   }
818 
819   // Find the insert location for the new operand.  Implicit registers go at
820   // the end, everything else goes before the implicit regs.
821   //
822   // FIXME: Allow mixed explicit and implicit operands on inline asm.
823   // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
824   // implicit-defs, but they must not be moved around.  See the FIXME in
825   // InstrEmitter.cpp.
826   unsigned OpNo = getNumOperands();
827   bool isImpReg = Op.isReg() && Op.isImplicit();
828   if (!isImpReg && !isInlineAsm()) {
829     while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
830       --OpNo;
831       assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
832     }
833   }
834 
835 #ifndef NDEBUG
836   bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
837   // OpNo now points as the desired insertion point.  Unless this is a variadic
838   // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
839   // RegMask operands go between the explicit and implicit operands.
840   assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
841           OpNo < MCID->getNumOperands() || isMetaDataOp) &&
842          "Trying to add an operand to a machine instr that is already done!");
843 #endif
844 
845   MachineRegisterInfo *MRI = getRegInfo();
846 
847   // Determine if the Operands array needs to be reallocated.
848   // Save the old capacity and operand array.
849   OperandCapacity OldCap = CapOperands;
850   MachineOperand *OldOperands = Operands;
851   if (!OldOperands || OldCap.getSize() == getNumOperands()) {
852     CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
853     Operands = MF.allocateOperandArray(CapOperands);
854     // Move the operands before the insertion point.
855     if (OpNo)
856       moveOperands(Operands, OldOperands, OpNo, MRI);
857   }
858 
859   // Move the operands following the insertion point.
860   if (OpNo != NumOperands)
861     moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
862                  MRI);
863   ++NumOperands;
864 
865   // Deallocate the old operand array.
866   if (OldOperands != Operands && OldOperands)
867     MF.deallocateOperandArray(OldCap, OldOperands);
868 
869   // Copy Op into place. It still needs to be inserted into the MRI use lists.
870   MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
871   NewMO->ParentMI = this;
872 
873   // When adding a register operand, tell MRI about it.
874   if (NewMO->isReg()) {
875     // Ensure isOnRegUseList() returns false, regardless of Op's status.
876     NewMO->Contents.Reg.Prev = nullptr;
877     // Ignore existing ties. This is not a property that can be copied.
878     NewMO->TiedTo = 0;
879     // Add the new operand to MRI, but only for instructions in an MBB.
880     if (MRI)
881       MRI->addRegOperandToUseList(NewMO);
882     // The MCID operand information isn't accurate until we start adding
883     // explicit operands. The implicit operands are added first, then the
884     // explicits are inserted before them.
885     if (!isImpReg) {
886       // Tie uses to defs as indicated in MCInstrDesc.
887       if (NewMO->isUse()) {
888         int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
889         if (DefIdx != -1)
890           tieOperands(DefIdx, OpNo);
891       }
892       // If the register operand is flagged as early, mark the operand as such.
893       if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
894         NewMO->setIsEarlyClobber(true);
895     }
896   }
897 }
898 
899 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
900 /// fewer operand than it started with.
901 ///
902 void MachineInstr::RemoveOperand(unsigned OpNo) {
903   assert(OpNo < getNumOperands() && "Invalid operand number");
904   untieRegOperand(OpNo);
905 
906 #ifndef NDEBUG
907   // Moving tied operands would break the ties.
908   for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
909     if (Operands[i].isReg())
910       assert(!Operands[i].isTied() && "Cannot move tied operands");
911 #endif
912 
913   MachineRegisterInfo *MRI = getRegInfo();
914   if (MRI && Operands[OpNo].isReg())
915     MRI->removeRegOperandFromUseList(Operands + OpNo);
916 
917   // Don't call the MachineOperand destructor. A lot of this code depends on
918   // MachineOperand having a trivial destructor anyway, and adding a call here
919   // wouldn't make it 'destructor-correct'.
920 
921   if (unsigned N = NumOperands - 1 - OpNo)
922     moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
923   --NumOperands;
924 }
925 
926 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
927 /// This function should be used only occasionally. The setMemRefs function
928 /// is the primary method for setting up a MachineInstr's MemRefs list.
929 void MachineInstr::addMemOperand(MachineFunction &MF,
930                                  MachineMemOperand *MO) {
931   mmo_iterator OldMemRefs = MemRefs;
932   unsigned OldNumMemRefs = NumMemRefs;
933 
934   unsigned NewNum = NumMemRefs + 1;
935   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
936 
937   std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
938   NewMemRefs[NewNum - 1] = MO;
939   setMemRefs(NewMemRefs, NewMemRefs + NewNum);
940 }
941 
942 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
943 /// identical.
944 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
945   auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
946   auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
947   if ((E1 - I1) != (E2 - I2))
948     return false;
949   for (; I1 != E1; ++I1, ++I2) {
950     if (**I1 != **I2)
951       return false;
952   }
953   return true;
954 }
955 
956 std::pair<MachineInstr::mmo_iterator, unsigned>
957 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
958 
959   // If either of the incoming memrefs are empty, we must be conservative and
960   // treat this as if we've exhausted our space for memrefs and dropped them.
961   if (memoperands_empty() || Other.memoperands_empty())
962     return std::make_pair(nullptr, 0);
963 
964   // If both instructions have identical memrefs, we don't need to merge them.
965   // Since many instructions have a single memref, and we tend to merge things
966   // like pairs of loads from the same location, this catches a large number of
967   // cases in practice.
968   if (hasIdenticalMMOs(*this, Other))
969     return std::make_pair(MemRefs, NumMemRefs);
970 
971   // TODO: consider uniquing elements within the operand lists to reduce
972   // space usage and fall back to conservative information less often.
973   size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
974 
975   // If we don't have enough room to store this many memrefs, be conservative
976   // and drop them.  Otherwise, we'd fail asserts when trying to add them to
977   // the new instruction.
978   if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
979     return std::make_pair(nullptr, 0);
980 
981   MachineFunction *MF = getParent()->getParent();
982   mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
983   mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
984                                   MemBegin);
985   MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
986                      MemEnd);
987   assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
988          "missing memrefs");
989 
990   return std::make_pair(MemBegin, CombinedNumMemRefs);
991 }
992 
993 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
994   assert(!isBundledWithPred() && "Must be called on bundle header");
995   for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
996     if (MII->getDesc().getFlags() & Mask) {
997       if (Type == AnyInBundle)
998         return true;
999     } else {
1000       if (Type == AllInBundle && !MII->isBundle())
1001         return false;
1002     }
1003     // This was the last instruction in the bundle.
1004     if (!MII->isBundledWithSucc())
1005       return Type == AllInBundle;
1006   }
1007 }
1008 
1009 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
1010                                  MICheckType Check) const {
1011   // If opcodes or number of operands are not the same then the two
1012   // instructions are obviously not identical.
1013   if (Other.getOpcode() != getOpcode() ||
1014       Other.getNumOperands() != getNumOperands())
1015     return false;
1016 
1017   if (isBundle()) {
1018     // Both instructions are bundles, compare MIs inside the bundle.
1019     MachineBasicBlock::const_instr_iterator I1 = getIterator();
1020     MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
1021     MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
1022     MachineBasicBlock::const_instr_iterator E2 = Other.getParent()->instr_end();
1023     while (++I1 != E1 && I1->isInsideBundle()) {
1024       ++I2;
1025       if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(*I2, Check))
1026         return false;
1027     }
1028   }
1029 
1030   // Check operands to make sure they match.
1031   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1032     const MachineOperand &MO = getOperand(i);
1033     const MachineOperand &OMO = Other.getOperand(i);
1034     if (!MO.isReg()) {
1035       if (!MO.isIdenticalTo(OMO))
1036         return false;
1037       continue;
1038     }
1039 
1040     // Clients may or may not want to ignore defs when testing for equality.
1041     // For example, machine CSE pass only cares about finding common
1042     // subexpressions, so it's safe to ignore virtual register defs.
1043     if (MO.isDef()) {
1044       if (Check == IgnoreDefs)
1045         continue;
1046       else if (Check == IgnoreVRegDefs) {
1047         if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1048             TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
1049           if (MO.getReg() != OMO.getReg())
1050             return false;
1051       } else {
1052         if (!MO.isIdenticalTo(OMO))
1053           return false;
1054         if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
1055           return false;
1056       }
1057     } else {
1058       if (!MO.isIdenticalTo(OMO))
1059         return false;
1060       if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
1061         return false;
1062     }
1063   }
1064   // If DebugLoc does not match then two dbg.values are not identical.
1065   if (isDebugValue())
1066     if (getDebugLoc() && Other.getDebugLoc() &&
1067         getDebugLoc() != Other.getDebugLoc())
1068       return false;
1069   return true;
1070 }
1071 
1072 MachineInstr *MachineInstr::removeFromParent() {
1073   assert(getParent() && "Not embedded in a basic block!");
1074   return getParent()->remove(this);
1075 }
1076 
1077 MachineInstr *MachineInstr::removeFromBundle() {
1078   assert(getParent() && "Not embedded in a basic block!");
1079   return getParent()->remove_instr(this);
1080 }
1081 
1082 void MachineInstr::eraseFromParent() {
1083   assert(getParent() && "Not embedded in a basic block!");
1084   getParent()->erase(this);
1085 }
1086 
1087 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1088   assert(getParent() && "Not embedded in a basic block!");
1089   MachineBasicBlock *MBB = getParent();
1090   MachineFunction *MF = MBB->getParent();
1091   assert(MF && "Not embedded in a function!");
1092 
1093   MachineInstr *MI = (MachineInstr *)this;
1094   MachineRegisterInfo &MRI = MF->getRegInfo();
1095 
1096   for (const MachineOperand &MO : MI->operands()) {
1097     if (!MO.isReg() || !MO.isDef())
1098       continue;
1099     unsigned Reg = MO.getReg();
1100     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1101       continue;
1102     MRI.markUsesInDebugValueAsUndef(Reg);
1103   }
1104   MI->eraseFromParent();
1105 }
1106 
1107 void MachineInstr::eraseFromBundle() {
1108   assert(getParent() && "Not embedded in a basic block!");
1109   getParent()->erase_instr(this);
1110 }
1111 
1112 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1113 ///
1114 unsigned MachineInstr::getNumExplicitOperands() const {
1115   unsigned NumOperands = MCID->getNumOperands();
1116   if (!MCID->isVariadic())
1117     return NumOperands;
1118 
1119   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1120     const MachineOperand &MO = getOperand(i);
1121     if (!MO.isReg() || !MO.isImplicit())
1122       NumOperands++;
1123   }
1124   return NumOperands;
1125 }
1126 
1127 void MachineInstr::bundleWithPred() {
1128   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1129   setFlag(BundledPred);
1130   MachineBasicBlock::instr_iterator Pred = getIterator();
1131   --Pred;
1132   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1133   Pred->setFlag(BundledSucc);
1134 }
1135 
1136 void MachineInstr::bundleWithSucc() {
1137   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1138   setFlag(BundledSucc);
1139   MachineBasicBlock::instr_iterator Succ = getIterator();
1140   ++Succ;
1141   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1142   Succ->setFlag(BundledPred);
1143 }
1144 
1145 void MachineInstr::unbundleFromPred() {
1146   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1147   clearFlag(BundledPred);
1148   MachineBasicBlock::instr_iterator Pred = getIterator();
1149   --Pred;
1150   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1151   Pred->clearFlag(BundledSucc);
1152 }
1153 
1154 void MachineInstr::unbundleFromSucc() {
1155   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1156   clearFlag(BundledSucc);
1157   MachineBasicBlock::instr_iterator Succ = getIterator();
1158   ++Succ;
1159   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1160   Succ->clearFlag(BundledPred);
1161 }
1162 
1163 bool MachineInstr::isStackAligningInlineAsm() const {
1164   if (isInlineAsm()) {
1165     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1166     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1167       return true;
1168   }
1169   return false;
1170 }
1171 
1172 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1173   assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1174   unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1175   return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1176 }
1177 
1178 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1179                                        unsigned *GroupNo) const {
1180   assert(isInlineAsm() && "Expected an inline asm instruction");
1181   assert(OpIdx < getNumOperands() && "OpIdx out of range");
1182 
1183   // Ignore queries about the initial operands.
1184   if (OpIdx < InlineAsm::MIOp_FirstOperand)
1185     return -1;
1186 
1187   unsigned Group = 0;
1188   unsigned NumOps;
1189   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1190        i += NumOps) {
1191     const MachineOperand &FlagMO = getOperand(i);
1192     // If we reach the implicit register operands, stop looking.
1193     if (!FlagMO.isImm())
1194       return -1;
1195     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1196     if (i + NumOps > OpIdx) {
1197       if (GroupNo)
1198         *GroupNo = Group;
1199       return i;
1200     }
1201     ++Group;
1202   }
1203   return -1;
1204 }
1205 
1206 const DILocalVariable *MachineInstr::getDebugVariable() const {
1207   assert(isDebugValue() && "not a DBG_VALUE");
1208   return cast<DILocalVariable>(getOperand(2).getMetadata());
1209 }
1210 
1211 const DIExpression *MachineInstr::getDebugExpression() const {
1212   assert(isDebugValue() && "not a DBG_VALUE");
1213   return cast<DIExpression>(getOperand(3).getMetadata());
1214 }
1215 
1216 const TargetRegisterClass*
1217 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1218                                     const TargetInstrInfo *TII,
1219                                     const TargetRegisterInfo *TRI) const {
1220   assert(getParent() && "Can't have an MBB reference here!");
1221   assert(getParent()->getParent() && "Can't have an MF reference here!");
1222   const MachineFunction &MF = *getParent()->getParent();
1223 
1224   // Most opcodes have fixed constraints in their MCInstrDesc.
1225   if (!isInlineAsm())
1226     return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1227 
1228   if (!getOperand(OpIdx).isReg())
1229     return nullptr;
1230 
1231   // For tied uses on inline asm, get the constraint from the def.
1232   unsigned DefIdx;
1233   if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1234     OpIdx = DefIdx;
1235 
1236   // Inline asm stores register class constraints in the flag word.
1237   int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1238   if (FlagIdx < 0)
1239     return nullptr;
1240 
1241   unsigned Flag = getOperand(FlagIdx).getImm();
1242   unsigned RCID;
1243   if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1244        InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1245        InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1246       InlineAsm::hasRegClassConstraint(Flag, RCID))
1247     return TRI->getRegClass(RCID);
1248 
1249   // Assume that all registers in a memory operand are pointers.
1250   if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1251     return TRI->getPointerRegClass(MF);
1252 
1253   return nullptr;
1254 }
1255 
1256 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1257     unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1258     const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1259   // Check every operands inside the bundle if we have
1260   // been asked to.
1261   if (ExploreBundle)
1262     for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1263          ++OpndIt)
1264       CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1265           OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1266   else
1267     // Otherwise, just check the current operands.
1268     for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1269       CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1270   return CurRC;
1271 }
1272 
1273 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1274     unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1275     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1276   assert(CurRC && "Invalid initial register class");
1277   // Check if Reg is constrained by some of its use/def from MI.
1278   const MachineOperand &MO = getOperand(OpIdx);
1279   if (!MO.isReg() || MO.getReg() != Reg)
1280     return CurRC;
1281   // If yes, accumulate the constraints through the operand.
1282   return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1283 }
1284 
1285 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1286     unsigned OpIdx, const TargetRegisterClass *CurRC,
1287     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1288   const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1289   const MachineOperand &MO = getOperand(OpIdx);
1290   assert(MO.isReg() &&
1291          "Cannot get register constraints for non-register operand");
1292   assert(CurRC && "Invalid initial register class");
1293   if (unsigned SubIdx = MO.getSubReg()) {
1294     if (OpRC)
1295       CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1296     else
1297       CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1298   } else if (OpRC)
1299     CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1300   return CurRC;
1301 }
1302 
1303 /// Return the number of instructions inside the MI bundle, not counting the
1304 /// header instruction.
1305 unsigned MachineInstr::getBundleSize() const {
1306   MachineBasicBlock::const_instr_iterator I = getIterator();
1307   unsigned Size = 0;
1308   while (I->isBundledWithSucc()) {
1309     ++Size;
1310     ++I;
1311   }
1312   return Size;
1313 }
1314 
1315 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1316 /// the given register (not considering sub/super-registers).
1317 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1318   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1319     const MachineOperand &MO = getOperand(i);
1320     if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1321       return true;
1322   }
1323   return false;
1324 }
1325 
1326 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1327 /// the specific register or -1 if it is not found. It further tightens
1328 /// the search criteria to a use that kills the register if isKill is true.
1329 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1330                                           const TargetRegisterInfo *TRI) const {
1331   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1332     const MachineOperand &MO = getOperand(i);
1333     if (!MO.isReg() || !MO.isUse())
1334       continue;
1335     unsigned MOReg = MO.getReg();
1336     if (!MOReg)
1337       continue;
1338     if (MOReg == Reg ||
1339         (TRI &&
1340          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1341          TargetRegisterInfo::isPhysicalRegister(Reg) &&
1342          TRI->isSubRegister(MOReg, Reg)))
1343       if (!isKill || MO.isKill())
1344         return i;
1345   }
1346   return -1;
1347 }
1348 
1349 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1350 /// indicating if this instruction reads or writes Reg. This also considers
1351 /// partial defines.
1352 std::pair<bool,bool>
1353 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1354                                          SmallVectorImpl<unsigned> *Ops) const {
1355   bool PartDef = false; // Partial redefine.
1356   bool FullDef = false; // Full define.
1357   bool Use = false;
1358 
1359   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1360     const MachineOperand &MO = getOperand(i);
1361     if (!MO.isReg() || MO.getReg() != Reg)
1362       continue;
1363     if (Ops)
1364       Ops->push_back(i);
1365     if (MO.isUse())
1366       Use |= !MO.isUndef();
1367     else if (MO.getSubReg() && !MO.isUndef())
1368       // A partial <def,undef> doesn't count as reading the register.
1369       PartDef = true;
1370     else
1371       FullDef = true;
1372   }
1373   // A partial redefine uses Reg unless there is also a full define.
1374   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1375 }
1376 
1377 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1378 /// the specified register or -1 if it is not found. If isDead is true, defs
1379 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1380 /// also checks if there is a def of a super-register.
1381 int
1382 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1383                                         const TargetRegisterInfo *TRI) const {
1384   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1385   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1386     const MachineOperand &MO = getOperand(i);
1387     // Accept regmask operands when Overlap is set.
1388     // Ignore them when looking for a specific def operand (Overlap == false).
1389     if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1390       return i;
1391     if (!MO.isReg() || !MO.isDef())
1392       continue;
1393     unsigned MOReg = MO.getReg();
1394     bool Found = (MOReg == Reg);
1395     if (!Found && TRI && isPhys &&
1396         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1397       if (Overlap)
1398         Found = TRI->regsOverlap(MOReg, Reg);
1399       else
1400         Found = TRI->isSubRegister(MOReg, Reg);
1401     }
1402     if (Found && (!isDead || MO.isDead()))
1403       return i;
1404   }
1405   return -1;
1406 }
1407 
1408 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1409 /// operand list that is used to represent the predicate. It returns -1 if
1410 /// none is found.
1411 int MachineInstr::findFirstPredOperandIdx() const {
1412   // Don't call MCID.findFirstPredOperandIdx() because this variant
1413   // is sometimes called on an instruction that's not yet complete, and
1414   // so the number of operands is less than the MCID indicates. In
1415   // particular, the PTX target does this.
1416   const MCInstrDesc &MCID = getDesc();
1417   if (MCID.isPredicable()) {
1418     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1419       if (MCID.OpInfo[i].isPredicate())
1420         return i;
1421   }
1422 
1423   return -1;
1424 }
1425 
1426 // MachineOperand::TiedTo is 4 bits wide.
1427 const unsigned TiedMax = 15;
1428 
1429 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1430 ///
1431 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1432 /// field. TiedTo can have these values:
1433 ///
1434 /// 0:              Operand is not tied to anything.
1435 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1436 /// TiedMax:        Tied to an operand >= TiedMax-1.
1437 ///
1438 /// The tied def must be one of the first TiedMax operands on a normal
1439 /// instruction. INLINEASM instructions allow more tied defs.
1440 ///
1441 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1442   MachineOperand &DefMO = getOperand(DefIdx);
1443   MachineOperand &UseMO = getOperand(UseIdx);
1444   assert(DefMO.isDef() && "DefIdx must be a def operand");
1445   assert(UseMO.isUse() && "UseIdx must be a use operand");
1446   assert(!DefMO.isTied() && "Def is already tied to another use");
1447   assert(!UseMO.isTied() && "Use is already tied to another def");
1448 
1449   if (DefIdx < TiedMax)
1450     UseMO.TiedTo = DefIdx + 1;
1451   else {
1452     // Inline asm can use the group descriptors to find tied operands, but on
1453     // normal instruction, the tied def must be within the first TiedMax
1454     // operands.
1455     assert(isInlineAsm() && "DefIdx out of range");
1456     UseMO.TiedTo = TiedMax;
1457   }
1458 
1459   // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1460   DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1461 }
1462 
1463 /// Given the index of a tied register operand, find the operand it is tied to.
1464 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1465 /// which must exist.
1466 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1467   const MachineOperand &MO = getOperand(OpIdx);
1468   assert(MO.isTied() && "Operand isn't tied");
1469 
1470   // Normally TiedTo is in range.
1471   if (MO.TiedTo < TiedMax)
1472     return MO.TiedTo - 1;
1473 
1474   // Uses on normal instructions can be out of range.
1475   if (!isInlineAsm()) {
1476     // Normal tied defs must be in the 0..TiedMax-1 range.
1477     if (MO.isUse())
1478       return TiedMax - 1;
1479     // MO is a def. Search for the tied use.
1480     for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1481       const MachineOperand &UseMO = getOperand(i);
1482       if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1483         return i;
1484     }
1485     llvm_unreachable("Can't find tied use");
1486   }
1487 
1488   // Now deal with inline asm by parsing the operand group descriptor flags.
1489   // Find the beginning of each operand group.
1490   SmallVector<unsigned, 8> GroupIdx;
1491   unsigned OpIdxGroup = ~0u;
1492   unsigned NumOps;
1493   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1494        i += NumOps) {
1495     const MachineOperand &FlagMO = getOperand(i);
1496     assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1497     unsigned CurGroup = GroupIdx.size();
1498     GroupIdx.push_back(i);
1499     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1500     // OpIdx belongs to this operand group.
1501     if (OpIdx > i && OpIdx < i + NumOps)
1502       OpIdxGroup = CurGroup;
1503     unsigned TiedGroup;
1504     if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1505       continue;
1506     // Operands in this group are tied to operands in TiedGroup which must be
1507     // earlier. Find the number of operands between the two groups.
1508     unsigned Delta = i - GroupIdx[TiedGroup];
1509 
1510     // OpIdx is a use tied to TiedGroup.
1511     if (OpIdxGroup == CurGroup)
1512       return OpIdx - Delta;
1513 
1514     // OpIdx is a def tied to this use group.
1515     if (OpIdxGroup == TiedGroup)
1516       return OpIdx + Delta;
1517   }
1518   llvm_unreachable("Invalid tied operand on inline asm");
1519 }
1520 
1521 /// clearKillInfo - Clears kill flags on all operands.
1522 ///
1523 void MachineInstr::clearKillInfo() {
1524   for (MachineOperand &MO : operands()) {
1525     if (MO.isReg() && MO.isUse())
1526       MO.setIsKill(false);
1527   }
1528 }
1529 
1530 void MachineInstr::substituteRegister(unsigned FromReg,
1531                                       unsigned ToReg,
1532                                       unsigned SubIdx,
1533                                       const TargetRegisterInfo &RegInfo) {
1534   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1535     if (SubIdx)
1536       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1537     for (MachineOperand &MO : operands()) {
1538       if (!MO.isReg() || MO.getReg() != FromReg)
1539         continue;
1540       MO.substPhysReg(ToReg, RegInfo);
1541     }
1542   } else {
1543     for (MachineOperand &MO : operands()) {
1544       if (!MO.isReg() || MO.getReg() != FromReg)
1545         continue;
1546       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1547     }
1548   }
1549 }
1550 
1551 /// isSafeToMove - Return true if it is safe to move this instruction. If
1552 /// SawStore is set to true, it means that there is a store (or call) between
1553 /// the instruction's location and its intended destination.
1554 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1555   // Ignore stuff that we obviously can't move.
1556   //
1557   // Treat volatile loads as stores. This is not strictly necessary for
1558   // volatiles, but it is required for atomic loads. It is not allowed to move
1559   // a load across an atomic load with Ordering > Monotonic.
1560   if (mayStore() || isCall() ||
1561       (mayLoad() && hasOrderedMemoryRef())) {
1562     SawStore = true;
1563     return false;
1564   }
1565 
1566   if (isPosition() || isDebugValue() || isTerminator() ||
1567       hasUnmodeledSideEffects())
1568     return false;
1569 
1570   // See if this instruction does a load.  If so, we have to guarantee that the
1571   // loaded value doesn't change between the load and the its intended
1572   // destination. The check for isInvariantLoad gives the targe the chance to
1573   // classify the load as always returning a constant, e.g. a constant pool
1574   // load.
1575   if (mayLoad() && !isInvariantLoad(AA))
1576     // Otherwise, this is a real load.  If there is a store between the load and
1577     // end of block, we can't move it.
1578     return !SawStore;
1579 
1580   return true;
1581 }
1582 
1583 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1584 /// or volatile memory reference, or if the information describing the memory
1585 /// reference is not available. Return false if it is known to have no ordered
1586 /// memory references.
1587 bool MachineInstr::hasOrderedMemoryRef() const {
1588   // An instruction known never to access memory won't have a volatile access.
1589   if (!mayStore() &&
1590       !mayLoad() &&
1591       !isCall() &&
1592       !hasUnmodeledSideEffects())
1593     return false;
1594 
1595   // Otherwise, if the instruction has no memory reference information,
1596   // conservatively assume it wasn't preserved.
1597   if (memoperands_empty())
1598     return true;
1599 
1600   // Check if any of our memory operands are ordered.
1601   return any_of(memoperands(), [](const MachineMemOperand *MMO) {
1602     return !MMO->isUnordered();
1603   });
1604 }
1605 
1606 /// isInvariantLoad - Return true if this instruction is loading from a
1607 /// location whose value is invariant across the function.  For example,
1608 /// loading a value from the constant pool or from the argument area
1609 /// of a function if it does not change.  This should only return true of
1610 /// *all* loads the instruction does are invariant (if it does multiple loads).
1611 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1612   // If the instruction doesn't load at all, it isn't an invariant load.
1613   if (!mayLoad())
1614     return false;
1615 
1616   // If the instruction has lost its memoperands, conservatively assume that
1617   // it may not be an invariant load.
1618   if (memoperands_empty())
1619     return false;
1620 
1621   const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1622 
1623   for (MachineMemOperand *MMO : memoperands()) {
1624     if (MMO->isVolatile()) return false;
1625     if (MMO->isStore()) return false;
1626     if (MMO->isInvariant()) continue;
1627 
1628     // A load from a constant PseudoSourceValue is invariant.
1629     if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1630       if (PSV->isConstant(&MFI))
1631         continue;
1632 
1633     if (const Value *V = MMO->getValue()) {
1634       // If we have an AliasAnalysis, ask it whether the memory is constant.
1635       if (AA &&
1636           AA->pointsToConstantMemory(
1637               MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1638         continue;
1639     }
1640 
1641     // Otherwise assume conservatively.
1642     return false;
1643   }
1644 
1645   // Everything checks out.
1646   return true;
1647 }
1648 
1649 /// isConstantValuePHI - If the specified instruction is a PHI that always
1650 /// merges together the same virtual register, return the register, otherwise
1651 /// return 0.
1652 unsigned MachineInstr::isConstantValuePHI() const {
1653   if (!isPHI())
1654     return 0;
1655   assert(getNumOperands() >= 3 &&
1656          "It's illegal to have a PHI without source operands");
1657 
1658   unsigned Reg = getOperand(1).getReg();
1659   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1660     if (getOperand(i).getReg() != Reg)
1661       return 0;
1662   return Reg;
1663 }
1664 
1665 bool MachineInstr::hasUnmodeledSideEffects() const {
1666   if (hasProperty(MCID::UnmodeledSideEffects))
1667     return true;
1668   if (isInlineAsm()) {
1669     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1670     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1671       return true;
1672   }
1673 
1674   return false;
1675 }
1676 
1677 bool MachineInstr::isLoadFoldBarrier() const {
1678   return mayStore() || isCall() || hasUnmodeledSideEffects();
1679 }
1680 
1681 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1682 ///
1683 bool MachineInstr::allDefsAreDead() const {
1684   for (const MachineOperand &MO : operands()) {
1685     if (!MO.isReg() || MO.isUse())
1686       continue;
1687     if (!MO.isDead())
1688       return false;
1689   }
1690   return true;
1691 }
1692 
1693 /// copyImplicitOps - Copy implicit register operands from specified
1694 /// instruction to this instruction.
1695 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1696                                    const MachineInstr &MI) {
1697   for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1698        i != e; ++i) {
1699     const MachineOperand &MO = MI.getOperand(i);
1700     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1701       addOperand(MF, MO);
1702   }
1703 }
1704 
1705 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1706 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1707   dbgs() << "  " << *this;
1708 #endif
1709 }
1710 
1711 void MachineInstr::print(raw_ostream &OS, bool SkipOpers) const {
1712   const Module *M = nullptr;
1713   if (const MachineBasicBlock *MBB = getParent())
1714     if (const MachineFunction *MF = MBB->getParent())
1715       M = MF->getFunction()->getParent();
1716 
1717   ModuleSlotTracker MST(M);
1718   print(OS, MST, SkipOpers);
1719 }
1720 
1721 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1722                          bool SkipOpers) const {
1723   // We can be a bit tidier if we know the MachineFunction.
1724   const MachineFunction *MF = nullptr;
1725   const TargetRegisterInfo *TRI = nullptr;
1726   const MachineRegisterInfo *MRI = nullptr;
1727   const TargetInstrInfo *TII = nullptr;
1728   const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1729 
1730   if (const MachineBasicBlock *MBB = getParent()) {
1731     MF = MBB->getParent();
1732     if (MF) {
1733       MRI = &MF->getRegInfo();
1734       TRI = MF->getSubtarget().getRegisterInfo();
1735       TII = MF->getSubtarget().getInstrInfo();
1736       IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
1737     }
1738   }
1739 
1740   // Save a list of virtual registers.
1741   SmallVector<unsigned, 8> VirtRegs;
1742 
1743   // Print explicitly defined operands on the left of an assignment syntax.
1744   unsigned StartOp = 0, e = getNumOperands();
1745   for (; StartOp < e && getOperand(StartOp).isReg() &&
1746          getOperand(StartOp).isDef() &&
1747          !getOperand(StartOp).isImplicit();
1748        ++StartOp) {
1749     if (StartOp != 0) OS << ", ";
1750     getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
1751     unsigned Reg = getOperand(StartOp).getReg();
1752     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1753       VirtRegs.push_back(Reg);
1754       unsigned Size;
1755       if (MRI && (Size = MRI->getSize(Reg)))
1756         OS << '(' << Size << ')';
1757     }
1758   }
1759 
1760   if (StartOp != 0)
1761     OS << " = ";
1762 
1763   // Print the opcode name.
1764   if (TII)
1765     OS << TII->getName(getOpcode());
1766   else
1767     OS << "UNKNOWN";
1768 
1769   if (getNumTypes() > 0) {
1770     OS << " { ";
1771     for (unsigned i = 0; i < getNumTypes(); ++i) {
1772       getType(i).print(OS);
1773       if (i + 1 != getNumTypes())
1774         OS << ", ";
1775     }
1776     OS << " } ";
1777   }
1778 
1779   if (SkipOpers)
1780     return;
1781 
1782   // Print the rest of the operands.
1783   bool OmittedAnyCallClobbers = false;
1784   bool FirstOp = true;
1785   unsigned AsmDescOp = ~0u;
1786   unsigned AsmOpCount = 0;
1787 
1788   if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1789     // Print asm string.
1790     OS << " ";
1791     getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1792 
1793     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1794     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1795     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1796       OS << " [sideeffect]";
1797     if (ExtraInfo & InlineAsm::Extra_MayLoad)
1798       OS << " [mayload]";
1799     if (ExtraInfo & InlineAsm::Extra_MayStore)
1800       OS << " [maystore]";
1801     if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1802       OS << " [isconvergent]";
1803     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1804       OS << " [alignstack]";
1805     if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1806       OS << " [attdialect]";
1807     if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1808       OS << " [inteldialect]";
1809 
1810     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1811     FirstOp = false;
1812   }
1813 
1814   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1815     const MachineOperand &MO = getOperand(i);
1816 
1817     if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1818       VirtRegs.push_back(MO.getReg());
1819 
1820     // Omit call-clobbered registers which aren't used anywhere. This makes
1821     // call instructions much less noisy on targets where calls clobber lots
1822     // of registers. Don't rely on MO.isDead() because we may be called before
1823     // LiveVariables is run, or we may be looking at a non-allocatable reg.
1824     if (MRI && isCall() &&
1825         MO.isReg() && MO.isImplicit() && MO.isDef()) {
1826       unsigned Reg = MO.getReg();
1827       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1828         if (MRI->use_empty(Reg)) {
1829           bool HasAliasLive = false;
1830           for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
1831             unsigned AliasReg = *AI;
1832             if (!MRI->use_empty(AliasReg)) {
1833               HasAliasLive = true;
1834               break;
1835             }
1836           }
1837           if (!HasAliasLive) {
1838             OmittedAnyCallClobbers = true;
1839             continue;
1840           }
1841         }
1842       }
1843     }
1844 
1845     if (FirstOp) FirstOp = false; else OS << ",";
1846     OS << " ";
1847     if (i < getDesc().NumOperands) {
1848       const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1849       if (MCOI.isPredicate())
1850         OS << "pred:";
1851       if (MCOI.isOptionalDef())
1852         OS << "opt:";
1853     }
1854     if (isDebugValue() && MO.isMetadata()) {
1855       // Pretty print DBG_VALUE instructions.
1856       auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1857       if (DIV && !DIV->getName().empty())
1858         OS << "!\"" << DIV->getName() << '\"';
1859       else
1860         MO.print(OS, MST, TRI);
1861     } else if (TRI && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1862       OS << TRI->getSubRegIndexName(MO.getImm());
1863     } else if (i == AsmDescOp && MO.isImm()) {
1864       // Pretty print the inline asm operand descriptor.
1865       OS << '$' << AsmOpCount++;
1866       unsigned Flag = MO.getImm();
1867       switch (InlineAsm::getKind(Flag)) {
1868       case InlineAsm::Kind_RegUse:             OS << ":[reguse"; break;
1869       case InlineAsm::Kind_RegDef:             OS << ":[regdef"; break;
1870       case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1871       case InlineAsm::Kind_Clobber:            OS << ":[clobber"; break;
1872       case InlineAsm::Kind_Imm:                OS << ":[imm"; break;
1873       case InlineAsm::Kind_Mem:                OS << ":[mem"; break;
1874       default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1875       }
1876 
1877       unsigned RCID = 0;
1878       if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1879           InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1880         if (TRI) {
1881           OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1882         } else
1883           OS << ":RC" << RCID;
1884       }
1885 
1886       if (InlineAsm::isMemKind(Flag)) {
1887         unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1888         switch (MCID) {
1889         case InlineAsm::Constraint_es: OS << ":es"; break;
1890         case InlineAsm::Constraint_i:  OS << ":i"; break;
1891         case InlineAsm::Constraint_m:  OS << ":m"; break;
1892         case InlineAsm::Constraint_o:  OS << ":o"; break;
1893         case InlineAsm::Constraint_v:  OS << ":v"; break;
1894         case InlineAsm::Constraint_Q:  OS << ":Q"; break;
1895         case InlineAsm::Constraint_R:  OS << ":R"; break;
1896         case InlineAsm::Constraint_S:  OS << ":S"; break;
1897         case InlineAsm::Constraint_T:  OS << ":T"; break;
1898         case InlineAsm::Constraint_Um: OS << ":Um"; break;
1899         case InlineAsm::Constraint_Un: OS << ":Un"; break;
1900         case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1901         case InlineAsm::Constraint_Us: OS << ":Us"; break;
1902         case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1903         case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1904         case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1905         case InlineAsm::Constraint_X:  OS << ":X"; break;
1906         case InlineAsm::Constraint_Z:  OS << ":Z"; break;
1907         case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1908         case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1909         default: OS << ":?"; break;
1910         }
1911       }
1912 
1913       unsigned TiedTo = 0;
1914       if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1915         OS << " tiedto:$" << TiedTo;
1916 
1917       OS << ']';
1918 
1919       // Compute the index of the next operand descriptor.
1920       AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1921     } else
1922       MO.print(OS, MST, TRI);
1923   }
1924 
1925   // Briefly indicate whether any call clobbers were omitted.
1926   if (OmittedAnyCallClobbers) {
1927     if (!FirstOp) OS << ",";
1928     OS << " ...";
1929   }
1930 
1931   bool HaveSemi = false;
1932   const unsigned PrintableFlags = FrameSetup | FrameDestroy;
1933   if (Flags & PrintableFlags) {
1934     if (!HaveSemi) {
1935       OS << ";";
1936       HaveSemi = true;
1937     }
1938     OS << " flags: ";
1939 
1940     if (Flags & FrameSetup)
1941       OS << "FrameSetup";
1942 
1943     if (Flags & FrameDestroy)
1944       OS << "FrameDestroy";
1945   }
1946 
1947   if (!memoperands_empty()) {
1948     if (!HaveSemi) {
1949       OS << ";";
1950       HaveSemi = true;
1951     }
1952 
1953     OS << " mem:";
1954     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1955          i != e; ++i) {
1956       (*i)->print(OS, MST);
1957       if (std::next(i) != e)
1958         OS << " ";
1959     }
1960   }
1961 
1962   // Print the regclass of any virtual registers encountered.
1963   if (MRI && !VirtRegs.empty()) {
1964     if (!HaveSemi) {
1965       OS << ";";
1966       HaveSemi = true;
1967     }
1968     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1969       const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
1970       if (!RC)
1971         continue;
1972       // Generic virtual registers do not have register classes.
1973       if (RC.is<const RegisterBank *>())
1974         OS << " " << RC.get<const RegisterBank *>()->getName();
1975       else
1976         OS << " "
1977            << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
1978       OS << ':' << PrintReg(VirtRegs[i]);
1979       for (unsigned j = i+1; j != VirtRegs.size();) {
1980         if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
1981           ++j;
1982           continue;
1983         }
1984         if (VirtRegs[i] != VirtRegs[j])
1985           OS << "," << PrintReg(VirtRegs[j]);
1986         VirtRegs.erase(VirtRegs.begin()+j);
1987       }
1988     }
1989   }
1990 
1991   // Print debug location information.
1992   if (isDebugValue() && getOperand(e - 2).isMetadata()) {
1993     if (!HaveSemi)
1994       OS << ";";
1995     auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
1996     OS << " line no:" <<  DV->getLine();
1997     if (auto *InlinedAt = debugLoc->getInlinedAt()) {
1998       DebugLoc InlinedAtDL(InlinedAt);
1999       if (InlinedAtDL && MF) {
2000         OS << " inlined @[ ";
2001         InlinedAtDL.print(OS);
2002         OS << " ]";
2003       }
2004     }
2005     if (isIndirectDebugValue())
2006       OS << " indirect";
2007   } else if (debugLoc && MF) {
2008     if (!HaveSemi)
2009       OS << ";";
2010     OS << " dbg:";
2011     debugLoc.print(OS);
2012   }
2013 
2014   OS << '\n';
2015 }
2016 
2017 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
2018                                      const TargetRegisterInfo *RegInfo,
2019                                      bool AddIfNotFound) {
2020   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
2021   bool hasAliases = isPhysReg &&
2022     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
2023   bool Found = false;
2024   SmallVector<unsigned,4> DeadOps;
2025   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2026     MachineOperand &MO = getOperand(i);
2027     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
2028       continue;
2029 
2030     // DEBUG_VALUE nodes do not contribute to code generation and should
2031     // always be ignored. Failure to do so may result in trying to modify
2032     // KILL flags on DEBUG_VALUE nodes.
2033     if (MO.isDebug())
2034       continue;
2035 
2036     unsigned Reg = MO.getReg();
2037     if (!Reg)
2038       continue;
2039 
2040     if (Reg == IncomingReg) {
2041       if (!Found) {
2042         if (MO.isKill())
2043           // The register is already marked kill.
2044           return true;
2045         if (isPhysReg && isRegTiedToDefOperand(i))
2046           // Two-address uses of physregs must not be marked kill.
2047           return true;
2048         MO.setIsKill();
2049         Found = true;
2050       }
2051     } else if (hasAliases && MO.isKill() &&
2052                TargetRegisterInfo::isPhysicalRegister(Reg)) {
2053       // A super-register kill already exists.
2054       if (RegInfo->isSuperRegister(IncomingReg, Reg))
2055         return true;
2056       if (RegInfo->isSubRegister(IncomingReg, Reg))
2057         DeadOps.push_back(i);
2058     }
2059   }
2060 
2061   // Trim unneeded kill operands.
2062   while (!DeadOps.empty()) {
2063     unsigned OpIdx = DeadOps.back();
2064     if (getOperand(OpIdx).isImplicit())
2065       RemoveOperand(OpIdx);
2066     else
2067       getOperand(OpIdx).setIsKill(false);
2068     DeadOps.pop_back();
2069   }
2070 
2071   // If not found, this means an alias of one of the operands is killed. Add a
2072   // new implicit operand if required.
2073   if (!Found && AddIfNotFound) {
2074     addOperand(MachineOperand::CreateReg(IncomingReg,
2075                                          false /*IsDef*/,
2076                                          true  /*IsImp*/,
2077                                          true  /*IsKill*/));
2078     return true;
2079   }
2080   return Found;
2081 }
2082 
2083 void MachineInstr::clearRegisterKills(unsigned Reg,
2084                                       const TargetRegisterInfo *RegInfo) {
2085   if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2086     RegInfo = nullptr;
2087   for (MachineOperand &MO : operands()) {
2088     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2089       continue;
2090     unsigned OpReg = MO.getReg();
2091     if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2092       MO.setIsKill(false);
2093   }
2094 }
2095 
2096 bool MachineInstr::addRegisterDead(unsigned Reg,
2097                                    const TargetRegisterInfo *RegInfo,
2098                                    bool AddIfNotFound) {
2099   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2100   bool hasAliases = isPhysReg &&
2101     MCRegAliasIterator(Reg, RegInfo, false).isValid();
2102   bool Found = false;
2103   SmallVector<unsigned,4> DeadOps;
2104   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2105     MachineOperand &MO = getOperand(i);
2106     if (!MO.isReg() || !MO.isDef())
2107       continue;
2108     unsigned MOReg = MO.getReg();
2109     if (!MOReg)
2110       continue;
2111 
2112     if (MOReg == Reg) {
2113       MO.setIsDead();
2114       Found = true;
2115     } else if (hasAliases && MO.isDead() &&
2116                TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2117       // There exists a super-register that's marked dead.
2118       if (RegInfo->isSuperRegister(Reg, MOReg))
2119         return true;
2120       if (RegInfo->isSubRegister(Reg, MOReg))
2121         DeadOps.push_back(i);
2122     }
2123   }
2124 
2125   // Trim unneeded dead operands.
2126   while (!DeadOps.empty()) {
2127     unsigned OpIdx = DeadOps.back();
2128     if (getOperand(OpIdx).isImplicit())
2129       RemoveOperand(OpIdx);
2130     else
2131       getOperand(OpIdx).setIsDead(false);
2132     DeadOps.pop_back();
2133   }
2134 
2135   // If not found, this means an alias of one of the operands is dead. Add a
2136   // new implicit operand if required.
2137   if (Found || !AddIfNotFound)
2138     return Found;
2139 
2140   addOperand(MachineOperand::CreateReg(Reg,
2141                                        true  /*IsDef*/,
2142                                        true  /*IsImp*/,
2143                                        false /*IsKill*/,
2144                                        true  /*IsDead*/));
2145   return true;
2146 }
2147 
2148 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2149   for (MachineOperand &MO : operands()) {
2150     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2151       continue;
2152     MO.setIsDead(false);
2153   }
2154 }
2155 
2156 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2157   for (MachineOperand &MO : operands()) {
2158     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2159       continue;
2160     MO.setIsUndef(IsUndef);
2161   }
2162 }
2163 
2164 void MachineInstr::addRegisterDefined(unsigned Reg,
2165                                       const TargetRegisterInfo *RegInfo) {
2166   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2167     MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2168     if (MO)
2169       return;
2170   } else {
2171     for (const MachineOperand &MO : operands()) {
2172       if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2173           MO.getSubReg() == 0)
2174         return;
2175     }
2176   }
2177   addOperand(MachineOperand::CreateReg(Reg,
2178                                        true  /*IsDef*/,
2179                                        true  /*IsImp*/));
2180 }
2181 
2182 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2183                                          const TargetRegisterInfo &TRI) {
2184   bool HasRegMask = false;
2185   for (MachineOperand &MO : operands()) {
2186     if (MO.isRegMask()) {
2187       HasRegMask = true;
2188       continue;
2189     }
2190     if (!MO.isReg() || !MO.isDef()) continue;
2191     unsigned Reg = MO.getReg();
2192     if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2193     // If there are no uses, including partial uses, the def is dead.
2194     if (none_of(UsedRegs,
2195                 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2196       MO.setIsDead();
2197   }
2198 
2199   // This is a call with a register mask operand.
2200   // Mask clobbers are always dead, so add defs for the non-dead defines.
2201   if (HasRegMask)
2202     for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2203          I != E; ++I)
2204       addRegisterDefined(*I, &TRI);
2205 }
2206 
2207 unsigned
2208 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2209   // Build up a buffer of hash code components.
2210   SmallVector<size_t, 8> HashComponents;
2211   HashComponents.reserve(MI->getNumOperands() + 1);
2212   HashComponents.push_back(MI->getOpcode());
2213   for (const MachineOperand &MO : MI->operands()) {
2214     if (MO.isReg() && MO.isDef() &&
2215         TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2216       continue;  // Skip virtual register defs.
2217 
2218     HashComponents.push_back(hash_value(MO));
2219   }
2220   return hash_combine_range(HashComponents.begin(), HashComponents.end());
2221 }
2222 
2223 void MachineInstr::emitError(StringRef Msg) const {
2224   // Find the source location cookie.
2225   unsigned LocCookie = 0;
2226   const MDNode *LocMD = nullptr;
2227   for (unsigned i = getNumOperands(); i != 0; --i) {
2228     if (getOperand(i-1).isMetadata() &&
2229         (LocMD = getOperand(i-1).getMetadata()) &&
2230         LocMD->getNumOperands() != 0) {
2231       if (const ConstantInt *CI =
2232               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2233         LocCookie = CI->getZExtValue();
2234         break;
2235       }
2236     }
2237   }
2238 
2239   if (const MachineBasicBlock *MBB = getParent())
2240     if (const MachineFunction *MF = MBB->getParent())
2241       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2242   report_fatal_error(Msg);
2243 }
2244 
2245 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2246                                   const MCInstrDesc &MCID, bool IsIndirect,
2247                                   unsigned Reg, unsigned Offset,
2248                                   const MDNode *Variable, const MDNode *Expr) {
2249   assert(isa<DILocalVariable>(Variable) && "not a variable");
2250   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2251   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2252          "Expected inlined-at fields to agree");
2253   if (IsIndirect)
2254     return BuildMI(MF, DL, MCID)
2255         .addReg(Reg, RegState::Debug)
2256         .addImm(Offset)
2257         .addMetadata(Variable)
2258         .addMetadata(Expr);
2259   else {
2260     assert(Offset == 0 && "A direct address cannot have an offset.");
2261     return BuildMI(MF, DL, MCID)
2262         .addReg(Reg, RegState::Debug)
2263         .addReg(0U, RegState::Debug)
2264         .addMetadata(Variable)
2265         .addMetadata(Expr);
2266   }
2267 }
2268 
2269 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2270                                   MachineBasicBlock::iterator I,
2271                                   const DebugLoc &DL, const MCInstrDesc &MCID,
2272                                   bool IsIndirect, unsigned Reg,
2273                                   unsigned Offset, const MDNode *Variable,
2274                                   const MDNode *Expr) {
2275   assert(isa<DILocalVariable>(Variable) && "not a variable");
2276   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2277   MachineFunction &MF = *BB.getParent();
2278   MachineInstr *MI =
2279       BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr);
2280   BB.insert(I, MI);
2281   return MachineInstrBuilder(MF, MI);
2282 }
2283