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