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