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