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