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