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()->getMF();
315     const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
316     unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
317 
318     // Deep compare of the two RegMasks
319     return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
320   }
321   case MachineOperand::MO_MCSymbol:
322     return getMCSymbol() == Other.getMCSymbol();
323   case MachineOperand::MO_CFIIndex:
324     return getCFIIndex() == Other.getCFIIndex();
325   case MachineOperand::MO_Metadata:
326     return getMetadata() == Other.getMetadata();
327   case MachineOperand::MO_IntrinsicID:
328     return getIntrinsicID() == Other.getIntrinsicID();
329   case MachineOperand::MO_Predicate:
330     return getPredicate() == Other.getPredicate();
331   }
332   llvm_unreachable("Invalid machine operand type");
333 }
334 
335 // Note: this must stay exactly in sync with isIdenticalTo above.
336 hash_code llvm::hash_value(const MachineOperand &MO) {
337   switch (MO.getType()) {
338   case MachineOperand::MO_Register:
339     // Register operands don't have target flags.
340     return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
341   case MachineOperand::MO_Immediate:
342     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
343   case MachineOperand::MO_CImmediate:
344     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
345   case MachineOperand::MO_FPImmediate:
346     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
347   case MachineOperand::MO_MachineBasicBlock:
348     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
349   case MachineOperand::MO_FrameIndex:
350     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
351   case MachineOperand::MO_ConstantPoolIndex:
352   case MachineOperand::MO_TargetIndex:
353     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
354                         MO.getOffset());
355   case MachineOperand::MO_JumpTableIndex:
356     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
357   case MachineOperand::MO_ExternalSymbol:
358     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
359                         MO.getSymbolName());
360   case MachineOperand::MO_GlobalAddress:
361     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
362                         MO.getOffset());
363   case MachineOperand::MO_BlockAddress:
364     return hash_combine(MO.getType(), MO.getTargetFlags(),
365                         MO.getBlockAddress(), MO.getOffset());
366   case MachineOperand::MO_RegisterMask:
367   case MachineOperand::MO_RegisterLiveOut:
368     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
369   case MachineOperand::MO_Metadata:
370     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
371   case MachineOperand::MO_MCSymbol:
372     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
373   case MachineOperand::MO_CFIIndex:
374     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
375   case MachineOperand::MO_IntrinsicID:
376     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
377   case MachineOperand::MO_Predicate:
378     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
379   }
380   llvm_unreachable("Invalid machine operand type");
381 }
382 
383 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
384                            const TargetIntrinsicInfo *IntrinsicInfo) const {
385   ModuleSlotTracker DummyMST(nullptr);
386   print(OS, DummyMST, TRI, IntrinsicInfo);
387 }
388 
389 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
390                            const TargetRegisterInfo *TRI,
391                            const TargetIntrinsicInfo *IntrinsicInfo) const {
392   switch (getType()) {
393   case MachineOperand::MO_Register:
394     OS << PrintReg(getReg(), TRI, getSubReg());
395 
396     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
397         isInternalRead() || isEarlyClobber() || isTied()) {
398       OS << '<';
399       bool NeedComma = false;
400       if (isDef()) {
401         if (NeedComma) OS << ',';
402         if (isEarlyClobber())
403           OS << "earlyclobber,";
404         if (isImplicit())
405           OS << "imp-";
406         OS << "def";
407         NeedComma = true;
408         // <def,read-undef> only makes sense when getSubReg() is set.
409         // Don't clutter the output otherwise.
410         if (isUndef() && getSubReg())
411           OS << ",read-undef";
412       } else if (isImplicit()) {
413         OS << "imp-use";
414         NeedComma = true;
415       }
416 
417       if (isKill()) {
418         if (NeedComma) OS << ',';
419         OS << "kill";
420         NeedComma = true;
421       }
422       if (isDead()) {
423         if (NeedComma) OS << ',';
424         OS << "dead";
425         NeedComma = true;
426       }
427       if (isUndef() && isUse()) {
428         if (NeedComma) OS << ',';
429         OS << "undef";
430         NeedComma = true;
431       }
432       if (isInternalRead()) {
433         if (NeedComma) OS << ',';
434         OS << "internal";
435         NeedComma = true;
436       }
437       if (isTied()) {
438         if (NeedComma) OS << ',';
439         OS << "tied";
440         if (TiedTo != 15)
441           OS << unsigned(TiedTo - 1);
442       }
443       OS << '>';
444     }
445     break;
446   case MachineOperand::MO_Immediate:
447     OS << getImm();
448     break;
449   case MachineOperand::MO_CImmediate:
450     getCImm()->getValue().print(OS, false);
451     break;
452   case MachineOperand::MO_FPImmediate:
453     if (getFPImm()->getType()->isFloatTy()) {
454       OS << getFPImm()->getValueAPF().convertToFloat();
455     } else if (getFPImm()->getType()->isHalfTy()) {
456       APFloat APF = getFPImm()->getValueAPF();
457       bool Unused;
458       APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &Unused);
459       OS << "half " << APF.convertToFloat();
460     } else if (getFPImm()->getType()->isFP128Ty()) {
461       APFloat APF = getFPImm()->getValueAPF();
462       SmallString<16> Str;
463       getFPImm()->getValueAPF().toString(Str);
464       OS << "quad " << Str;
465     } else if (getFPImm()->getType()->isX86_FP80Ty()) {
466       APFloat APF = getFPImm()->getValueAPF();
467       OS << "x86_fp80 0xK";
468       APInt API = APF.bitcastToAPInt();
469       OS << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
470                                  /*Upper=*/true);
471       OS << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
472                                  /*Upper=*/true);
473     } else {
474       OS << getFPImm()->getValueAPF().convertToDouble();
475     }
476     break;
477   case MachineOperand::MO_MachineBasicBlock:
478     OS << "<BB#" << getMBB()->getNumber() << ">";
479     break;
480   case MachineOperand::MO_FrameIndex:
481     OS << "<fi#" << getIndex() << '>';
482     break;
483   case MachineOperand::MO_ConstantPoolIndex:
484     OS << "<cp#" << getIndex();
485     if (getOffset()) OS << "+" << getOffset();
486     OS << '>';
487     break;
488   case MachineOperand::MO_TargetIndex:
489     OS << "<ti#" << getIndex();
490     if (getOffset()) OS << "+" << getOffset();
491     OS << '>';
492     break;
493   case MachineOperand::MO_JumpTableIndex:
494     OS << "<jt#" << getIndex() << '>';
495     break;
496   case MachineOperand::MO_GlobalAddress:
497     OS << "<ga:";
498     getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
499     if (getOffset()) OS << "+" << getOffset();
500     OS << '>';
501     break;
502   case MachineOperand::MO_ExternalSymbol:
503     OS << "<es:" << getSymbolName();
504     if (getOffset()) OS << "+" << getOffset();
505     OS << '>';
506     break;
507   case MachineOperand::MO_BlockAddress:
508     OS << '<';
509     getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
510     if (getOffset()) OS << "+" << getOffset();
511     OS << '>';
512     break;
513   case MachineOperand::MO_RegisterMask: {
514     unsigned NumRegsInMask = 0;
515     unsigned NumRegsEmitted = 0;
516     OS << "<regmask";
517     for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
518       unsigned MaskWord = i / 32;
519       unsigned MaskBit = i % 32;
520       if (getRegMask()[MaskWord] & (1 << MaskBit)) {
521         if (PrintRegMaskNumRegs < 0 ||
522             NumRegsEmitted <= static_cast<unsigned>(PrintRegMaskNumRegs)) {
523           OS << " " << PrintReg(i, TRI);
524           NumRegsEmitted++;
525         }
526         NumRegsInMask++;
527       }
528     }
529     if (NumRegsEmitted != NumRegsInMask)
530       OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
531     OS << ">";
532     break;
533   }
534   case MachineOperand::MO_RegisterLiveOut:
535     OS << "<regliveout>";
536     break;
537   case MachineOperand::MO_Metadata:
538     OS << '<';
539     getMetadata()->printAsOperand(OS, MST);
540     OS << '>';
541     break;
542   case MachineOperand::MO_MCSymbol:
543     OS << "<MCSym=" << *getMCSymbol() << '>';
544     break;
545   case MachineOperand::MO_CFIIndex:
546     OS << "<call frame instruction>";
547     break;
548   case MachineOperand::MO_IntrinsicID: {
549     Intrinsic::ID ID = getIntrinsicID();
550     if (ID < Intrinsic::num_intrinsics)
551       OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << '>';
552     else if (IntrinsicInfo)
553       OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << '>';
554     else
555       OS << "<intrinsic:" << ID << '>';
556     break;
557   }
558   case MachineOperand::MO_Predicate: {
559     auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
560     OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
561        << CmpInst::getPredicateName(Pred) << '>';
562     break;
563   }
564   }
565   if (unsigned TF = getTargetFlags())
566     OS << "[TF=" << TF << ']';
567 }
568 
569 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
570 LLVM_DUMP_METHOD void MachineOperand::dump() const {
571   dbgs() << *this << '\n';
572 }
573 #endif
574 
575 //===----------------------------------------------------------------------===//
576 // MachineMemOperand Implementation
577 //===----------------------------------------------------------------------===//
578 
579 /// getAddrSpace - Return the LLVM IR address space number that this pointer
580 /// points into.
581 unsigned MachinePointerInfo::getAddrSpace() const {
582   if (V.isNull()) return 0;
583 
584   if (V.is<const PseudoSourceValue*>())
585     return V.get<const PseudoSourceValue*>()->getAddressSpace();
586 
587   return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
588 }
589 
590 /// isDereferenceable - Return true if V is always dereferenceable for
591 /// Offset + Size byte.
592 bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
593                                            const DataLayout &DL) const {
594   if (!V.is<const Value*>())
595     return false;
596 
597   const Value *BasePtr = V.get<const Value*>();
598   if (BasePtr == nullptr)
599     return false;
600 
601   return isDereferenceableAndAlignedPointer(
602       BasePtr, 1, APInt(DL.getPointerSizeInBits(), Offset + Size), DL);
603 }
604 
605 /// getConstantPool - Return a MachinePointerInfo record that refers to the
606 /// constant pool.
607 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
608   return MachinePointerInfo(MF.getPSVManager().getConstantPool());
609 }
610 
611 /// getFixedStack - Return a MachinePointerInfo record that refers to the
612 /// the specified FrameIndex.
613 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
614                                                      int FI, int64_t Offset) {
615   return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
616 }
617 
618 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
619   return MachinePointerInfo(MF.getPSVManager().getJumpTable());
620 }
621 
622 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
623   return MachinePointerInfo(MF.getPSVManager().getGOT());
624 }
625 
626 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
627                                                 int64_t Offset,
628                                                 uint8_t ID) {
629   return MachinePointerInfo(MF.getPSVManager().getStack(), Offset,ID);
630 }
631 
632 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
633                                      uint64_t s, unsigned int a,
634                                      const AAMDNodes &AAInfo,
635                                      const MDNode *Ranges,
636                                      SyncScope::ID SSID,
637                                      AtomicOrdering Ordering,
638                                      AtomicOrdering FailureOrdering)
639     : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
640       AAInfo(AAInfo), Ranges(Ranges) {
641   assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
642           isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
643          "invalid pointer value");
644   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
645   assert((isLoad() || isStore()) && "Not a load/store!");
646 
647   AtomicInfo.SSID = static_cast<unsigned>(SSID);
648   assert(getSyncScopeID() == SSID && "Value truncated");
649   AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
650   assert(getOrdering() == Ordering && "Value truncated");
651   AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
652   assert(getFailureOrdering() == FailureOrdering && "Value truncated");
653 }
654 
655 /// Profile - Gather unique data for the object.
656 ///
657 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
658   ID.AddInteger(getOffset());
659   ID.AddInteger(Size);
660   ID.AddPointer(getOpaqueValue());
661   ID.AddInteger(getFlags());
662   ID.AddInteger(getBaseAlignment());
663 }
664 
665 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
666   // The Value and Offset may differ due to CSE. But the flags and size
667   // should be the same.
668   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
669   assert(MMO->getSize() == getSize() && "Size mismatch!");
670 
671   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
672     // Update the alignment value.
673     BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
674     // Also update the base and offset, because the new alignment may
675     // not be applicable with the old ones.
676     PtrInfo = MMO->PtrInfo;
677   }
678 }
679 
680 /// getAlignment - Return the minimum known alignment in bytes of the
681 /// actual memory reference.
682 uint64_t MachineMemOperand::getAlignment() const {
683   return MinAlign(getBaseAlignment(), getOffset());
684 }
685 
686 void MachineMemOperand::print(raw_ostream &OS) const {
687   ModuleSlotTracker DummyMST(nullptr);
688   print(OS, DummyMST);
689 }
690 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
691   assert((isLoad() || isStore()) &&
692          "SV has to be a load, store or both.");
693 
694   if (isVolatile())
695     OS << "Volatile ";
696 
697   if (isLoad())
698     OS << "LD";
699   if (isStore())
700     OS << "ST";
701   OS << getSize();
702 
703   // Print the address information.
704   OS << "[";
705   if (const Value *V = getValue())
706     V->printAsOperand(OS, /*PrintType=*/false, MST);
707   else if (const PseudoSourceValue *PSV = getPseudoValue())
708     PSV->printCustom(OS);
709   else
710     OS << "<unknown>";
711 
712   unsigned AS = getAddrSpace();
713   if (AS != 0)
714     OS << "(addrspace=" << AS << ')';
715 
716   // If the alignment of the memory reference itself differs from the alignment
717   // of the base pointer, print the base alignment explicitly, next to the base
718   // pointer.
719   if (getBaseAlignment() != getAlignment())
720     OS << "(align=" << getBaseAlignment() << ")";
721 
722   if (getOffset() != 0)
723     OS << "+" << getOffset();
724   OS << "]";
725 
726   // Print the alignment of the reference.
727   if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
728     OS << "(align=" << getAlignment() << ")";
729 
730   // Print TBAA info.
731   if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
732     OS << "(tbaa=";
733     if (TBAAInfo->getNumOperands() > 0)
734       TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
735     else
736       OS << "<unknown>";
737     OS << ")";
738   }
739 
740   // Print AA scope info.
741   if (const MDNode *ScopeInfo = getAAInfo().Scope) {
742     OS << "(alias.scope=";
743     if (ScopeInfo->getNumOperands() > 0)
744       for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
745         ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
746         if (i != ie-1)
747           OS << ",";
748       }
749     else
750       OS << "<unknown>";
751     OS << ")";
752   }
753 
754   // Print AA noalias scope info.
755   if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
756     OS << "(noalias=";
757     if (NoAliasInfo->getNumOperands() > 0)
758       for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
759         NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
760         if (i != ie-1)
761           OS << ",";
762       }
763     else
764       OS << "<unknown>";
765     OS << ")";
766   }
767 
768   if (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 = getMF();
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::isVirtualRegister(MO.getReg()) ||
1133             !TargetRegisterInfo::isVirtualRegister(OMO.getReg()))
1134           if (!MO.isIdenticalTo(OMO))
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 const MachineFunction *MachineInstr::getMF() const {
1158   return getParent()->getParent();
1159 }
1160 
1161 MachineInstr *MachineInstr::removeFromParent() {
1162   assert(getParent() && "Not embedded in a basic block!");
1163   return getParent()->remove(this);
1164 }
1165 
1166 MachineInstr *MachineInstr::removeFromBundle() {
1167   assert(getParent() && "Not embedded in a basic block!");
1168   return getParent()->remove_instr(this);
1169 }
1170 
1171 void MachineInstr::eraseFromParent() {
1172   assert(getParent() && "Not embedded in a basic block!");
1173   getParent()->erase(this);
1174 }
1175 
1176 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1177   assert(getParent() && "Not embedded in a basic block!");
1178   MachineBasicBlock *MBB = getParent();
1179   MachineFunction *MF = MBB->getParent();
1180   assert(MF && "Not embedded in a function!");
1181 
1182   MachineInstr *MI = (MachineInstr *)this;
1183   MachineRegisterInfo &MRI = MF->getRegInfo();
1184 
1185   for (const MachineOperand &MO : MI->operands()) {
1186     if (!MO.isReg() || !MO.isDef())
1187       continue;
1188     unsigned Reg = MO.getReg();
1189     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1190       continue;
1191     MRI.markUsesInDebugValueAsUndef(Reg);
1192   }
1193   MI->eraseFromParent();
1194 }
1195 
1196 void MachineInstr::eraseFromBundle() {
1197   assert(getParent() && "Not embedded in a basic block!");
1198   getParent()->erase_instr(this);
1199 }
1200 
1201 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1202 ///
1203 unsigned MachineInstr::getNumExplicitOperands() const {
1204   unsigned NumOperands = MCID->getNumOperands();
1205   if (!MCID->isVariadic())
1206     return NumOperands;
1207 
1208   for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1209     const MachineOperand &MO = getOperand(i);
1210     if (!MO.isReg() || !MO.isImplicit())
1211       NumOperands++;
1212   }
1213   return NumOperands;
1214 }
1215 
1216 void MachineInstr::bundleWithPred() {
1217   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1218   setFlag(BundledPred);
1219   MachineBasicBlock::instr_iterator Pred = getIterator();
1220   --Pred;
1221   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1222   Pred->setFlag(BundledSucc);
1223 }
1224 
1225 void MachineInstr::bundleWithSucc() {
1226   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1227   setFlag(BundledSucc);
1228   MachineBasicBlock::instr_iterator Succ = getIterator();
1229   ++Succ;
1230   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1231   Succ->setFlag(BundledPred);
1232 }
1233 
1234 void MachineInstr::unbundleFromPred() {
1235   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1236   clearFlag(BundledPred);
1237   MachineBasicBlock::instr_iterator Pred = getIterator();
1238   --Pred;
1239   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1240   Pred->clearFlag(BundledSucc);
1241 }
1242 
1243 void MachineInstr::unbundleFromSucc() {
1244   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1245   clearFlag(BundledSucc);
1246   MachineBasicBlock::instr_iterator Succ = getIterator();
1247   ++Succ;
1248   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1249   Succ->clearFlag(BundledPred);
1250 }
1251 
1252 bool MachineInstr::isStackAligningInlineAsm() const {
1253   if (isInlineAsm()) {
1254     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1255     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1256       return true;
1257   }
1258   return false;
1259 }
1260 
1261 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1262   assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1263   unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1264   return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1265 }
1266 
1267 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1268                                        unsigned *GroupNo) const {
1269   assert(isInlineAsm() && "Expected an inline asm instruction");
1270   assert(OpIdx < getNumOperands() && "OpIdx out of range");
1271 
1272   // Ignore queries about the initial operands.
1273   if (OpIdx < InlineAsm::MIOp_FirstOperand)
1274     return -1;
1275 
1276   unsigned Group = 0;
1277   unsigned NumOps;
1278   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1279        i += NumOps) {
1280     const MachineOperand &FlagMO = getOperand(i);
1281     // If we reach the implicit register operands, stop looking.
1282     if (!FlagMO.isImm())
1283       return -1;
1284     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1285     if (i + NumOps > OpIdx) {
1286       if (GroupNo)
1287         *GroupNo = Group;
1288       return i;
1289     }
1290     ++Group;
1291   }
1292   return -1;
1293 }
1294 
1295 const DILocalVariable *MachineInstr::getDebugVariable() const {
1296   assert(isDebugValue() && "not a DBG_VALUE");
1297   return cast<DILocalVariable>(getOperand(2).getMetadata());
1298 }
1299 
1300 const DIExpression *MachineInstr::getDebugExpression() const {
1301   assert(isDebugValue() && "not a DBG_VALUE");
1302   return cast<DIExpression>(getOperand(3).getMetadata());
1303 }
1304 
1305 const TargetRegisterClass*
1306 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1307                                     const TargetInstrInfo *TII,
1308                                     const TargetRegisterInfo *TRI) const {
1309   assert(getParent() && "Can't have an MBB reference here!");
1310   assert(getMF() && "Can't have an MF reference here!");
1311   const MachineFunction &MF = *getMF();
1312 
1313   // Most opcodes have fixed constraints in their MCInstrDesc.
1314   if (!isInlineAsm())
1315     return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1316 
1317   if (!getOperand(OpIdx).isReg())
1318     return nullptr;
1319 
1320   // For tied uses on inline asm, get the constraint from the def.
1321   unsigned DefIdx;
1322   if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1323     OpIdx = DefIdx;
1324 
1325   // Inline asm stores register class constraints in the flag word.
1326   int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1327   if (FlagIdx < 0)
1328     return nullptr;
1329 
1330   unsigned Flag = getOperand(FlagIdx).getImm();
1331   unsigned RCID;
1332   if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1333        InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1334        InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1335       InlineAsm::hasRegClassConstraint(Flag, RCID))
1336     return TRI->getRegClass(RCID);
1337 
1338   // Assume that all registers in a memory operand are pointers.
1339   if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1340     return TRI->getPointerRegClass(MF);
1341 
1342   return nullptr;
1343 }
1344 
1345 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1346     unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1347     const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1348   // Check every operands inside the bundle if we have
1349   // been asked to.
1350   if (ExploreBundle)
1351     for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1352          ++OpndIt)
1353       CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1354           OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1355   else
1356     // Otherwise, just check the current operands.
1357     for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1358       CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1359   return CurRC;
1360 }
1361 
1362 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1363     unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1364     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1365   assert(CurRC && "Invalid initial register class");
1366   // Check if Reg is constrained by some of its use/def from MI.
1367   const MachineOperand &MO = getOperand(OpIdx);
1368   if (!MO.isReg() || MO.getReg() != Reg)
1369     return CurRC;
1370   // If yes, accumulate the constraints through the operand.
1371   return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1372 }
1373 
1374 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1375     unsigned OpIdx, const TargetRegisterClass *CurRC,
1376     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1377   const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1378   const MachineOperand &MO = getOperand(OpIdx);
1379   assert(MO.isReg() &&
1380          "Cannot get register constraints for non-register operand");
1381   assert(CurRC && "Invalid initial register class");
1382   if (unsigned SubIdx = MO.getSubReg()) {
1383     if (OpRC)
1384       CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1385     else
1386       CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1387   } else if (OpRC)
1388     CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1389   return CurRC;
1390 }
1391 
1392 /// Return the number of instructions inside the MI bundle, not counting the
1393 /// header instruction.
1394 unsigned MachineInstr::getBundleSize() const {
1395   MachineBasicBlock::const_instr_iterator I = getIterator();
1396   unsigned Size = 0;
1397   while (I->isBundledWithSucc()) {
1398     ++Size;
1399     ++I;
1400   }
1401   return Size;
1402 }
1403 
1404 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1405 /// the given register (not considering sub/super-registers).
1406 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1407   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1408     const MachineOperand &MO = getOperand(i);
1409     if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1410       return true;
1411   }
1412   return false;
1413 }
1414 
1415 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1416 /// the specific register or -1 if it is not found. It further tightens
1417 /// the search criteria to a use that kills the register if isKill is true.
1418 int MachineInstr::findRegisterUseOperandIdx(
1419     unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
1420   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1421     const MachineOperand &MO = getOperand(i);
1422     if (!MO.isReg() || !MO.isUse())
1423       continue;
1424     unsigned MOReg = MO.getReg();
1425     if (!MOReg)
1426       continue;
1427     if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1428                          TargetRegisterInfo::isPhysicalRegister(Reg) &&
1429                          TRI->isSubRegister(MOReg, Reg)))
1430       if (!isKill || MO.isKill())
1431         return i;
1432   }
1433   return -1;
1434 }
1435 
1436 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1437 /// indicating if this instruction reads or writes Reg. This also considers
1438 /// partial defines.
1439 std::pair<bool,bool>
1440 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1441                                          SmallVectorImpl<unsigned> *Ops) const {
1442   bool PartDef = false; // Partial redefine.
1443   bool FullDef = false; // Full define.
1444   bool Use = false;
1445 
1446   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1447     const MachineOperand &MO = getOperand(i);
1448     if (!MO.isReg() || MO.getReg() != Reg)
1449       continue;
1450     if (Ops)
1451       Ops->push_back(i);
1452     if (MO.isUse())
1453       Use |= !MO.isUndef();
1454     else if (MO.getSubReg() && !MO.isUndef())
1455       // A partial <def,undef> doesn't count as reading the register.
1456       PartDef = true;
1457     else
1458       FullDef = true;
1459   }
1460   // A partial redefine uses Reg unless there is also a full define.
1461   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1462 }
1463 
1464 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1465 /// the specified register or -1 if it is not found. If isDead is true, defs
1466 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1467 /// also checks if there is a def of a super-register.
1468 int
1469 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1470                                         const TargetRegisterInfo *TRI) const {
1471   bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1472   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1473     const MachineOperand &MO = getOperand(i);
1474     // Accept regmask operands when Overlap is set.
1475     // Ignore them when looking for a specific def operand (Overlap == false).
1476     if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1477       return i;
1478     if (!MO.isReg() || !MO.isDef())
1479       continue;
1480     unsigned MOReg = MO.getReg();
1481     bool Found = (MOReg == Reg);
1482     if (!Found && TRI && isPhys &&
1483         TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1484       if (Overlap)
1485         Found = TRI->regsOverlap(MOReg, Reg);
1486       else
1487         Found = TRI->isSubRegister(MOReg, Reg);
1488     }
1489     if (Found && (!isDead || MO.isDead()))
1490       return i;
1491   }
1492   return -1;
1493 }
1494 
1495 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1496 /// operand list that is used to represent the predicate. It returns -1 if
1497 /// none is found.
1498 int MachineInstr::findFirstPredOperandIdx() const {
1499   // Don't call MCID.findFirstPredOperandIdx() because this variant
1500   // is sometimes called on an instruction that's not yet complete, and
1501   // so the number of operands is less than the MCID indicates. In
1502   // particular, the PTX target does this.
1503   const MCInstrDesc &MCID = getDesc();
1504   if (MCID.isPredicable()) {
1505     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1506       if (MCID.OpInfo[i].isPredicate())
1507         return i;
1508   }
1509 
1510   return -1;
1511 }
1512 
1513 // MachineOperand::TiedTo is 4 bits wide.
1514 const unsigned TiedMax = 15;
1515 
1516 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1517 ///
1518 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1519 /// field. TiedTo can have these values:
1520 ///
1521 /// 0:              Operand is not tied to anything.
1522 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1523 /// TiedMax:        Tied to an operand >= TiedMax-1.
1524 ///
1525 /// The tied def must be one of the first TiedMax operands on a normal
1526 /// instruction. INLINEASM instructions allow more tied defs.
1527 ///
1528 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1529   MachineOperand &DefMO = getOperand(DefIdx);
1530   MachineOperand &UseMO = getOperand(UseIdx);
1531   assert(DefMO.isDef() && "DefIdx must be a def operand");
1532   assert(UseMO.isUse() && "UseIdx must be a use operand");
1533   assert(!DefMO.isTied() && "Def is already tied to another use");
1534   assert(!UseMO.isTied() && "Use is already tied to another def");
1535 
1536   if (DefIdx < TiedMax)
1537     UseMO.TiedTo = DefIdx + 1;
1538   else {
1539     // Inline asm can use the group descriptors to find tied operands, but on
1540     // normal instruction, the tied def must be within the first TiedMax
1541     // operands.
1542     assert(isInlineAsm() && "DefIdx out of range");
1543     UseMO.TiedTo = TiedMax;
1544   }
1545 
1546   // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1547   DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1548 }
1549 
1550 /// Given the index of a tied register operand, find the operand it is tied to.
1551 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1552 /// which must exist.
1553 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1554   const MachineOperand &MO = getOperand(OpIdx);
1555   assert(MO.isTied() && "Operand isn't tied");
1556 
1557   // Normally TiedTo is in range.
1558   if (MO.TiedTo < TiedMax)
1559     return MO.TiedTo - 1;
1560 
1561   // Uses on normal instructions can be out of range.
1562   if (!isInlineAsm()) {
1563     // Normal tied defs must be in the 0..TiedMax-1 range.
1564     if (MO.isUse())
1565       return TiedMax - 1;
1566     // MO is a def. Search for the tied use.
1567     for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1568       const MachineOperand &UseMO = getOperand(i);
1569       if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1570         return i;
1571     }
1572     llvm_unreachable("Can't find tied use");
1573   }
1574 
1575   // Now deal with inline asm by parsing the operand group descriptor flags.
1576   // Find the beginning of each operand group.
1577   SmallVector<unsigned, 8> GroupIdx;
1578   unsigned OpIdxGroup = ~0u;
1579   unsigned NumOps;
1580   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1581        i += NumOps) {
1582     const MachineOperand &FlagMO = getOperand(i);
1583     assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1584     unsigned CurGroup = GroupIdx.size();
1585     GroupIdx.push_back(i);
1586     NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1587     // OpIdx belongs to this operand group.
1588     if (OpIdx > i && OpIdx < i + NumOps)
1589       OpIdxGroup = CurGroup;
1590     unsigned TiedGroup;
1591     if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1592       continue;
1593     // Operands in this group are tied to operands in TiedGroup which must be
1594     // earlier. Find the number of operands between the two groups.
1595     unsigned Delta = i - GroupIdx[TiedGroup];
1596 
1597     // OpIdx is a use tied to TiedGroup.
1598     if (OpIdxGroup == CurGroup)
1599       return OpIdx - Delta;
1600 
1601     // OpIdx is a def tied to this use group.
1602     if (OpIdxGroup == TiedGroup)
1603       return OpIdx + Delta;
1604   }
1605   llvm_unreachable("Invalid tied operand on inline asm");
1606 }
1607 
1608 /// clearKillInfo - Clears kill flags on all operands.
1609 ///
1610 void MachineInstr::clearKillInfo() {
1611   for (MachineOperand &MO : operands()) {
1612     if (MO.isReg() && MO.isUse())
1613       MO.setIsKill(false);
1614   }
1615 }
1616 
1617 void MachineInstr::substituteRegister(unsigned FromReg,
1618                                       unsigned ToReg,
1619                                       unsigned SubIdx,
1620                                       const TargetRegisterInfo &RegInfo) {
1621   if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1622     if (SubIdx)
1623       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1624     for (MachineOperand &MO : operands()) {
1625       if (!MO.isReg() || MO.getReg() != FromReg)
1626         continue;
1627       MO.substPhysReg(ToReg, RegInfo);
1628     }
1629   } else {
1630     for (MachineOperand &MO : operands()) {
1631       if (!MO.isReg() || MO.getReg() != FromReg)
1632         continue;
1633       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1634     }
1635   }
1636 }
1637 
1638 /// isSafeToMove - Return true if it is safe to move this instruction. If
1639 /// SawStore is set to true, it means that there is a store (or call) between
1640 /// the instruction's location and its intended destination.
1641 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1642   // Ignore stuff that we obviously can't move.
1643   //
1644   // Treat volatile loads as stores. This is not strictly necessary for
1645   // volatiles, but it is required for atomic loads. It is not allowed to move
1646   // a load across an atomic load with Ordering > Monotonic.
1647   if (mayStore() || isCall() ||
1648       (mayLoad() && hasOrderedMemoryRef())) {
1649     SawStore = true;
1650     return false;
1651   }
1652 
1653   if (isPosition() || isDebugValue() || isTerminator() ||
1654       hasUnmodeledSideEffects())
1655     return false;
1656 
1657   // See if this instruction does a load.  If so, we have to guarantee that the
1658   // loaded value doesn't change between the load and the its intended
1659   // destination. The check for isInvariantLoad gives the targe the chance to
1660   // classify the load as always returning a constant, e.g. a constant pool
1661   // load.
1662   if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1663     // Otherwise, this is a real load.  If there is a store between the load and
1664     // end of block, we can't move it.
1665     return !SawStore;
1666 
1667   return true;
1668 }
1669 
1670 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
1671                             bool UseTBAA) {
1672   const MachineFunction *MF = getMF();
1673   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1674   const MachineFrameInfo &MFI = MF->getFrameInfo();
1675 
1676   // If neither instruction stores to memory, they can't alias in any
1677   // meaningful way, even if they read from the same address.
1678   if (!mayStore() && !Other.mayStore())
1679     return false;
1680 
1681   // Let the target decide if memory accesses cannot possibly overlap.
1682   if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
1683     return false;
1684 
1685   // FIXME: Need to handle multiple memory operands to support all targets.
1686   if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1687     return true;
1688 
1689   MachineMemOperand *MMOa = *memoperands_begin();
1690   MachineMemOperand *MMOb = *Other.memoperands_begin();
1691 
1692   // The following interface to AA is fashioned after DAGCombiner::isAlias
1693   // and operates with MachineMemOperand offset with some important
1694   // assumptions:
1695   //   - LLVM fundamentally assumes flat address spaces.
1696   //   - MachineOperand offset can *only* result from legalization and
1697   //     cannot affect queries other than the trivial case of overlap
1698   //     checking.
1699   //   - These offsets never wrap and never step outside
1700   //     of allocated objects.
1701   //   - There should never be any negative offsets here.
1702   //
1703   // FIXME: Modify API to hide this math from "user"
1704   // Even before we go to AA we can reason locally about some
1705   // memory objects. It can save compile time, and possibly catch some
1706   // corner cases not currently covered.
1707 
1708   int64_t OffsetA = MMOa->getOffset();
1709   int64_t OffsetB = MMOb->getOffset();
1710 
1711   int64_t MinOffset = std::min(OffsetA, OffsetB);
1712   int64_t WidthA = MMOa->getSize();
1713   int64_t WidthB = MMOb->getSize();
1714   const Value *ValA = MMOa->getValue();
1715   const Value *ValB = MMOb->getValue();
1716   bool SameVal = (ValA && ValB && (ValA == ValB));
1717   if (!SameVal) {
1718     const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
1719     const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
1720     if (PSVa && ValB && !PSVa->mayAlias(&MFI))
1721       return false;
1722     if (PSVb && ValA && !PSVb->mayAlias(&MFI))
1723       return false;
1724     if (PSVa && PSVb && (PSVa == PSVb))
1725       SameVal = true;
1726   }
1727 
1728   if (SameVal) {
1729     int64_t MaxOffset = std::max(OffsetA, OffsetB);
1730     int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
1731     return (MinOffset + LowWidth > MaxOffset);
1732   }
1733 
1734   if (!AA)
1735     return true;
1736 
1737   if (!ValA || !ValB)
1738     return true;
1739 
1740   assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
1741   assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
1742 
1743   int64_t Overlapa = WidthA + OffsetA - MinOffset;
1744   int64_t Overlapb = WidthB + OffsetB - MinOffset;
1745 
1746   AliasResult AAResult = AA->alias(
1747       MemoryLocation(ValA, Overlapa,
1748                      UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1749       MemoryLocation(ValB, Overlapb,
1750                      UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1751 
1752   return (AAResult != NoAlias);
1753 }
1754 
1755 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1756 /// or volatile memory reference, or if the information describing the memory
1757 /// reference is not available. Return false if it is known to have no ordered
1758 /// memory references.
1759 bool MachineInstr::hasOrderedMemoryRef() const {
1760   // An instruction known never to access memory won't have a volatile access.
1761   if (!mayStore() &&
1762       !mayLoad() &&
1763       !isCall() &&
1764       !hasUnmodeledSideEffects())
1765     return false;
1766 
1767   // Otherwise, if the instruction has no memory reference information,
1768   // conservatively assume it wasn't preserved.
1769   if (memoperands_empty())
1770     return true;
1771 
1772   // Check if any of our memory operands are ordered.
1773   return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1774     return !MMO->isUnordered();
1775   });
1776 }
1777 
1778 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1779 /// trap and is loading from a location whose value is invariant across a run of
1780 /// this function.
1781 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
1782   // If the instruction doesn't load at all, it isn't an invariant load.
1783   if (!mayLoad())
1784     return false;
1785 
1786   // If the instruction has lost its memoperands, conservatively assume that
1787   // it may not be an invariant load.
1788   if (memoperands_empty())
1789     return false;
1790 
1791   const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1792 
1793   for (MachineMemOperand *MMO : memoperands()) {
1794     if (MMO->isVolatile()) return false;
1795     if (MMO->isStore()) return false;
1796     if (MMO->isInvariant() && MMO->isDereferenceable())
1797       continue;
1798 
1799     // A load from a constant PseudoSourceValue is invariant.
1800     if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1801       if (PSV->isConstant(&MFI))
1802         continue;
1803 
1804     if (const Value *V = MMO->getValue()) {
1805       // If we have an AliasAnalysis, ask it whether the memory is constant.
1806       if (AA &&
1807           AA->pointsToConstantMemory(
1808               MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1809         continue;
1810     }
1811 
1812     // Otherwise assume conservatively.
1813     return false;
1814   }
1815 
1816   // Everything checks out.
1817   return true;
1818 }
1819 
1820 /// isConstantValuePHI - If the specified instruction is a PHI that always
1821 /// merges together the same virtual register, return the register, otherwise
1822 /// return 0.
1823 unsigned MachineInstr::isConstantValuePHI() const {
1824   if (!isPHI())
1825     return 0;
1826   assert(getNumOperands() >= 3 &&
1827          "It's illegal to have a PHI without source operands");
1828 
1829   unsigned Reg = getOperand(1).getReg();
1830   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1831     if (getOperand(i).getReg() != Reg)
1832       return 0;
1833   return Reg;
1834 }
1835 
1836 bool MachineInstr::hasUnmodeledSideEffects() const {
1837   if (hasProperty(MCID::UnmodeledSideEffects))
1838     return true;
1839   if (isInlineAsm()) {
1840     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1841     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1842       return true;
1843   }
1844 
1845   return false;
1846 }
1847 
1848 bool MachineInstr::isLoadFoldBarrier() const {
1849   return mayStore() || isCall() || hasUnmodeledSideEffects();
1850 }
1851 
1852 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1853 ///
1854 bool MachineInstr::allDefsAreDead() const {
1855   for (const MachineOperand &MO : operands()) {
1856     if (!MO.isReg() || MO.isUse())
1857       continue;
1858     if (!MO.isDead())
1859       return false;
1860   }
1861   return true;
1862 }
1863 
1864 /// copyImplicitOps - Copy implicit register operands from specified
1865 /// instruction to this instruction.
1866 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1867                                    const MachineInstr &MI) {
1868   for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1869        i != e; ++i) {
1870     const MachineOperand &MO = MI.getOperand(i);
1871     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1872       addOperand(MF, MO);
1873   }
1874 }
1875 
1876 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1877 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1878   dbgs() << "  ";
1879   print(dbgs());
1880 }
1881 #endif
1882 
1883 void MachineInstr::print(raw_ostream &OS, bool SkipOpers, bool SkipDebugLoc,
1884                          const TargetInstrInfo *TII) const {
1885   const Module *M = nullptr;
1886   if (const MachineBasicBlock *MBB = getParent())
1887     if (const MachineFunction *MF = MBB->getParent())
1888       M = MF->getFunction()->getParent();
1889 
1890   ModuleSlotTracker MST(M);
1891   print(OS, MST, SkipOpers, SkipDebugLoc, TII);
1892 }
1893 
1894 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1895                          bool SkipOpers, bool SkipDebugLoc,
1896                          const TargetInstrInfo *TII) const {
1897   // We can be a bit tidier if we know the MachineFunction.
1898   const MachineFunction *MF = nullptr;
1899   const TargetRegisterInfo *TRI = nullptr;
1900   const MachineRegisterInfo *MRI = nullptr;
1901   const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1902 
1903   if (const MachineBasicBlock *MBB = getParent()) {
1904     MF = MBB->getParent();
1905     if (MF) {
1906       MRI = &MF->getRegInfo();
1907       TRI = MF->getSubtarget().getRegisterInfo();
1908       if (!TII)
1909         TII = MF->getSubtarget().getInstrInfo();
1910       IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
1911     }
1912   }
1913 
1914   // Save a list of virtual registers.
1915   SmallVector<unsigned, 8> VirtRegs;
1916 
1917   // Print explicitly defined operands on the left of an assignment syntax.
1918   unsigned StartOp = 0, e = getNumOperands();
1919   for (; StartOp < e && getOperand(StartOp).isReg() &&
1920          getOperand(StartOp).isDef() &&
1921          !getOperand(StartOp).isImplicit();
1922        ++StartOp) {
1923     if (StartOp != 0) OS << ", ";
1924     getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
1925     unsigned Reg = getOperand(StartOp).getReg();
1926     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1927       VirtRegs.push_back(Reg);
1928       LLT Ty = MRI ? MRI->getType(Reg) : LLT{};
1929       if (Ty.isValid())
1930         OS << '(' << Ty << ')';
1931     }
1932   }
1933 
1934   if (StartOp != 0)
1935     OS << " = ";
1936 
1937   // Print the opcode name.
1938   if (TII)
1939     OS << TII->getName(getOpcode());
1940   else
1941     OS << "UNKNOWN";
1942 
1943   if (SkipOpers)
1944     return;
1945 
1946   // Print the rest of the operands.
1947   bool FirstOp = true;
1948   unsigned AsmDescOp = ~0u;
1949   unsigned AsmOpCount = 0;
1950 
1951   if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1952     // Print asm string.
1953     OS << " ";
1954     getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1955 
1956     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1957     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1958     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1959       OS << " [sideeffect]";
1960     if (ExtraInfo & InlineAsm::Extra_MayLoad)
1961       OS << " [mayload]";
1962     if (ExtraInfo & InlineAsm::Extra_MayStore)
1963       OS << " [maystore]";
1964     if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1965       OS << " [isconvergent]";
1966     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1967       OS << " [alignstack]";
1968     if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1969       OS << " [attdialect]";
1970     if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1971       OS << " [inteldialect]";
1972 
1973     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1974     FirstOp = false;
1975   }
1976 
1977   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1978     const MachineOperand &MO = getOperand(i);
1979 
1980     if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1981       VirtRegs.push_back(MO.getReg());
1982 
1983     if (FirstOp) FirstOp = false; else OS << ",";
1984     OS << " ";
1985     if (i < getDesc().NumOperands) {
1986       const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1987       if (MCOI.isPredicate())
1988         OS << "pred:";
1989       if (MCOI.isOptionalDef())
1990         OS << "opt:";
1991     }
1992     if (isDebugValue() && MO.isMetadata()) {
1993       // Pretty print DBG_VALUE instructions.
1994       auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1995       if (DIV && !DIV->getName().empty())
1996         OS << "!\"" << DIV->getName() << '\"';
1997       else
1998         MO.print(OS, MST, TRI);
1999     } else if (TRI && (isInsertSubreg() || isRegSequence() ||
2000                        (isSubregToReg() && i == 3)) && MO.isImm()) {
2001       OS << TRI->getSubRegIndexName(MO.getImm());
2002     } else if (i == AsmDescOp && MO.isImm()) {
2003       // Pretty print the inline asm operand descriptor.
2004       OS << '$' << AsmOpCount++;
2005       unsigned Flag = MO.getImm();
2006       switch (InlineAsm::getKind(Flag)) {
2007       case InlineAsm::Kind_RegUse:             OS << ":[reguse"; break;
2008       case InlineAsm::Kind_RegDef:             OS << ":[regdef"; break;
2009       case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
2010       case InlineAsm::Kind_Clobber:            OS << ":[clobber"; break;
2011       case InlineAsm::Kind_Imm:                OS << ":[imm"; break;
2012       case InlineAsm::Kind_Mem:                OS << ":[mem"; break;
2013       default: OS << ":[??" << InlineAsm::getKind(Flag); break;
2014       }
2015 
2016       unsigned RCID = 0;
2017       if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
2018           InlineAsm::hasRegClassConstraint(Flag, RCID)) {
2019         if (TRI) {
2020           OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
2021         } else
2022           OS << ":RC" << RCID;
2023       }
2024 
2025       if (InlineAsm::isMemKind(Flag)) {
2026         unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
2027         switch (MCID) {
2028         case InlineAsm::Constraint_es: OS << ":es"; break;
2029         case InlineAsm::Constraint_i:  OS << ":i"; break;
2030         case InlineAsm::Constraint_m:  OS << ":m"; break;
2031         case InlineAsm::Constraint_o:  OS << ":o"; break;
2032         case InlineAsm::Constraint_v:  OS << ":v"; break;
2033         case InlineAsm::Constraint_Q:  OS << ":Q"; break;
2034         case InlineAsm::Constraint_R:  OS << ":R"; break;
2035         case InlineAsm::Constraint_S:  OS << ":S"; break;
2036         case InlineAsm::Constraint_T:  OS << ":T"; break;
2037         case InlineAsm::Constraint_Um: OS << ":Um"; break;
2038         case InlineAsm::Constraint_Un: OS << ":Un"; break;
2039         case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
2040         case InlineAsm::Constraint_Us: OS << ":Us"; break;
2041         case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
2042         case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
2043         case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
2044         case InlineAsm::Constraint_X:  OS << ":X"; break;
2045         case InlineAsm::Constraint_Z:  OS << ":Z"; break;
2046         case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
2047         case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
2048         default: OS << ":?"; break;
2049         }
2050       }
2051 
2052       unsigned TiedTo = 0;
2053       if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
2054         OS << " tiedto:$" << TiedTo;
2055 
2056       OS << ']';
2057 
2058       // Compute the index of the next operand descriptor.
2059       AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
2060     } else
2061       MO.print(OS, MST, TRI);
2062   }
2063 
2064   bool HaveSemi = false;
2065   const unsigned PrintableFlags = FrameSetup | FrameDestroy;
2066   if (Flags & PrintableFlags) {
2067     if (!HaveSemi) {
2068       OS << ";";
2069       HaveSemi = true;
2070     }
2071     OS << " flags: ";
2072 
2073     if (Flags & FrameSetup)
2074       OS << "FrameSetup";
2075 
2076     if (Flags & FrameDestroy)
2077       OS << "FrameDestroy";
2078   }
2079 
2080   if (!memoperands_empty()) {
2081     if (!HaveSemi) {
2082       OS << ";";
2083       HaveSemi = true;
2084     }
2085 
2086     OS << " mem:";
2087     for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
2088          i != e; ++i) {
2089       (*i)->print(OS, MST);
2090       if (std::next(i) != e)
2091         OS << " ";
2092     }
2093   }
2094 
2095   // Print the regclass of any virtual registers encountered.
2096   if (MRI && !VirtRegs.empty()) {
2097     if (!HaveSemi) {
2098       OS << ";";
2099       HaveSemi = true;
2100     }
2101     for (unsigned i = 0; i != VirtRegs.size(); ++i) {
2102       const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
2103       if (!RC)
2104         continue;
2105       // Generic virtual registers do not have register classes.
2106       if (RC.is<const RegisterBank *>())
2107         OS << " " << RC.get<const RegisterBank *>()->getName();
2108       else
2109         OS << " "
2110            << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
2111       OS << ':' << PrintReg(VirtRegs[i]);
2112       for (unsigned j = i+1; j != VirtRegs.size();) {
2113         if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
2114           ++j;
2115           continue;
2116         }
2117         if (VirtRegs[i] != VirtRegs[j])
2118           OS << "," << PrintReg(VirtRegs[j]);
2119         VirtRegs.erase(VirtRegs.begin()+j);
2120       }
2121     }
2122   }
2123 
2124   // Print debug location information.
2125   if (isDebugValue() && getOperand(e - 2).isMetadata()) {
2126     if (!HaveSemi)
2127       OS << ";";
2128     auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
2129     OS << " line no:" <<  DV->getLine();
2130     if (auto *InlinedAt = debugLoc->getInlinedAt()) {
2131       DebugLoc InlinedAtDL(InlinedAt);
2132       if (InlinedAtDL && MF) {
2133         OS << " inlined @[ ";
2134         InlinedAtDL.print(OS);
2135         OS << " ]";
2136       }
2137     }
2138     if (isIndirectDebugValue())
2139       OS << " indirect";
2140   } else if (SkipDebugLoc) {
2141     return;
2142   } else if (debugLoc && MF) {
2143     if (!HaveSemi)
2144       OS << ";";
2145     OS << " dbg:";
2146     debugLoc.print(OS);
2147   }
2148 
2149   OS << '\n';
2150 }
2151 
2152 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
2153                                      const TargetRegisterInfo *RegInfo,
2154                                      bool AddIfNotFound) {
2155   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
2156   bool hasAliases = isPhysReg &&
2157     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
2158   bool Found = false;
2159   SmallVector<unsigned,4> DeadOps;
2160   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2161     MachineOperand &MO = getOperand(i);
2162     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
2163       continue;
2164 
2165     // DEBUG_VALUE nodes do not contribute to code generation and should
2166     // always be ignored. Failure to do so may result in trying to modify
2167     // KILL flags on DEBUG_VALUE nodes.
2168     if (MO.isDebug())
2169       continue;
2170 
2171     unsigned Reg = MO.getReg();
2172     if (!Reg)
2173       continue;
2174 
2175     if (Reg == IncomingReg) {
2176       if (!Found) {
2177         if (MO.isKill())
2178           // The register is already marked kill.
2179           return true;
2180         if (isPhysReg && isRegTiedToDefOperand(i))
2181           // Two-address uses of physregs must not be marked kill.
2182           return true;
2183         MO.setIsKill();
2184         Found = true;
2185       }
2186     } else if (hasAliases && MO.isKill() &&
2187                TargetRegisterInfo::isPhysicalRegister(Reg)) {
2188       // A super-register kill already exists.
2189       if (RegInfo->isSuperRegister(IncomingReg, Reg))
2190         return true;
2191       if (RegInfo->isSubRegister(IncomingReg, Reg))
2192         DeadOps.push_back(i);
2193     }
2194   }
2195 
2196   // Trim unneeded kill operands.
2197   while (!DeadOps.empty()) {
2198     unsigned OpIdx = DeadOps.back();
2199     if (getOperand(OpIdx).isImplicit())
2200       RemoveOperand(OpIdx);
2201     else
2202       getOperand(OpIdx).setIsKill(false);
2203     DeadOps.pop_back();
2204   }
2205 
2206   // If not found, this means an alias of one of the operands is killed. Add a
2207   // new implicit operand if required.
2208   if (!Found && AddIfNotFound) {
2209     addOperand(MachineOperand::CreateReg(IncomingReg,
2210                                          false /*IsDef*/,
2211                                          true  /*IsImp*/,
2212                                          true  /*IsKill*/));
2213     return true;
2214   }
2215   return Found;
2216 }
2217 
2218 void MachineInstr::clearRegisterKills(unsigned Reg,
2219                                       const TargetRegisterInfo *RegInfo) {
2220   if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2221     RegInfo = nullptr;
2222   for (MachineOperand &MO : operands()) {
2223     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2224       continue;
2225     unsigned OpReg = MO.getReg();
2226     if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2227       MO.setIsKill(false);
2228   }
2229 }
2230 
2231 bool MachineInstr::addRegisterDead(unsigned Reg,
2232                                    const TargetRegisterInfo *RegInfo,
2233                                    bool AddIfNotFound) {
2234   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2235   bool hasAliases = isPhysReg &&
2236     MCRegAliasIterator(Reg, RegInfo, false).isValid();
2237   bool Found = false;
2238   SmallVector<unsigned,4> DeadOps;
2239   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2240     MachineOperand &MO = getOperand(i);
2241     if (!MO.isReg() || !MO.isDef())
2242       continue;
2243     unsigned MOReg = MO.getReg();
2244     if (!MOReg)
2245       continue;
2246 
2247     if (MOReg == Reg) {
2248       MO.setIsDead();
2249       Found = true;
2250     } else if (hasAliases && MO.isDead() &&
2251                TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2252       // There exists a super-register that's marked dead.
2253       if (RegInfo->isSuperRegister(Reg, MOReg))
2254         return true;
2255       if (RegInfo->isSubRegister(Reg, MOReg))
2256         DeadOps.push_back(i);
2257     }
2258   }
2259 
2260   // Trim unneeded dead operands.
2261   while (!DeadOps.empty()) {
2262     unsigned OpIdx = DeadOps.back();
2263     if (getOperand(OpIdx).isImplicit())
2264       RemoveOperand(OpIdx);
2265     else
2266       getOperand(OpIdx).setIsDead(false);
2267     DeadOps.pop_back();
2268   }
2269 
2270   // If not found, this means an alias of one of the operands is dead. Add a
2271   // new implicit operand if required.
2272   if (Found || !AddIfNotFound)
2273     return Found;
2274 
2275   addOperand(MachineOperand::CreateReg(Reg,
2276                                        true  /*IsDef*/,
2277                                        true  /*IsImp*/,
2278                                        false /*IsKill*/,
2279                                        true  /*IsDead*/));
2280   return true;
2281 }
2282 
2283 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2284   for (MachineOperand &MO : operands()) {
2285     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2286       continue;
2287     MO.setIsDead(false);
2288   }
2289 }
2290 
2291 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2292   for (MachineOperand &MO : operands()) {
2293     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2294       continue;
2295     MO.setIsUndef(IsUndef);
2296   }
2297 }
2298 
2299 void MachineInstr::addRegisterDefined(unsigned Reg,
2300                                       const TargetRegisterInfo *RegInfo) {
2301   if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2302     MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2303     if (MO)
2304       return;
2305   } else {
2306     for (const MachineOperand &MO : operands()) {
2307       if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2308           MO.getSubReg() == 0)
2309         return;
2310     }
2311   }
2312   addOperand(MachineOperand::CreateReg(Reg,
2313                                        true  /*IsDef*/,
2314                                        true  /*IsImp*/));
2315 }
2316 
2317 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2318                                          const TargetRegisterInfo &TRI) {
2319   bool HasRegMask = false;
2320   for (MachineOperand &MO : operands()) {
2321     if (MO.isRegMask()) {
2322       HasRegMask = true;
2323       continue;
2324     }
2325     if (!MO.isReg() || !MO.isDef()) continue;
2326     unsigned Reg = MO.getReg();
2327     if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2328     // If there are no uses, including partial uses, the def is dead.
2329     if (llvm::none_of(UsedRegs,
2330                       [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2331       MO.setIsDead();
2332   }
2333 
2334   // This is a call with a register mask operand.
2335   // Mask clobbers are always dead, so add defs for the non-dead defines.
2336   if (HasRegMask)
2337     for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2338          I != E; ++I)
2339       addRegisterDefined(*I, &TRI);
2340 }
2341 
2342 unsigned
2343 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2344   // Build up a buffer of hash code components.
2345   SmallVector<size_t, 8> HashComponents;
2346   HashComponents.reserve(MI->getNumOperands() + 1);
2347   HashComponents.push_back(MI->getOpcode());
2348   for (const MachineOperand &MO : MI->operands()) {
2349     if (MO.isReg() && MO.isDef() &&
2350         TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2351       continue;  // Skip virtual register defs.
2352 
2353     HashComponents.push_back(hash_value(MO));
2354   }
2355   return hash_combine_range(HashComponents.begin(), HashComponents.end());
2356 }
2357 
2358 void MachineInstr::emitError(StringRef Msg) const {
2359   // Find the source location cookie.
2360   unsigned LocCookie = 0;
2361   const MDNode *LocMD = nullptr;
2362   for (unsigned i = getNumOperands(); i != 0; --i) {
2363     if (getOperand(i-1).isMetadata() &&
2364         (LocMD = getOperand(i-1).getMetadata()) &&
2365         LocMD->getNumOperands() != 0) {
2366       if (const ConstantInt *CI =
2367               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2368         LocCookie = CI->getZExtValue();
2369         break;
2370       }
2371     }
2372   }
2373 
2374   if (const MachineBasicBlock *MBB = getParent())
2375     if (const MachineFunction *MF = MBB->getParent())
2376       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2377   report_fatal_error(Msg);
2378 }
2379 
2380 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2381                                   const MCInstrDesc &MCID, bool IsIndirect,
2382                                   unsigned Reg, const MDNode *Variable,
2383                                   const MDNode *Expr) {
2384   assert(isa<DILocalVariable>(Variable) && "not a variable");
2385   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2386   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2387          "Expected inlined-at fields to agree");
2388   if (IsIndirect)
2389     return BuildMI(MF, DL, MCID)
2390         .addReg(Reg, RegState::Debug)
2391         .addImm(0U)
2392         .addMetadata(Variable)
2393         .addMetadata(Expr);
2394   else
2395     return BuildMI(MF, DL, MCID)
2396         .addReg(Reg, RegState::Debug)
2397         .addReg(0U, RegState::Debug)
2398         .addMetadata(Variable)
2399         .addMetadata(Expr);
2400 }
2401 
2402 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2403                                   MachineBasicBlock::iterator I,
2404                                   const DebugLoc &DL, const MCInstrDesc &MCID,
2405                                   bool IsIndirect, unsigned Reg,
2406                                   const MDNode *Variable, const MDNode *Expr) {
2407   assert(isa<DILocalVariable>(Variable) && "not a variable");
2408   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2409   MachineFunction &MF = *BB.getParent();
2410   MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
2411   BB.insert(I, MI);
2412   return MachineInstrBuilder(MF, MI);
2413 }
2414 
2415 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
2416 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
2417 static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
2418   assert(MI.getOperand(0).isReg() && "can't spill non-register");
2419   assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
2420          "Expected inlined-at fields to agree");
2421 
2422   const DIExpression *Expr = MI.getDebugExpression();
2423   if (MI.isIndirectDebugValue()) {
2424     assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
2425     Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
2426   }
2427   return Expr;
2428 }
2429 
2430 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2431                                           MachineBasicBlock::iterator I,
2432                                           const MachineInstr &Orig,
2433                                           int FrameIndex) {
2434   const DIExpression *Expr = computeExprForSpill(Orig);
2435   return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
2436       .addFrameIndex(FrameIndex)
2437       .addImm(0U)
2438       .addMetadata(Orig.getDebugVariable())
2439       .addMetadata(Expr);
2440 }
2441 
2442 void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
2443   const DIExpression *Expr = computeExprForSpill(Orig);
2444   Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
2445   Orig.getOperand(1).ChangeToImmediate(0U);
2446   Orig.getOperand(3).setMetadata(Expr);
2447 }
2448