xref: /llvm-project/llvm/lib/CodeGen/MachineInstr.cpp (revision 9e6c309ef343acc13a14ca97f370e35079fbea1f)
1 //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Methods common to all machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/Loads.h"
25 #include "llvm/Analysis/MemoryLocation.h"
26 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineInstrBundle.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/InstrTypes.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Metadata.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/ModuleSlotTracker.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/Value.h"
50 #include "llvm/MC/MCInstrDesc.h"
51 #include "llvm/MC/MCRegisterInfo.h"
52 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/LowLevelTypeImpl.h"
59 #include "llvm/Support/MathExtras.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Target/TargetInstrInfo.h"
62 #include "llvm/Target/TargetIntrinsicInfo.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Target/TargetRegisterInfo.h"
65 #include "llvm/Target/TargetSubtargetInfo.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstddef>
69 #include <cstdint>
70 #include <cstring>
71 #include <iterator>
72 #include <utility>
73 
74 using namespace llvm;
75 
76 static cl::opt<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()->getParent()->getParent();
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 (isNonTemporal())
769     OS << "(nontemporal)";
770   if (isDereferenceable())
771     OS << "(dereferenceable)";
772   if (isInvariant())
773     OS << "(invariant)";
774   if (getFlags() & MOTargetFlag1)
775     OS << "(flag1)";
776   if (getFlags() & MOTargetFlag2)
777     OS << "(flag2)";
778   if (getFlags() & MOTargetFlag3)
779     OS << "(flag3)";
780 }
781 
782 //===----------------------------------------------------------------------===//
783 // MachineInstr Implementation
784 //===----------------------------------------------------------------------===//
785 
786 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
787   if (MCID->ImplicitDefs)
788     for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
789            ++ImpDefs)
790       addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
791   if (MCID->ImplicitUses)
792     for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
793            ++ImpUses)
794       addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
795 }
796 
797 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
798 /// implicit operands. It reserves space for the number of operands specified by
799 /// the MCInstrDesc.
800 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
801                            DebugLoc dl, bool NoImp)
802     : MCID(&tid), debugLoc(std::move(dl)) {
803   assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
804 
805   // Reserve space for the expected number of operands.
806   if (unsigned NumOps = MCID->getNumOperands() +
807     MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
808     CapOperands = OperandCapacity::get(NumOps);
809     Operands = MF.allocateOperandArray(CapOperands);
810   }
811 
812   if (!NoImp)
813     addImplicitDefUseOperands(MF);
814 }
815 
816 /// MachineInstr ctor - Copies MachineInstr arg exactly
817 ///
818 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
819     : MCID(&MI.getDesc()), NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
820       debugLoc(MI.getDebugLoc()) {
821   assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
822 
823   CapOperands = OperandCapacity::get(MI.getNumOperands());
824   Operands = MF.allocateOperandArray(CapOperands);
825 
826   // Copy operands.
827   for (const MachineOperand &MO : MI.operands())
828     addOperand(MF, MO);
829 
830   // Copy all the sensible flags.
831   setFlags(MI.Flags);
832 }
833 
834 /// getRegInfo - If this instruction is embedded into a MachineFunction,
835 /// return the MachineRegisterInfo object for the current function, otherwise
836 /// return null.
837 MachineRegisterInfo *MachineInstr::getRegInfo() {
838   if (MachineBasicBlock *MBB = getParent())
839     return &MBB->getParent()->getRegInfo();
840   return nullptr;
841 }
842 
843 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
844 /// this instruction from their respective use lists.  This requires that the
845 /// operands already be on their use lists.
846 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
847   for (MachineOperand &MO : operands())
848     if (MO.isReg())
849       MRI.removeRegOperandFromUseList(&MO);
850 }
851 
852 /// AddRegOperandsToUseLists - Add all of the register operands in
853 /// this instruction from their respective use lists.  This requires that the
854 /// operands not be on their use lists yet.
855 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
856   for (MachineOperand &MO : operands())
857     if (MO.isReg())
858       MRI.addRegOperandToUseList(&MO);
859 }
860 
861 void MachineInstr::addOperand(const MachineOperand &Op) {
862   MachineBasicBlock *MBB = getParent();
863   assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
864   MachineFunction *MF = MBB->getParent();
865   assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
866   addOperand(*MF, Op);
867 }
868 
869 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
870 /// ranges. If MRI is non-null also update use-def chains.
871 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
872                          unsigned NumOps, MachineRegisterInfo *MRI) {
873   if (MRI)
874     return MRI->moveOperands(Dst, Src, NumOps);
875 
876   // MachineOperand is a trivially copyable type so we can just use memmove.
877   std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
878 }
879 
880 /// addOperand - Add the specified operand to the instruction.  If it is an
881 /// implicit operand, it is added to the end of the operand list.  If it is
882 /// an explicit operand it is added at the end of the explicit operand list
883 /// (before the first implicit operand).
884 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
885   assert(MCID && "Cannot add operands before providing an instr descriptor");
886 
887   // Check if we're adding one of our existing operands.
888   if (&Op >= Operands && &Op < Operands + NumOperands) {
889     // This is unusual: MI->addOperand(MI->getOperand(i)).
890     // If adding Op requires reallocating or moving existing operands around,
891     // the Op reference could go stale. Support it by copying Op.
892     MachineOperand CopyOp(Op);
893     return addOperand(MF, CopyOp);
894   }
895 
896   // Find the insert location for the new operand.  Implicit registers go at
897   // the end, everything else goes before the implicit regs.
898   //
899   // FIXME: Allow mixed explicit and implicit operands on inline asm.
900   // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
901   // implicit-defs, but they must not be moved around.  See the FIXME in
902   // InstrEmitter.cpp.
903   unsigned OpNo = getNumOperands();
904   bool isImpReg = Op.isReg() && Op.isImplicit();
905   if (!isImpReg && !isInlineAsm()) {
906     while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
907       --OpNo;
908       assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
909     }
910   }
911 
912 #ifndef NDEBUG
913   bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
914   // OpNo now points as the desired insertion point.  Unless this is a variadic
915   // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
916   // RegMask operands go between the explicit and implicit operands.
917   assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
918           OpNo < MCID->getNumOperands() || isMetaDataOp) &&
919          "Trying to add an operand to a machine instr that is already done!");
920 #endif
921 
922   MachineRegisterInfo *MRI = getRegInfo();
923 
924   // Determine if the Operands array needs to be reallocated.
925   // Save the old capacity and operand array.
926   OperandCapacity OldCap = CapOperands;
927   MachineOperand *OldOperands = Operands;
928   if (!OldOperands || OldCap.getSize() == getNumOperands()) {
929     CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
930     Operands = MF.allocateOperandArray(CapOperands);
931     // Move the operands before the insertion point.
932     if (OpNo)
933       moveOperands(Operands, OldOperands, OpNo, MRI);
934   }
935 
936   // Move the operands following the insertion point.
937   if (OpNo != NumOperands)
938     moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
939                  MRI);
940   ++NumOperands;
941 
942   // Deallocate the old operand array.
943   if (OldOperands != Operands && OldOperands)
944     MF.deallocateOperandArray(OldCap, OldOperands);
945 
946   // Copy Op into place. It still needs to be inserted into the MRI use lists.
947   MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
948   NewMO->ParentMI = this;
949 
950   // When adding a register operand, tell MRI about it.
951   if (NewMO->isReg()) {
952     // Ensure isOnRegUseList() returns false, regardless of Op's status.
953     NewMO->Contents.Reg.Prev = nullptr;
954     // Ignore existing ties. This is not a property that can be copied.
955     NewMO->TiedTo = 0;
956     // Add the new operand to MRI, but only for instructions in an MBB.
957     if (MRI)
958       MRI->addRegOperandToUseList(NewMO);
959     // The MCID operand information isn't accurate until we start adding
960     // explicit operands. The implicit operands are added first, then the
961     // explicits are inserted before them.
962     if (!isImpReg) {
963       // Tie uses to defs as indicated in MCInstrDesc.
964       if (NewMO->isUse()) {
965         int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
966         if (DefIdx != -1)
967           tieOperands(DefIdx, OpNo);
968       }
969       // If the register operand is flagged as early, mark the operand as such.
970       if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
971         NewMO->setIsEarlyClobber(true);
972     }
973   }
974 }
975 
976 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
977 /// fewer operand than it started with.
978 ///
979 void MachineInstr::RemoveOperand(unsigned OpNo) {
980   assert(OpNo < getNumOperands() && "Invalid operand number");
981   untieRegOperand(OpNo);
982 
983 #ifndef NDEBUG
984   // Moving tied operands would break the ties.
985   for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
986     if (Operands[i].isReg())
987       assert(!Operands[i].isTied() && "Cannot move tied operands");
988 #endif
989 
990   MachineRegisterInfo *MRI = getRegInfo();
991   if (MRI && Operands[OpNo].isReg())
992     MRI->removeRegOperandFromUseList(Operands + OpNo);
993 
994   // Don't call the MachineOperand destructor. A lot of this code depends on
995   // MachineOperand having a trivial destructor anyway, and adding a call here
996   // wouldn't make it 'destructor-correct'.
997 
998   if (unsigned N = NumOperands - 1 - OpNo)
999     moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
1000   --NumOperands;
1001 }
1002 
1003 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
1004 /// This function should be used only occasionally. The setMemRefs function
1005 /// is the primary method for setting up a MachineInstr's MemRefs list.
1006 void MachineInstr::addMemOperand(MachineFunction &MF,
1007                                  MachineMemOperand *MO) {
1008   mmo_iterator OldMemRefs = MemRefs;
1009   unsigned OldNumMemRefs = NumMemRefs;
1010 
1011   unsigned NewNum = NumMemRefs + 1;
1012   mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
1013 
1014   std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
1015   NewMemRefs[NewNum - 1] = MO;
1016   setMemRefs(NewMemRefs, NewMemRefs + NewNum);
1017 }
1018 
1019 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
1020 /// identical.
1021 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
1022   auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
1023   auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
1024   if ((E1 - I1) != (E2 - I2))
1025     return false;
1026   for (; I1 != E1; ++I1, ++I2) {
1027     if (**I1 != **I2)
1028       return false;
1029   }
1030   return true;
1031 }
1032 
1033 std::pair<MachineInstr::mmo_iterator, unsigned>
1034 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
1035 
1036   // If either of the incoming memrefs are empty, we must be conservative and
1037   // treat this as if we've exhausted our space for memrefs and dropped them.
1038   if (memoperands_empty() || Other.memoperands_empty())
1039     return std::make_pair(nullptr, 0);
1040 
1041   // If both instructions have identical memrefs, we don't need to merge them.
1042   // Since many instructions have a single memref, and we tend to merge things
1043   // like pairs of loads from the same location, this catches a large number of
1044   // cases in practice.
1045   if (hasIdenticalMMOs(*this, Other))
1046     return std::make_pair(MemRefs, NumMemRefs);
1047 
1048   // TODO: consider uniquing elements within the operand lists to reduce
1049   // space usage and fall back to conservative information less often.
1050   size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
1051 
1052   // If we don't have enough room to store this many memrefs, be conservative
1053   // and drop them.  Otherwise, we'd fail asserts when trying to add them to
1054   // the new instruction.
1055   if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
1056     return std::make_pair(nullptr, 0);
1057 
1058   MachineFunction *MF = getParent()->getParent();
1059   mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
1060   mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
1061                                   MemBegin);
1062   MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
1063                      MemEnd);
1064   assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
1065          "missing memrefs");
1066 
1067   return std::make_pair(MemBegin, CombinedNumMemRefs);
1068 }
1069 
1070 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
1071   assert(!isBundledWithPred() && "Must be called on bundle header");
1072   for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
1073     if (MII->getDesc().getFlags() & Mask) {
1074       if (Type == AnyInBundle)
1075         return true;
1076     } else {
1077       if (Type == AllInBundle && !MII->isBundle())
1078         return false;
1079     }
1080     // This was the last instruction in the bundle.
1081     if (!MII->isBundledWithSucc())
1082       return Type == AllInBundle;
1083   }
1084 }
1085 
1086 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
1087                                  MICheckType Check) const {
1088   // If opcodes or number of operands are not the same then the two
1089   // instructions are obviously not identical.
1090   if (Other.getOpcode() != getOpcode() ||
1091       Other.getNumOperands() != getNumOperands())
1092     return false;
1093 
1094   if (isBundle()) {
1095     // We have passed the test above that both instructions have the same
1096     // opcode, so we know that both instructions are bundles here. Let's compare
1097     // MIs inside the bundle.
1098     assert(Other.isBundle() && "Expected that both instructions are bundles.");
1099     MachineBasicBlock::const_instr_iterator I1 = getIterator();
1100     MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
1101     // Loop until we analysed the last intruction inside at least one of the
1102     // bundles.
1103     while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
1104       ++I1;
1105       ++I2;
1106       if (!I1->isIdenticalTo(*I2, Check))
1107         return false;
1108     }
1109     // If we've reached the end of just one of the two bundles, but not both,
1110     // the instructions are not identical.
1111     if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
1112       return false;
1113   }
1114 
1115   // Check operands to make sure they match.
1116   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1117     const MachineOperand &MO = getOperand(i);
1118     const MachineOperand &OMO = Other.getOperand(i);
1119     if (!MO.isReg()) {
1120       if (!MO.isIdenticalTo(OMO))
1121         return false;
1122       continue;
1123     }
1124 
1125     // Clients may or may not want to ignore defs when testing for equality.
1126     // For example, machine CSE pass only cares about finding common
1127     // subexpressions, so it's safe to ignore virtual register defs.
1128     if (MO.isDef()) {
1129       if (Check == IgnoreDefs)
1130         continue;
1131       else if (Check == IgnoreVRegDefs) {
1132         if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1133             TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
1134           if (MO.getReg() != OMO.getReg())
1135             return false;
1136       } else {
1137         if (!MO.isIdenticalTo(OMO))
1138           return false;
1139         if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
1140           return false;
1141       }
1142     } else {
1143       if (!MO.isIdenticalTo(OMO))
1144         return false;
1145       if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
1146         return false;
1147     }
1148   }
1149   // If DebugLoc does not match then two dbg.values are not identical.
1150   if (isDebugValue())
1151     if (getDebugLoc() && Other.getDebugLoc() &&
1152         getDebugLoc() != Other.getDebugLoc())
1153       return false;
1154   return true;
1155 }
1156 
1157 MachineInstr *MachineInstr::removeFromParent() {
1158   assert(getParent() && "Not embedded in a basic block!");
1159   return getParent()->remove(this);
1160 }
1161 
1162 MachineInstr *MachineInstr::removeFromBundle() {
1163   assert(getParent() && "Not embedded in a basic block!");
1164   return getParent()->remove_instr(this);
1165 }
1166 
1167 void MachineInstr::eraseFromParent() {
1168   assert(getParent() && "Not embedded in a basic block!");
1169   getParent()->erase(this);
1170 }
1171 
1172 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1173   assert(getParent() && "Not embedded in a basic block!");
1174   MachineBasicBlock *MBB = getParent();
1175   MachineFunction *MF = MBB->getParent();
1176   assert(MF && "Not embedded in a function!");
1177 
1178   MachineInstr *MI = (MachineInstr *)this;
1179   MachineRegisterInfo &MRI = MF->getRegInfo();
1180 
1181   for (const MachineOperand &MO : MI->operands()) {
1182     if (!MO.isReg() || !MO.isDef())
1183       continue;
1184     unsigned Reg = MO.getReg();
1185     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1186       continue;
1187     MRI.markUsesInDebugValueAsUndef(Reg);
1188   }
1189   MI->eraseFromParent();
1190 }
1191 
1192 void MachineInstr::eraseFromBundle() {
1193   assert(getParent() && "Not embedded in a basic block!");
1194   getParent()->erase_instr(this);
1195 }
1196 
1197 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1198 ///
1199 unsigned MachineInstr::getNumExplicitOperands() const {
1200   unsigned NumOperands = MCID->getNumOperands();
1201   if (!MCID->isVariadic())
1202     return NumOperands;
1203 
1204   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1205     const MachineOperand &MO = getOperand(i);
1206     if (!MO.isReg() || !MO.isImplicit())
1207       NumOperands++;
1208   }
1209   return NumOperands;
1210 }
1211 
1212 void MachineInstr::bundleWithPred() {
1213   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1214   setFlag(BundledPred);
1215   MachineBasicBlock::instr_iterator Pred = getIterator();
1216   --Pred;
1217   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1218   Pred->setFlag(BundledSucc);
1219 }
1220 
1221 void MachineInstr::bundleWithSucc() {
1222   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1223   setFlag(BundledSucc);
1224   MachineBasicBlock::instr_iterator Succ = getIterator();
1225   ++Succ;
1226   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1227   Succ->setFlag(BundledPred);
1228 }
1229 
1230 void MachineInstr::unbundleFromPred() {
1231   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1232   clearFlag(BundledPred);
1233   MachineBasicBlock::instr_iterator Pred = getIterator();
1234   --Pred;
1235   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1236   Pred->clearFlag(BundledSucc);
1237 }
1238 
1239 void MachineInstr::unbundleFromSucc() {
1240   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1241   clearFlag(BundledSucc);
1242   MachineBasicBlock::instr_iterator Succ = getIterator();
1243   ++Succ;
1244   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1245   Succ->clearFlag(BundledPred);
1246 }
1247 
1248 bool MachineInstr::isStackAligningInlineAsm() const {
1249   if (isInlineAsm()) {
1250     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1251     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1252       return true;
1253   }
1254   return false;
1255 }
1256 
1257 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1258   assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1259   unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1260   return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1261 }
1262 
1263 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1264                                        unsigned *GroupNo) const {
1265   assert(isInlineAsm() && "Expected an inline asm instruction");
1266   assert(OpIdx < getNumOperands() && "OpIdx out of range");
1267 
1268   // Ignore queries about the initial operands.
1269   if (OpIdx < InlineAsm::MIOp_FirstOperand)
1270     return -1;
1271 
1272   unsigned Group = 0;
1273   unsigned NumOps;
1274   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1275        i += NumOps) {
1276     const MachineOperand &FlagMO = getOperand(i);
1277     // If we reach the implicit register operands, stop looking.
1278     if (!FlagMO.isImm())
1279       return -1;
1280     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1281     if (i + NumOps > OpIdx) {
1282       if (GroupNo)
1283         *GroupNo = Group;
1284       return i;
1285     }
1286     ++Group;
1287   }
1288   return -1;
1289 }
1290 
1291 const DILocalVariable *MachineInstr::getDebugVariable() const {
1292   assert(isDebugValue() && "not a DBG_VALUE");
1293   return cast<DILocalVariable>(getOperand(2).getMetadata());
1294 }
1295 
1296 const DIExpression *MachineInstr::getDebugExpression() const {
1297   assert(isDebugValue() && "not a DBG_VALUE");
1298   return cast<DIExpression>(getOperand(3).getMetadata());
1299 }
1300 
1301 const TargetRegisterClass*
1302 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1303                                     const TargetInstrInfo *TII,
1304                                     const TargetRegisterInfo *TRI) const {
1305   assert(getParent() && "Can't have an MBB reference here!");
1306   assert(getParent()->getParent() && "Can't have an MF reference here!");
1307   const MachineFunction &MF = *getParent()->getParent();
1308 
1309   // Most opcodes have fixed constraints in their MCInstrDesc.
1310   if (!isInlineAsm())
1311     return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1312 
1313   if (!getOperand(OpIdx).isReg())
1314     return nullptr;
1315 
1316   // For tied uses on inline asm, get the constraint from the def.
1317   unsigned DefIdx;
1318   if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1319     OpIdx = DefIdx;
1320 
1321   // Inline asm stores register class constraints in the flag word.
1322   int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1323   if (FlagIdx < 0)
1324     return nullptr;
1325 
1326   unsigned Flag = getOperand(FlagIdx).getImm();
1327   unsigned RCID;
1328   if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1329        InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1330        InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1331       InlineAsm::hasRegClassConstraint(Flag, RCID))
1332     return TRI->getRegClass(RCID);
1333 
1334   // Assume that all registers in a memory operand are pointers.
1335   if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1336     return TRI->getPointerRegClass(MF);
1337 
1338   return nullptr;
1339 }
1340 
1341 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1342     unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1343     const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1344   // Check every operands inside the bundle if we have
1345   // been asked to.
1346   if (ExploreBundle)
1347     for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1348          ++OpndIt)
1349       CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1350           OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1351   else
1352     // Otherwise, just check the current operands.
1353     for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1354       CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1355   return CurRC;
1356 }
1357 
1358 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1359     unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1360     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1361   assert(CurRC && "Invalid initial register class");
1362   // Check if Reg is constrained by some of its use/def from MI.
1363   const MachineOperand &MO = getOperand(OpIdx);
1364   if (!MO.isReg() || MO.getReg() != Reg)
1365     return CurRC;
1366   // If yes, accumulate the constraints through the operand.
1367   return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1368 }
1369 
1370 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1371     unsigned OpIdx, const TargetRegisterClass *CurRC,
1372     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1373   const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1374   const MachineOperand &MO = getOperand(OpIdx);
1375   assert(MO.isReg() &&
1376          "Cannot get register constraints for non-register operand");
1377   assert(CurRC && "Invalid initial register class");
1378   if (unsigned SubIdx = MO.getSubReg()) {
1379     if (OpRC)
1380       CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1381     else
1382       CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1383   } else if (OpRC)
1384     CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1385   return CurRC;
1386 }
1387 
1388 /// Return the number of instructions inside the MI bundle, not counting the
1389 /// header instruction.
1390 unsigned MachineInstr::getBundleSize() const {
1391   MachineBasicBlock::const_instr_iterator I = getIterator();
1392   unsigned Size = 0;
1393   while (I->isBundledWithSucc()) {
1394     ++Size;
1395     ++I;
1396   }
1397   return Size;
1398 }
1399 
1400 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1401 /// the given register (not considering sub/super-registers).
1402 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1403   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1404     const MachineOperand &MO = getOperand(i);
1405     if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1406       return true;
1407   }
1408   return false;
1409 }
1410 
1411 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1412 /// the specific register or -1 if it is not found. It further tightens
1413 /// the search criteria to a use that kills the register if isKill is true.
1414 int MachineInstr::findRegisterUseOperandIdx(
1415     unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
1416   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1417     const MachineOperand &MO = getOperand(i);
1418     if (!MO.isReg() || !MO.isUse())
1419       continue;
1420     unsigned MOReg = MO.getReg();
1421     if (!MOReg)
1422       continue;
1423     if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1424                          TargetRegisterInfo::isPhysicalRegister(Reg) &&
1425                          TRI->isSubRegister(MOReg, Reg)))
1426       if (!isKill || MO.isKill())
1427         return i;
1428   }
1429   return -1;
1430 }
1431 
1432 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1433 /// indicating if this instruction reads or writes Reg. This also considers
1434 /// partial defines.
1435 std::pair<bool,bool>
1436 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1437                                          SmallVectorImpl<unsigned> *Ops) const {
1438   bool PartDef = false; // Partial redefine.
1439   bool FullDef = false; // Full define.
1440   bool Use = false;
1441 
1442   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1443     const MachineOperand &MO = getOperand(i);
1444     if (!MO.isReg() || MO.getReg() != Reg)
1445       continue;
1446     if (Ops)
1447       Ops->push_back(i);
1448     if (MO.isUse())
1449       Use |= !MO.isUndef();
1450     else if (MO.getSubReg() && !MO.isUndef())
1451       // A partial <def,undef> doesn't count as reading the register.
1452       PartDef = true;
1453     else
1454       FullDef = true;
1455   }
1456   // A partial redefine uses Reg unless there is also a full define.
1457   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1458 }
1459 
1460 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1461 /// the specified register or -1 if it is not found. If isDead is true, defs
1462 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1463 /// also checks if there is a def of a super-register.
1464 int
1465 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1466                                         const TargetRegisterInfo *TRI) const {
1467   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1468   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1469     const MachineOperand &MO = getOperand(i);
1470     // Accept regmask operands when Overlap is set.
1471     // Ignore them when looking for a specific def operand (Overlap == false).
1472     if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1473       return i;
1474     if (!MO.isReg() || !MO.isDef())
1475       continue;
1476     unsigned MOReg = MO.getReg();
1477     bool Found = (MOReg == Reg);
1478     if (!Found && TRI && isPhys &&
1479         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1480       if (Overlap)
1481         Found = TRI->regsOverlap(MOReg, Reg);
1482       else
1483         Found = TRI->isSubRegister(MOReg, Reg);
1484     }
1485     if (Found && (!isDead || MO.isDead()))
1486       return i;
1487   }
1488   return -1;
1489 }
1490 
1491 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1492 /// operand list that is used to represent the predicate. It returns -1 if
1493 /// none is found.
1494 int MachineInstr::findFirstPredOperandIdx() const {
1495   // Don't call MCID.findFirstPredOperandIdx() because this variant
1496   // is sometimes called on an instruction that's not yet complete, and
1497   // so the number of operands is less than the MCID indicates. In
1498   // particular, the PTX target does this.
1499   const MCInstrDesc &MCID = getDesc();
1500   if (MCID.isPredicable()) {
1501     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1502       if (MCID.OpInfo[i].isPredicate())
1503         return i;
1504   }
1505 
1506   return -1;
1507 }
1508 
1509 // MachineOperand::TiedTo is 4 bits wide.
1510 const unsigned TiedMax = 15;
1511 
1512 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1513 ///
1514 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1515 /// field. TiedTo can have these values:
1516 ///
1517 /// 0:              Operand is not tied to anything.
1518 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1519 /// TiedMax:        Tied to an operand >= TiedMax-1.
1520 ///
1521 /// The tied def must be one of the first TiedMax operands on a normal
1522 /// instruction. INLINEASM instructions allow more tied defs.
1523 ///
1524 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1525   MachineOperand &DefMO = getOperand(DefIdx);
1526   MachineOperand &UseMO = getOperand(UseIdx);
1527   assert(DefMO.isDef() && "DefIdx must be a def operand");
1528   assert(UseMO.isUse() && "UseIdx must be a use operand");
1529   assert(!DefMO.isTied() && "Def is already tied to another use");
1530   assert(!UseMO.isTied() && "Use is already tied to another def");
1531 
1532   if (DefIdx < TiedMax)
1533     UseMO.TiedTo = DefIdx + 1;
1534   else {
1535     // Inline asm can use the group descriptors to find tied operands, but on
1536     // normal instruction, the tied def must be within the first TiedMax
1537     // operands.
1538     assert(isInlineAsm() && "DefIdx out of range");
1539     UseMO.TiedTo = TiedMax;
1540   }
1541 
1542   // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1543   DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1544 }
1545 
1546 /// Given the index of a tied register operand, find the operand it is tied to.
1547 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1548 /// which must exist.
1549 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1550   const MachineOperand &MO = getOperand(OpIdx);
1551   assert(MO.isTied() && "Operand isn't tied");
1552 
1553   // Normally TiedTo is in range.
1554   if (MO.TiedTo < TiedMax)
1555     return MO.TiedTo - 1;
1556 
1557   // Uses on normal instructions can be out of range.
1558   if (!isInlineAsm()) {
1559     // Normal tied defs must be in the 0..TiedMax-1 range.
1560     if (MO.isUse())
1561       return TiedMax - 1;
1562     // MO is a def. Search for the tied use.
1563     for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1564       const MachineOperand &UseMO = getOperand(i);
1565       if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1566         return i;
1567     }
1568     llvm_unreachable("Can't find tied use");
1569   }
1570 
1571   // Now deal with inline asm by parsing the operand group descriptor flags.
1572   // Find the beginning of each operand group.
1573   SmallVector<unsigned, 8> GroupIdx;
1574   unsigned OpIdxGroup = ~0u;
1575   unsigned NumOps;
1576   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1577        i += NumOps) {
1578     const MachineOperand &FlagMO = getOperand(i);
1579     assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1580     unsigned CurGroup = GroupIdx.size();
1581     GroupIdx.push_back(i);
1582     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1583     // OpIdx belongs to this operand group.
1584     if (OpIdx > i && OpIdx < i + NumOps)
1585       OpIdxGroup = CurGroup;
1586     unsigned TiedGroup;
1587     if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1588       continue;
1589     // Operands in this group are tied to operands in TiedGroup which must be
1590     // earlier. Find the number of operands between the two groups.
1591     unsigned Delta = i - GroupIdx[TiedGroup];
1592 
1593     // OpIdx is a use tied to TiedGroup.
1594     if (OpIdxGroup == CurGroup)
1595       return OpIdx - Delta;
1596 
1597     // OpIdx is a def tied to this use group.
1598     if (OpIdxGroup == TiedGroup)
1599       return OpIdx + Delta;
1600   }
1601   llvm_unreachable("Invalid tied operand on inline asm");
1602 }
1603 
1604 /// clearKillInfo - Clears kill flags on all operands.
1605 ///
1606 void MachineInstr::clearKillInfo() {
1607   for (MachineOperand &MO : operands()) {
1608     if (MO.isReg() && MO.isUse())
1609       MO.setIsKill(false);
1610   }
1611 }
1612 
1613 void MachineInstr::substituteRegister(unsigned FromReg,
1614                                       unsigned ToReg,
1615                                       unsigned SubIdx,
1616                                       const TargetRegisterInfo &RegInfo) {
1617   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1618     if (SubIdx)
1619       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1620     for (MachineOperand &MO : operands()) {
1621       if (!MO.isReg() || MO.getReg() != FromReg)
1622         continue;
1623       MO.substPhysReg(ToReg, RegInfo);
1624     }
1625   } else {
1626     for (MachineOperand &MO : operands()) {
1627       if (!MO.isReg() || MO.getReg() != FromReg)
1628         continue;
1629       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1630     }
1631   }
1632 }
1633 
1634 /// isSafeToMove - Return true if it is safe to move this instruction. If
1635 /// SawStore is set to true, it means that there is a store (or call) between
1636 /// the instruction's location and its intended destination.
1637 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1638   // Ignore stuff that we obviously can't move.
1639   //
1640   // Treat volatile loads as stores. This is not strictly necessary for
1641   // volatiles, but it is required for atomic loads. It is not allowed to move
1642   // a load across an atomic load with Ordering > Monotonic.
1643   if (mayStore() || isCall() ||
1644       (mayLoad() && hasOrderedMemoryRef())) {
1645     SawStore = true;
1646     return false;
1647   }
1648 
1649   if (isPosition() || isDebugValue() || isTerminator() ||
1650       hasUnmodeledSideEffects())
1651     return false;
1652 
1653   // See if this instruction does a load.  If so, we have to guarantee that the
1654   // loaded value doesn't change between the load and the its intended
1655   // destination. The check for isInvariantLoad gives the targe the chance to
1656   // classify the load as always returning a constant, e.g. a constant pool
1657   // load.
1658   if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1659     // Otherwise, this is a real load.  If there is a store between the load and
1660     // end of block, we can't move it.
1661     return !SawStore;
1662 
1663   return true;
1664 }
1665 
1666 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
1667                             bool UseTBAA) {
1668   const MachineFunction *MF = getParent()->getParent();
1669   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1670   const MachineFrameInfo &MFI = MF->getFrameInfo();
1671 
1672   // If neither instruction stores to memory, they can't alias in any
1673   // meaningful way, even if they read from the same address.
1674   if (!mayStore() && !Other.mayStore())
1675     return false;
1676 
1677   // Let the target decide if memory accesses cannot possibly overlap.
1678   if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
1679     return false;
1680 
1681   // FIXME: Need to handle multiple memory operands to support all targets.
1682   if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1683     return true;
1684 
1685   MachineMemOperand *MMOa = *memoperands_begin();
1686   MachineMemOperand *MMOb = *Other.memoperands_begin();
1687 
1688   // The following interface to AA is fashioned after DAGCombiner::isAlias
1689   // and operates with MachineMemOperand offset with some important
1690   // assumptions:
1691   //   - LLVM fundamentally assumes flat address spaces.
1692   //   - MachineOperand offset can *only* result from legalization and
1693   //     cannot affect queries other than the trivial case of overlap
1694   //     checking.
1695   //   - These offsets never wrap and never step outside
1696   //     of allocated objects.
1697   //   - There should never be any negative offsets here.
1698   //
1699   // FIXME: Modify API to hide this math from "user"
1700   // Even before we go to AA we can reason locally about some
1701   // memory objects. It can save compile time, and possibly catch some
1702   // corner cases not currently covered.
1703 
1704   int64_t OffsetA = MMOa->getOffset();
1705   int64_t OffsetB = MMOb->getOffset();
1706 
1707   int64_t MinOffset = std::min(OffsetA, OffsetB);
1708   int64_t WidthA = MMOa->getSize();
1709   int64_t WidthB = MMOb->getSize();
1710   const Value *ValA = MMOa->getValue();
1711   const Value *ValB = MMOb->getValue();
1712   bool SameVal = (ValA && ValB && (ValA == ValB));
1713   if (!SameVal) {
1714     const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
1715     const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
1716     if (PSVa && ValB && !PSVa->mayAlias(&MFI))
1717       return false;
1718     if (PSVb && ValA && !PSVb->mayAlias(&MFI))
1719       return false;
1720     if (PSVa && PSVb && (PSVa == PSVb))
1721       SameVal = true;
1722   }
1723 
1724   if (SameVal) {
1725     int64_t MaxOffset = std::max(OffsetA, OffsetB);
1726     int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
1727     return (MinOffset + LowWidth > MaxOffset);
1728   }
1729 
1730   if (!AA)
1731     return true;
1732 
1733   if (!ValA || !ValB)
1734     return true;
1735 
1736   assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
1737   assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
1738 
1739   int64_t Overlapa = WidthA + OffsetA - MinOffset;
1740   int64_t Overlapb = WidthB + OffsetB - MinOffset;
1741 
1742   AliasResult AAResult = AA->alias(
1743       MemoryLocation(ValA, Overlapa,
1744                      UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1745       MemoryLocation(ValB, Overlapb,
1746                      UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1747 
1748   return (AAResult != NoAlias);
1749 }
1750 
1751 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1752 /// or volatile memory reference, or if the information describing the memory
1753 /// reference is not available. Return false if it is known to have no ordered
1754 /// memory references.
1755 bool MachineInstr::hasOrderedMemoryRef() const {
1756   // An instruction known never to access memory won't have a volatile access.
1757   if (!mayStore() &&
1758       !mayLoad() &&
1759       !isCall() &&
1760       !hasUnmodeledSideEffects())
1761     return false;
1762 
1763   // Otherwise, if the instruction has no memory reference information,
1764   // conservatively assume it wasn't preserved.
1765   if (memoperands_empty())
1766     return true;
1767 
1768   // Check if any of our memory operands are ordered.
1769   return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1770     return !MMO->isUnordered();
1771   });
1772 }
1773 
1774 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1775 /// trap and is loading from a location whose value is invariant across a run of
1776 /// this function.
1777 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
1778   // If the instruction doesn't load at all, it isn't an invariant load.
1779   if (!mayLoad())
1780     return false;
1781 
1782   // If the instruction has lost its memoperands, conservatively assume that
1783   // it may not be an invariant load.
1784   if (memoperands_empty())
1785     return false;
1786 
1787   const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1788 
1789   for (MachineMemOperand *MMO : memoperands()) {
1790     if (MMO->isVolatile()) return false;
1791     if (MMO->isStore()) return false;
1792     if (MMO->isInvariant() && MMO->isDereferenceable())
1793       continue;
1794 
1795     // A load from a constant PseudoSourceValue is invariant.
1796     if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1797       if (PSV->isConstant(&MFI))
1798         continue;
1799 
1800     if (const Value *V = MMO->getValue()) {
1801       // If we have an AliasAnalysis, ask it whether the memory is constant.
1802       if (AA &&
1803           AA->pointsToConstantMemory(
1804               MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1805         continue;
1806     }
1807 
1808     // Otherwise assume conservatively.
1809     return false;
1810   }
1811 
1812   // Everything checks out.
1813   return true;
1814 }
1815 
1816 /// isConstantValuePHI - If the specified instruction is a PHI that always
1817 /// merges together the same virtual register, return the register, otherwise
1818 /// return 0.
1819 unsigned MachineInstr::isConstantValuePHI() const {
1820   if (!isPHI())
1821     return 0;
1822   assert(getNumOperands() >= 3 &&
1823          "It's illegal to have a PHI without source operands");
1824 
1825   unsigned Reg = getOperand(1).getReg();
1826   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1827     if (getOperand(i).getReg() != Reg)
1828       return 0;
1829   return Reg;
1830 }
1831 
1832 bool MachineInstr::hasUnmodeledSideEffects() const {
1833   if (hasProperty(MCID::UnmodeledSideEffects))
1834     return true;
1835   if (isInlineAsm()) {
1836     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1837     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1838       return true;
1839   }
1840 
1841   return false;
1842 }
1843 
1844 bool MachineInstr::isLoadFoldBarrier() const {
1845   return mayStore() || isCall() || hasUnmodeledSideEffects();
1846 }
1847 
1848 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1849 ///
1850 bool MachineInstr::allDefsAreDead() const {
1851   for (const MachineOperand &MO : operands()) {
1852     if (!MO.isReg() || MO.isUse())
1853       continue;
1854     if (!MO.isDead())
1855       return false;
1856   }
1857   return true;
1858 }
1859 
1860 /// copyImplicitOps - Copy implicit register operands from specified
1861 /// instruction to this instruction.
1862 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1863                                    const MachineInstr &MI) {
1864   for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1865        i != e; ++i) {
1866     const MachineOperand &MO = MI.getOperand(i);
1867     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1868       addOperand(MF, MO);
1869   }
1870 }
1871 
1872 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1873 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1874   dbgs() << "  ";
1875   print(dbgs());
1876 }
1877 #endif
1878 
1879 void MachineInstr::print(raw_ostream &OS, bool SkipOpers, bool SkipDebugLoc,
1880                          const TargetInstrInfo *TII) const {
1881   const Module *M = nullptr;
1882   if (const MachineBasicBlock *MBB = getParent())
1883     if (const MachineFunction *MF = MBB->getParent())
1884       M = MF->getFunction()->getParent();
1885 
1886   ModuleSlotTracker MST(M);
1887   print(OS, MST, SkipOpers, SkipDebugLoc, TII);
1888 }
1889 
1890 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1891                          bool SkipOpers, bool SkipDebugLoc,
1892                          const TargetInstrInfo *TII) const {
1893   // We can be a bit tidier if we know the MachineFunction.
1894   const MachineFunction *MF = nullptr;
1895   const TargetRegisterInfo *TRI = nullptr;
1896   const MachineRegisterInfo *MRI = nullptr;
1897   const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1898 
1899   if (const MachineBasicBlock *MBB = getParent()) {
1900     MF = MBB->getParent();
1901     if (MF) {
1902       MRI = &MF->getRegInfo();
1903       TRI = MF->getSubtarget().getRegisterInfo();
1904       if (!TII)
1905         TII = MF->getSubtarget().getInstrInfo();
1906       IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
1907     }
1908   }
1909 
1910   // Save a list of virtual registers.
1911   SmallVector<unsigned, 8> VirtRegs;
1912 
1913   // Print explicitly defined operands on the left of an assignment syntax.
1914   unsigned StartOp = 0, e = getNumOperands();
1915   for (; StartOp < e && getOperand(StartOp).isReg() &&
1916          getOperand(StartOp).isDef() &&
1917          !getOperand(StartOp).isImplicit();
1918        ++StartOp) {
1919     if (StartOp != 0) OS << ", ";
1920     getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
1921     unsigned Reg = getOperand(StartOp).getReg();
1922     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1923       VirtRegs.push_back(Reg);
1924       LLT Ty = MRI ? MRI->getType(Reg) : LLT{};
1925       if (Ty.isValid())
1926         OS << '(' << Ty << ')';
1927     }
1928   }
1929 
1930   if (StartOp != 0)
1931     OS << " = ";
1932 
1933   // Print the opcode name.
1934   if (TII)
1935     OS << TII->getName(getOpcode());
1936   else
1937     OS << "UNKNOWN";
1938 
1939   if (SkipOpers)
1940     return;
1941 
1942   // Print the rest of the operands.
1943   bool FirstOp = true;
1944   unsigned AsmDescOp = ~0u;
1945   unsigned AsmOpCount = 0;
1946 
1947   if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1948     // Print asm string.
1949     OS << " ";
1950     getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1951 
1952     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1953     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1954     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1955       OS << " [sideeffect]";
1956     if (ExtraInfo & InlineAsm::Extra_MayLoad)
1957       OS << " [mayload]";
1958     if (ExtraInfo & InlineAsm::Extra_MayStore)
1959       OS << " [maystore]";
1960     if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1961       OS << " [isconvergent]";
1962     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1963       OS << " [alignstack]";
1964     if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1965       OS << " [attdialect]";
1966     if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1967       OS << " [inteldialect]";
1968 
1969     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1970     FirstOp = false;
1971   }
1972 
1973   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1974     const MachineOperand &MO = getOperand(i);
1975 
1976     if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1977       VirtRegs.push_back(MO.getReg());
1978 
1979     if (FirstOp) FirstOp = false; else OS << ",";
1980     OS << " ";
1981     if (i < getDesc().NumOperands) {
1982       const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1983       if (MCOI.isPredicate())
1984         OS << "pred:";
1985       if (MCOI.isOptionalDef())
1986         OS << "opt:";
1987     }
1988     if (isDebugValue() && MO.isMetadata()) {
1989       // Pretty print DBG_VALUE instructions.
1990       auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1991       if (DIV && !DIV->getName().empty())
1992         OS << "!\"" << DIV->getName() << '\"';
1993       else
1994         MO.print(OS, MST, TRI);
1995     } else if (TRI && (isInsertSubreg() || isRegSequence() ||
1996                        (isSubregToReg() && i == 3)) && MO.isImm()) {
1997       OS << TRI->getSubRegIndexName(MO.getImm());
1998     } else if (i == AsmDescOp && MO.isImm()) {
1999       // Pretty print the inline asm operand descriptor.
2000       OS << '$' << AsmOpCount++;
2001       unsigned Flag = MO.getImm();
2002       switch (InlineAsm::getKind(Flag)) {
2003       case InlineAsm::Kind_RegUse:             OS << ":[reguse"; break;
2004       case InlineAsm::Kind_RegDef:             OS << ":[regdef"; break;
2005       case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
2006       case InlineAsm::Kind_Clobber:            OS << ":[clobber"; break;
2007       case InlineAsm::Kind_Imm:                OS << ":[imm"; break;
2008       case InlineAsm::Kind_Mem:                OS << ":[mem"; break;
2009       default: OS << ":[??" << InlineAsm::getKind(Flag); break;
2010       }
2011 
2012       unsigned RCID = 0;
2013       if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
2014           InlineAsm::hasRegClassConstraint(Flag, RCID)) {
2015         if (TRI) {
2016           OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
2017         } else
2018           OS << ":RC" << RCID;
2019       }
2020 
2021       if (InlineAsm::isMemKind(Flag)) {
2022         unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
2023         switch (MCID) {
2024         case InlineAsm::Constraint_es: OS << ":es"; break;
2025         case InlineAsm::Constraint_i:  OS << ":i"; break;
2026         case InlineAsm::Constraint_m:  OS << ":m"; break;
2027         case InlineAsm::Constraint_o:  OS << ":o"; break;
2028         case InlineAsm::Constraint_v:  OS << ":v"; break;
2029         case InlineAsm::Constraint_Q:  OS << ":Q"; break;
2030         case InlineAsm::Constraint_R:  OS << ":R"; break;
2031         case InlineAsm::Constraint_S:  OS << ":S"; break;
2032         case InlineAsm::Constraint_T:  OS << ":T"; break;
2033         case InlineAsm::Constraint_Um: OS << ":Um"; break;
2034         case InlineAsm::Constraint_Un: OS << ":Un"; break;
2035         case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
2036         case InlineAsm::Constraint_Us: OS << ":Us"; break;
2037         case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
2038         case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
2039         case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
2040         case InlineAsm::Constraint_X:  OS << ":X"; break;
2041         case InlineAsm::Constraint_Z:  OS << ":Z"; break;
2042         case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
2043         case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
2044         default: OS << ":?"; break;
2045         }
2046       }
2047 
2048       unsigned TiedTo = 0;
2049       if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
2050         OS << " tiedto:$" << TiedTo;
2051 
2052       OS << ']';
2053 
2054       // Compute the index of the next operand descriptor.
2055       AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
2056     } else
2057       MO.print(OS, MST, TRI);
2058   }
2059 
2060   bool HaveSemi = false;
2061   const unsigned PrintableFlags = FrameSetup | FrameDestroy;
2062   if (Flags & PrintableFlags) {
2063     if (!HaveSemi) {
2064       OS << ";";
2065       HaveSemi = true;
2066     }
2067     OS << " flags: ";
2068 
2069     if (Flags & FrameSetup)
2070       OS << "FrameSetup";
2071 
2072     if (Flags & FrameDestroy)
2073       OS << "FrameDestroy";
2074   }
2075 
2076   if (!memoperands_empty()) {
2077     if (!HaveSemi) {
2078       OS << ";";
2079       HaveSemi = true;
2080     }
2081 
2082     OS << " mem:";
2083     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
2084          i != e; ++i) {
2085       (*i)->print(OS, MST);
2086       if (std::next(i) != e)
2087         OS << " ";
2088     }
2089   }
2090 
2091   // Print the regclass of any virtual registers encountered.
2092   if (MRI && !VirtRegs.empty()) {
2093     if (!HaveSemi) {
2094       OS << ";";
2095       HaveSemi = true;
2096     }
2097     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
2098       const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
2099       if (!RC)
2100         continue;
2101       // Generic virtual registers do not have register classes.
2102       if (RC.is<const RegisterBank *>())
2103         OS << " " << RC.get<const RegisterBank *>()->getName();
2104       else
2105         OS << " "
2106            << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
2107       OS << ':' << PrintReg(VirtRegs[i]);
2108       for (unsigned j = i+1; j != VirtRegs.size();) {
2109         if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
2110           ++j;
2111           continue;
2112         }
2113         if (VirtRegs[i] != VirtRegs[j])
2114           OS << "," << PrintReg(VirtRegs[j]);
2115         VirtRegs.erase(VirtRegs.begin()+j);
2116       }
2117     }
2118   }
2119 
2120   // Print debug location information.
2121   if (isDebugValue() && getOperand(e - 2).isMetadata()) {
2122     if (!HaveSemi)
2123       OS << ";";
2124     auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
2125     OS << " line no:" <<  DV->getLine();
2126     if (auto *InlinedAt = debugLoc->getInlinedAt()) {
2127       DebugLoc InlinedAtDL(InlinedAt);
2128       if (InlinedAtDL && MF) {
2129         OS << " inlined @[ ";
2130         InlinedAtDL.print(OS);
2131         OS << " ]";
2132       }
2133     }
2134     if (isIndirectDebugValue())
2135       OS << " indirect";
2136   } else if (SkipDebugLoc) {
2137     return;
2138   } else if (debugLoc && MF) {
2139     if (!HaveSemi)
2140       OS << ";";
2141     OS << " dbg:";
2142     debugLoc.print(OS);
2143   }
2144 
2145   OS << '\n';
2146 }
2147 
2148 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
2149                                      const TargetRegisterInfo *RegInfo,
2150                                      bool AddIfNotFound) {
2151   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
2152   bool hasAliases = isPhysReg &&
2153     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
2154   bool Found = false;
2155   SmallVector<unsigned,4> DeadOps;
2156   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2157     MachineOperand &MO = getOperand(i);
2158     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
2159       continue;
2160 
2161     // DEBUG_VALUE nodes do not contribute to code generation and should
2162     // always be ignored. Failure to do so may result in trying to modify
2163     // KILL flags on DEBUG_VALUE nodes.
2164     if (MO.isDebug())
2165       continue;
2166 
2167     unsigned Reg = MO.getReg();
2168     if (!Reg)
2169       continue;
2170 
2171     if (Reg == IncomingReg) {
2172       if (!Found) {
2173         if (MO.isKill())
2174           // The register is already marked kill.
2175           return true;
2176         if (isPhysReg && isRegTiedToDefOperand(i))
2177           // Two-address uses of physregs must not be marked kill.
2178           return true;
2179         MO.setIsKill();
2180         Found = true;
2181       }
2182     } else if (hasAliases && MO.isKill() &&
2183                TargetRegisterInfo::isPhysicalRegister(Reg)) {
2184       // A super-register kill already exists.
2185       if (RegInfo->isSuperRegister(IncomingReg, Reg))
2186         return true;
2187       if (RegInfo->isSubRegister(IncomingReg, Reg))
2188         DeadOps.push_back(i);
2189     }
2190   }
2191 
2192   // Trim unneeded kill operands.
2193   while (!DeadOps.empty()) {
2194     unsigned OpIdx = DeadOps.back();
2195     if (getOperand(OpIdx).isImplicit())
2196       RemoveOperand(OpIdx);
2197     else
2198       getOperand(OpIdx).setIsKill(false);
2199     DeadOps.pop_back();
2200   }
2201 
2202   // If not found, this means an alias of one of the operands is killed. Add a
2203   // new implicit operand if required.
2204   if (!Found && AddIfNotFound) {
2205     addOperand(MachineOperand::CreateReg(IncomingReg,
2206                                          false /*IsDef*/,
2207                                          true  /*IsImp*/,
2208                                          true  /*IsKill*/));
2209     return true;
2210   }
2211   return Found;
2212 }
2213 
2214 void MachineInstr::clearRegisterKills(unsigned Reg,
2215                                       const TargetRegisterInfo *RegInfo) {
2216   if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2217     RegInfo = nullptr;
2218   for (MachineOperand &MO : operands()) {
2219     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2220       continue;
2221     unsigned OpReg = MO.getReg();
2222     if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2223       MO.setIsKill(false);
2224   }
2225 }
2226 
2227 bool MachineInstr::addRegisterDead(unsigned Reg,
2228                                    const TargetRegisterInfo *RegInfo,
2229                                    bool AddIfNotFound) {
2230   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2231   bool hasAliases = isPhysReg &&
2232     MCRegAliasIterator(Reg, RegInfo, false).isValid();
2233   bool Found = false;
2234   SmallVector<unsigned,4> DeadOps;
2235   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2236     MachineOperand &MO = getOperand(i);
2237     if (!MO.isReg() || !MO.isDef())
2238       continue;
2239     unsigned MOReg = MO.getReg();
2240     if (!MOReg)
2241       continue;
2242 
2243     if (MOReg == Reg) {
2244       MO.setIsDead();
2245       Found = true;
2246     } else if (hasAliases && MO.isDead() &&
2247                TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2248       // There exists a super-register that's marked dead.
2249       if (RegInfo->isSuperRegister(Reg, MOReg))
2250         return true;
2251       if (RegInfo->isSubRegister(Reg, MOReg))
2252         DeadOps.push_back(i);
2253     }
2254   }
2255 
2256   // Trim unneeded dead operands.
2257   while (!DeadOps.empty()) {
2258     unsigned OpIdx = DeadOps.back();
2259     if (getOperand(OpIdx).isImplicit())
2260       RemoveOperand(OpIdx);
2261     else
2262       getOperand(OpIdx).setIsDead(false);
2263     DeadOps.pop_back();
2264   }
2265 
2266   // If not found, this means an alias of one of the operands is dead. Add a
2267   // new implicit operand if required.
2268   if (Found || !AddIfNotFound)
2269     return Found;
2270 
2271   addOperand(MachineOperand::CreateReg(Reg,
2272                                        true  /*IsDef*/,
2273                                        true  /*IsImp*/,
2274                                        false /*IsKill*/,
2275                                        true  /*IsDead*/));
2276   return true;
2277 }
2278 
2279 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2280   for (MachineOperand &MO : operands()) {
2281     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2282       continue;
2283     MO.setIsDead(false);
2284   }
2285 }
2286 
2287 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2288   for (MachineOperand &MO : operands()) {
2289     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2290       continue;
2291     MO.setIsUndef(IsUndef);
2292   }
2293 }
2294 
2295 void MachineInstr::addRegisterDefined(unsigned Reg,
2296                                       const TargetRegisterInfo *RegInfo) {
2297   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2298     MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2299     if (MO)
2300       return;
2301   } else {
2302     for (const MachineOperand &MO : operands()) {
2303       if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2304           MO.getSubReg() == 0)
2305         return;
2306     }
2307   }
2308   addOperand(MachineOperand::CreateReg(Reg,
2309                                        true  /*IsDef*/,
2310                                        true  /*IsImp*/));
2311 }
2312 
2313 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2314                                          const TargetRegisterInfo &TRI) {
2315   bool HasRegMask = false;
2316   for (MachineOperand &MO : operands()) {
2317     if (MO.isRegMask()) {
2318       HasRegMask = true;
2319       continue;
2320     }
2321     if (!MO.isReg() || !MO.isDef()) continue;
2322     unsigned Reg = MO.getReg();
2323     if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2324     // If there are no uses, including partial uses, the def is dead.
2325     if (llvm::none_of(UsedRegs,
2326                       [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2327       MO.setIsDead();
2328   }
2329 
2330   // This is a call with a register mask operand.
2331   // Mask clobbers are always dead, so add defs for the non-dead defines.
2332   if (HasRegMask)
2333     for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2334          I != E; ++I)
2335       addRegisterDefined(*I, &TRI);
2336 }
2337 
2338 unsigned
2339 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2340   // Build up a buffer of hash code components.
2341   SmallVector<size_t, 8> HashComponents;
2342   HashComponents.reserve(MI->getNumOperands() + 1);
2343   HashComponents.push_back(MI->getOpcode());
2344   for (const MachineOperand &MO : MI->operands()) {
2345     if (MO.isReg() && MO.isDef() &&
2346         TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2347       continue;  // Skip virtual register defs.
2348 
2349     HashComponents.push_back(hash_value(MO));
2350   }
2351   return hash_combine_range(HashComponents.begin(), HashComponents.end());
2352 }
2353 
2354 void MachineInstr::emitError(StringRef Msg) const {
2355   // Find the source location cookie.
2356   unsigned LocCookie = 0;
2357   const MDNode *LocMD = nullptr;
2358   for (unsigned i = getNumOperands(); i != 0; --i) {
2359     if (getOperand(i-1).isMetadata() &&
2360         (LocMD = getOperand(i-1).getMetadata()) &&
2361         LocMD->getNumOperands() != 0) {
2362       if (const ConstantInt *CI =
2363               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2364         LocCookie = CI->getZExtValue();
2365         break;
2366       }
2367     }
2368   }
2369 
2370   if (const MachineBasicBlock *MBB = getParent())
2371     if (const MachineFunction *MF = MBB->getParent())
2372       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2373   report_fatal_error(Msg);
2374 }
2375 
2376 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2377                                   const MCInstrDesc &MCID, bool IsIndirect,
2378                                   unsigned Reg, const MDNode *Variable,
2379                                   const MDNode *Expr) {
2380   assert(isa<DILocalVariable>(Variable) && "not a variable");
2381   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2382   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2383          "Expected inlined-at fields to agree");
2384   if (IsIndirect)
2385     return BuildMI(MF, DL, MCID)
2386         .addReg(Reg, RegState::Debug)
2387         .addImm(0U)
2388         .addMetadata(Variable)
2389         .addMetadata(Expr);
2390   else
2391     return BuildMI(MF, DL, MCID)
2392         .addReg(Reg, RegState::Debug)
2393         .addReg(0U, RegState::Debug)
2394         .addMetadata(Variable)
2395         .addMetadata(Expr);
2396 }
2397 
2398 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2399                                   MachineBasicBlock::iterator I,
2400                                   const DebugLoc &DL, const MCInstrDesc &MCID,
2401                                   bool IsIndirect, unsigned Reg,
2402                                   const MDNode *Variable, const MDNode *Expr) {
2403   assert(isa<DILocalVariable>(Variable) && "not a variable");
2404   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2405   MachineFunction &MF = *BB.getParent();
2406   MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
2407   BB.insert(I, MI);
2408   return MachineInstrBuilder(MF, MI);
2409 }
2410 
2411 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
2412 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
2413 static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
2414   assert(MI.getOperand(0).isReg() && "can't spill non-register");
2415   assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
2416          "Expected inlined-at fields to agree");
2417 
2418   const DIExpression *Expr = MI.getDebugExpression();
2419   if (MI.isIndirectDebugValue()) {
2420     assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
2421     Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
2422   }
2423   return Expr;
2424 }
2425 
2426 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2427                                           MachineBasicBlock::iterator I,
2428                                           const MachineInstr &Orig,
2429                                           int FrameIndex) {
2430   const DIExpression *Expr = computeExprForSpill(Orig);
2431   return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
2432       .addFrameIndex(FrameIndex)
2433       .addImm(0U)
2434       .addMetadata(Orig.getDebugVariable())
2435       .addMetadata(Expr);
2436 }
2437 
2438 void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
2439   const DIExpression *Expr = computeExprForSpill(Orig);
2440   Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
2441   Orig.getOperand(1).ChangeToImmediate(0U);
2442   Orig.getOperand(3).setMetadata(Expr);
2443 }
2444