xref: /llvm-project/llvm/lib/CodeGen/MachineInstr.cpp (revision a41b149f481e2bcba24e81f208a1938247f040e0)
1 //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Methods common to all machine instructions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/MachineInstr.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/Hashing.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallBitVector.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/MemoryLocation.h"
21 #include "llvm/CodeGen/LowLevelType.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineInstrBundle.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/PseudoSourceValue.h"
32 #include "llvm/CodeGen/Register.h"
33 #include "llvm/CodeGen/StackMaps.h"
34 #include "llvm/CodeGen/TargetInstrInfo.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DebugInfoMetadata.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/ModuleSlotTracker.h"
46 #include "llvm/IR/Operator.h"
47 #include "llvm/MC/MCInstrDesc.h"
48 #include "llvm/MC/MCRegisterInfo.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/FormattedStream.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include <algorithm>
57 #include <cassert>
58 #include <cstdint>
59 #include <cstring>
60 #include <utility>
61 
62 using namespace llvm;
63 
64 static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
65   if (const MachineBasicBlock *MBB = MI.getParent())
66     if (const MachineFunction *MF = MBB->getParent())
67       return MF;
68   return nullptr;
69 }
70 
71 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
72 // it.
73 static void tryToGetTargetInfo(const MachineInstr &MI,
74                                const TargetRegisterInfo *&TRI,
75                                const MachineRegisterInfo *&MRI,
76                                const TargetIntrinsicInfo *&IntrinsicInfo,
77                                const TargetInstrInfo *&TII) {
78 
79   if (const MachineFunction *MF = getMFIfAvailable(MI)) {
80     TRI = MF->getSubtarget().getRegisterInfo();
81     MRI = &MF->getRegInfo();
82     IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
83     TII = MF->getSubtarget().getInstrInfo();
84   }
85 }
86 
87 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
88   for (MCPhysReg ImpDef : MCID->implicit_defs())
89     addOperand(MF, MachineOperand::CreateReg(ImpDef, true, true));
90   for (MCPhysReg ImpUse : MCID->implicit_uses())
91     addOperand(MF, MachineOperand::CreateReg(ImpUse, false, true));
92 }
93 
94 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
95 /// implicit operands. It reserves space for the number of operands specified by
96 /// the MCInstrDesc.
97 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &TID,
98                            DebugLoc DL, bool NoImp)
99     : MCID(&TID), NumOperands(0), Flags(0), AsmPrinterFlags(0),
100       DbgLoc(std::move(DL)), DebugInstrNum(0) {
101   assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor");
102 
103   // Reserve space for the expected number of operands.
104   if (unsigned NumOps = MCID->getNumOperands() + MCID->implicit_defs().size() +
105                         MCID->implicit_uses().size()) {
106     CapOperands = OperandCapacity::get(NumOps);
107     Operands = MF.allocateOperandArray(CapOperands);
108   }
109 
110   if (!NoImp)
111     addImplicitDefUseOperands(MF);
112 }
113 
114 /// MachineInstr ctor - Copies MachineInstr arg exactly.
115 /// Does not copy the number from debug instruction numbering, to preserve
116 /// uniqueness.
117 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
118     : MCID(&MI.getDesc()), NumOperands(0), Flags(0), AsmPrinterFlags(0),
119       Info(MI.Info), DbgLoc(MI.getDebugLoc()), DebugInstrNum(0) {
120   assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor");
121 
122   CapOperands = OperandCapacity::get(MI.getNumOperands());
123   Operands = MF.allocateOperandArray(CapOperands);
124 
125   // Copy operands.
126   for (const MachineOperand &MO : MI.operands())
127     addOperand(MF, MO);
128 
129   // Replicate ties between the operands, which addOperand was not
130   // able to do reliably.
131   for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
132     MachineOperand &NewMO = getOperand(i);
133     const MachineOperand &OrigMO = MI.getOperand(i);
134     NewMO.TiedTo = OrigMO.TiedTo;
135   }
136 
137   // Copy all the sensible flags.
138   setFlags(MI.Flags);
139 }
140 
141 void MachineInstr::setDesc(const MCInstrDesc &TID) {
142   if (getParent())
143     getMF()->handleChangeDesc(*this, TID);
144   MCID = &TID;
145 }
146 
147 void MachineInstr::moveBefore(MachineInstr *MovePos) {
148   MovePos->getParent()->splice(MovePos, getParent(), getIterator());
149 }
150 
151 /// getRegInfo - If this instruction is embedded into a MachineFunction,
152 /// return the MachineRegisterInfo object for the current function, otherwise
153 /// return null.
154 MachineRegisterInfo *MachineInstr::getRegInfo() {
155   if (MachineBasicBlock *MBB = getParent())
156     return &MBB->getParent()->getRegInfo();
157   return nullptr;
158 }
159 
160 const MachineRegisterInfo *MachineInstr::getRegInfo() const {
161   if (const MachineBasicBlock *MBB = getParent())
162     return &MBB->getParent()->getRegInfo();
163   return nullptr;
164 }
165 
166 void MachineInstr::removeRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
167   for (MachineOperand &MO : operands())
168     if (MO.isReg())
169       MRI.removeRegOperandFromUseList(&MO);
170 }
171 
172 void MachineInstr::addRegOperandsToUseLists(MachineRegisterInfo &MRI) {
173   for (MachineOperand &MO : operands())
174     if (MO.isReg())
175       MRI.addRegOperandToUseList(&MO);
176 }
177 
178 void MachineInstr::addOperand(const MachineOperand &Op) {
179   MachineBasicBlock *MBB = getParent();
180   assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
181   MachineFunction *MF = MBB->getParent();
182   assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
183   addOperand(*MF, Op);
184 }
185 
186 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
187 /// ranges. If MRI is non-null also update use-def chains.
188 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
189                          unsigned NumOps, MachineRegisterInfo *MRI) {
190   if (MRI)
191     return MRI->moveOperands(Dst, Src, NumOps);
192   // MachineOperand is a trivially copyable type so we can just use memmove.
193   assert(Dst && Src && "Unknown operands");
194   std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
195 }
196 
197 /// addOperand - Add the specified operand to the instruction.  If it is an
198 /// implicit operand, it is added to the end of the operand list.  If it is
199 /// an explicit operand it is added at the end of the explicit operand list
200 /// (before the first implicit operand).
201 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
202   assert(isUInt<LLVM_MI_NUMOPERANDS_BITS>(NumOperands + 1) &&
203          "Cannot add more operands.");
204   assert(MCID && "Cannot add operands before providing an instr descriptor");
205 
206   // Check if we're adding one of our existing operands.
207   if (&Op >= Operands && &Op < Operands + NumOperands) {
208     // This is unusual: MI->addOperand(MI->getOperand(i)).
209     // If adding Op requires reallocating or moving existing operands around,
210     // the Op reference could go stale. Support it by copying Op.
211     MachineOperand CopyOp(Op);
212     return addOperand(MF, CopyOp);
213   }
214 
215   // Find the insert location for the new operand.  Implicit registers go at
216   // the end, everything else goes before the implicit regs.
217   //
218   // FIXME: Allow mixed explicit and implicit operands on inline asm.
219   // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
220   // implicit-defs, but they must not be moved around.  See the FIXME in
221   // InstrEmitter.cpp.
222   unsigned OpNo = getNumOperands();
223   bool isImpReg = Op.isReg() && Op.isImplicit();
224   if (!isImpReg && !isInlineAsm()) {
225     while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
226       --OpNo;
227       assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
228     }
229   }
230 
231   // OpNo now points as the desired insertion point.  Unless this is a variadic
232   // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
233   // RegMask operands go between the explicit and implicit operands.
234   assert((MCID->isVariadic() || OpNo < MCID->getNumOperands() ||
235           Op.isValidExcessOperand()) &&
236          "Trying to add an operand to a machine instr that is already done!");
237 
238   MachineRegisterInfo *MRI = getRegInfo();
239 
240   // Determine if the Operands array needs to be reallocated.
241   // Save the old capacity and operand array.
242   OperandCapacity OldCap = CapOperands;
243   MachineOperand *OldOperands = Operands;
244   if (!OldOperands || OldCap.getSize() == getNumOperands()) {
245     CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
246     Operands = MF.allocateOperandArray(CapOperands);
247     // Move the operands before the insertion point.
248     if (OpNo)
249       moveOperands(Operands, OldOperands, OpNo, MRI);
250   }
251 
252   // Move the operands following the insertion point.
253   if (OpNo != NumOperands)
254     moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
255                  MRI);
256   ++NumOperands;
257 
258   // Deallocate the old operand array.
259   if (OldOperands != Operands && OldOperands)
260     MF.deallocateOperandArray(OldCap, OldOperands);
261 
262   // Copy Op into place. It still needs to be inserted into the MRI use lists.
263   MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
264   NewMO->ParentMI = this;
265 
266   // When adding a register operand, tell MRI about it.
267   if (NewMO->isReg()) {
268     // Ensure isOnRegUseList() returns false, regardless of Op's status.
269     NewMO->Contents.Reg.Prev = nullptr;
270     // Ignore existing ties. This is not a property that can be copied.
271     NewMO->TiedTo = 0;
272     // Add the new operand to MRI, but only for instructions in an MBB.
273     if (MRI)
274       MRI->addRegOperandToUseList(NewMO);
275     // The MCID operand information isn't accurate until we start adding
276     // explicit operands. The implicit operands are added first, then the
277     // explicits are inserted before them.
278     if (!isImpReg) {
279       // Tie uses to defs as indicated in MCInstrDesc.
280       if (NewMO->isUse()) {
281         int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
282         if (DefIdx != -1)
283           tieOperands(DefIdx, OpNo);
284       }
285       // If the register operand is flagged as early, mark the operand as such.
286       if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
287         NewMO->setIsEarlyClobber(true);
288     }
289     // Ensure debug instructions set debug flag on register uses.
290     if (NewMO->isUse() && isDebugInstr())
291       NewMO->setIsDebug();
292   }
293 }
294 
295 void MachineInstr::removeOperand(unsigned OpNo) {
296   assert(OpNo < getNumOperands() && "Invalid operand number");
297   untieRegOperand(OpNo);
298 
299 #ifndef NDEBUG
300   // Moving tied operands would break the ties.
301   for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
302     if (Operands[i].isReg())
303       assert(!Operands[i].isTied() && "Cannot move tied operands");
304 #endif
305 
306   MachineRegisterInfo *MRI = getRegInfo();
307   if (MRI && Operands[OpNo].isReg())
308     MRI->removeRegOperandFromUseList(Operands + OpNo);
309 
310   // Don't call the MachineOperand destructor. A lot of this code depends on
311   // MachineOperand having a trivial destructor anyway, and adding a call here
312   // wouldn't make it 'destructor-correct'.
313 
314   if (unsigned N = NumOperands - 1 - OpNo)
315     moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
316   --NumOperands;
317 }
318 
319 void MachineInstr::setExtraInfo(MachineFunction &MF,
320                                 ArrayRef<MachineMemOperand *> MMOs,
321                                 MCSymbol *PreInstrSymbol,
322                                 MCSymbol *PostInstrSymbol,
323                                 MDNode *HeapAllocMarker, MDNode *PCSections,
324                                 uint32_t CFIType) {
325   bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
326   bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
327   bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
328   bool HasPCSections = PCSections != nullptr;
329   bool HasCFIType = CFIType != 0;
330   int NumPointers = MMOs.size() + HasPreInstrSymbol + HasPostInstrSymbol +
331                     HasHeapAllocMarker + HasPCSections + HasCFIType;
332 
333   // Drop all extra info if there is none.
334   if (NumPointers <= 0) {
335     Info.clear();
336     return;
337   }
338 
339   // If more than one pointer, then store out of line. Store heap alloc markers
340   // out of line because PointerSumType cannot hold more than 4 tag types with
341   // 32-bit pointers.
342   // FIXME: Maybe we should make the symbols in the extra info mutable?
343   else if (NumPointers > 1 || HasHeapAllocMarker || HasPCSections ||
344            HasCFIType) {
345     Info.set<EIIK_OutOfLine>(
346         MF.createMIExtraInfo(MMOs, PreInstrSymbol, PostInstrSymbol,
347                              HeapAllocMarker, PCSections, CFIType));
348     return;
349   }
350 
351   // Otherwise store the single pointer inline.
352   if (HasPreInstrSymbol)
353     Info.set<EIIK_PreInstrSymbol>(PreInstrSymbol);
354   else if (HasPostInstrSymbol)
355     Info.set<EIIK_PostInstrSymbol>(PostInstrSymbol);
356   else
357     Info.set<EIIK_MMO>(MMOs[0]);
358 }
359 
360 void MachineInstr::dropMemRefs(MachineFunction &MF) {
361   if (memoperands_empty())
362     return;
363 
364   setExtraInfo(MF, {}, getPreInstrSymbol(), getPostInstrSymbol(),
365                getHeapAllocMarker(), getPCSections(), getCFIType());
366 }
367 
368 void MachineInstr::setMemRefs(MachineFunction &MF,
369                               ArrayRef<MachineMemOperand *> MMOs) {
370   if (MMOs.empty()) {
371     dropMemRefs(MF);
372     return;
373   }
374 
375   setExtraInfo(MF, MMOs, getPreInstrSymbol(), getPostInstrSymbol(),
376                getHeapAllocMarker(), getPCSections(), getCFIType());
377 }
378 
379 void MachineInstr::addMemOperand(MachineFunction &MF,
380                                  MachineMemOperand *MO) {
381   SmallVector<MachineMemOperand *, 2> MMOs;
382   MMOs.append(memoperands_begin(), memoperands_end());
383   MMOs.push_back(MO);
384   setMemRefs(MF, MMOs);
385 }
386 
387 void MachineInstr::cloneMemRefs(MachineFunction &MF, const MachineInstr &MI) {
388   if (this == &MI)
389     // Nothing to do for a self-clone!
390     return;
391 
392   assert(&MF == MI.getMF() &&
393          "Invalid machine functions when cloning memory refrences!");
394   // See if we can just steal the extra info already allocated for the
395   // instruction. We can do this whenever the pre- and post-instruction symbols
396   // are the same (including null).
397   if (getPreInstrSymbol() == MI.getPreInstrSymbol() &&
398       getPostInstrSymbol() == MI.getPostInstrSymbol() &&
399       getHeapAllocMarker() == MI.getHeapAllocMarker() &&
400       getPCSections() == MI.getPCSections()) {
401     Info = MI.Info;
402     return;
403   }
404 
405   // Otherwise, fall back on a copy-based clone.
406   setMemRefs(MF, MI.memoperands());
407 }
408 
409 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
410 /// identical.
411 static bool hasIdenticalMMOs(ArrayRef<MachineMemOperand *> LHS,
412                              ArrayRef<MachineMemOperand *> RHS) {
413   if (LHS.size() != RHS.size())
414     return false;
415 
416   auto LHSPointees = make_pointee_range(LHS);
417   auto RHSPointees = make_pointee_range(RHS);
418   return std::equal(LHSPointees.begin(), LHSPointees.end(),
419                     RHSPointees.begin());
420 }
421 
422 void MachineInstr::cloneMergedMemRefs(MachineFunction &MF,
423                                       ArrayRef<const MachineInstr *> MIs) {
424   // Try handling easy numbers of MIs with simpler mechanisms.
425   if (MIs.empty()) {
426     dropMemRefs(MF);
427     return;
428   }
429   if (MIs.size() == 1) {
430     cloneMemRefs(MF, *MIs[0]);
431     return;
432   }
433   // Because an empty memoperands list provides *no* information and must be
434   // handled conservatively (assuming the instruction can do anything), the only
435   // way to merge with it is to drop all other memoperands.
436   if (MIs[0]->memoperands_empty()) {
437     dropMemRefs(MF);
438     return;
439   }
440 
441   // Handle the general case.
442   SmallVector<MachineMemOperand *, 2> MergedMMOs;
443   // Start with the first instruction.
444   assert(&MF == MIs[0]->getMF() &&
445          "Invalid machine functions when cloning memory references!");
446   MergedMMOs.append(MIs[0]->memoperands_begin(), MIs[0]->memoperands_end());
447   // Now walk all the other instructions and accumulate any different MMOs.
448   for (const MachineInstr &MI : make_pointee_range(MIs.slice(1))) {
449     assert(&MF == MI.getMF() &&
450            "Invalid machine functions when cloning memory references!");
451 
452     // Skip MIs with identical operands to the first. This is a somewhat
453     // arbitrary hack but will catch common cases without being quadratic.
454     // TODO: We could fully implement merge semantics here if needed.
455     if (hasIdenticalMMOs(MIs[0]->memoperands(), MI.memoperands()))
456       continue;
457 
458     // Because an empty memoperands list provides *no* information and must be
459     // handled conservatively (assuming the instruction can do anything), the
460     // only way to merge with it is to drop all other memoperands.
461     if (MI.memoperands_empty()) {
462       dropMemRefs(MF);
463       return;
464     }
465 
466     // Otherwise accumulate these into our temporary buffer of the merged state.
467     MergedMMOs.append(MI.memoperands_begin(), MI.memoperands_end());
468   }
469 
470   setMemRefs(MF, MergedMMOs);
471 }
472 
473 void MachineInstr::setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
474   // Do nothing if old and new symbols are the same.
475   if (Symbol == getPreInstrSymbol())
476     return;
477 
478   // If there was only one symbol and we're removing it, just clear info.
479   if (!Symbol && Info.is<EIIK_PreInstrSymbol>()) {
480     Info.clear();
481     return;
482   }
483 
484   setExtraInfo(MF, memoperands(), Symbol, getPostInstrSymbol(),
485                getHeapAllocMarker(), getPCSections(), getCFIType());
486 }
487 
488 void MachineInstr::setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
489   // Do nothing if old and new symbols are the same.
490   if (Symbol == getPostInstrSymbol())
491     return;
492 
493   // If there was only one symbol and we're removing it, just clear info.
494   if (!Symbol && Info.is<EIIK_PostInstrSymbol>()) {
495     Info.clear();
496     return;
497   }
498 
499   setExtraInfo(MF, memoperands(), getPreInstrSymbol(), Symbol,
500                getHeapAllocMarker(), getPCSections(), getCFIType());
501 }
502 
503 void MachineInstr::setHeapAllocMarker(MachineFunction &MF, MDNode *Marker) {
504   // Do nothing if old and new symbols are the same.
505   if (Marker == getHeapAllocMarker())
506     return;
507 
508   setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(),
509                Marker, getPCSections(), getCFIType());
510 }
511 
512 void MachineInstr::setPCSections(MachineFunction &MF, MDNode *PCSections) {
513   // Do nothing if old and new symbols are the same.
514   if (PCSections == getPCSections())
515     return;
516 
517   setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(),
518                getHeapAllocMarker(), PCSections, getCFIType());
519 }
520 
521 void MachineInstr::setCFIType(MachineFunction &MF, uint32_t Type) {
522   // Do nothing if old and new types are the same.
523   if (Type == getCFIType())
524     return;
525 
526   setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(),
527                getHeapAllocMarker(), getPCSections(), Type);
528 }
529 
530 void MachineInstr::cloneInstrSymbols(MachineFunction &MF,
531                                      const MachineInstr &MI) {
532   if (this == &MI)
533     // Nothing to do for a self-clone!
534     return;
535 
536   assert(&MF == MI.getMF() &&
537          "Invalid machine functions when cloning instruction symbols!");
538 
539   setPreInstrSymbol(MF, MI.getPreInstrSymbol());
540   setPostInstrSymbol(MF, MI.getPostInstrSymbol());
541   setHeapAllocMarker(MF, MI.getHeapAllocMarker());
542   setPCSections(MF, MI.getPCSections());
543 }
544 
545 uint32_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
546   // For now, the just return the union of the flags. If the flags get more
547   // complicated over time, we might need more logic here.
548   return getFlags() | Other.getFlags();
549 }
550 
551 uint32_t MachineInstr::copyFlagsFromInstruction(const Instruction &I) {
552   uint32_t MIFlags = 0;
553   // Copy the wrapping flags.
554   if (const OverflowingBinaryOperator *OB =
555           dyn_cast<OverflowingBinaryOperator>(&I)) {
556     if (OB->hasNoSignedWrap())
557       MIFlags |= MachineInstr::MIFlag::NoSWrap;
558     if (OB->hasNoUnsignedWrap())
559       MIFlags |= MachineInstr::MIFlag::NoUWrap;
560   }
561 
562   // Copy the exact flag.
563   if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I))
564     if (PE->isExact())
565       MIFlags |= MachineInstr::MIFlag::IsExact;
566 
567   // Copy the fast-math flags.
568   if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) {
569     const FastMathFlags Flags = FP->getFastMathFlags();
570     if (Flags.noNaNs())
571       MIFlags |= MachineInstr::MIFlag::FmNoNans;
572     if (Flags.noInfs())
573       MIFlags |= MachineInstr::MIFlag::FmNoInfs;
574     if (Flags.noSignedZeros())
575       MIFlags |= MachineInstr::MIFlag::FmNsz;
576     if (Flags.allowReciprocal())
577       MIFlags |= MachineInstr::MIFlag::FmArcp;
578     if (Flags.allowContract())
579       MIFlags |= MachineInstr::MIFlag::FmContract;
580     if (Flags.approxFunc())
581       MIFlags |= MachineInstr::MIFlag::FmAfn;
582     if (Flags.allowReassoc())
583       MIFlags |= MachineInstr::MIFlag::FmReassoc;
584   }
585 
586   if (I.getMetadata(LLVMContext::MD_unpredictable))
587     MIFlags |= MachineInstr::MIFlag::Unpredictable;
588 
589   return MIFlags;
590 }
591 
592 void MachineInstr::copyIRFlags(const Instruction &I) {
593   Flags = copyFlagsFromInstruction(I);
594 }
595 
596 bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const {
597   assert(!isBundledWithPred() && "Must be called on bundle header");
598   for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
599     if (MII->getDesc().getFlags() & Mask) {
600       if (Type == AnyInBundle)
601         return true;
602     } else {
603       if (Type == AllInBundle && !MII->isBundle())
604         return false;
605     }
606     // This was the last instruction in the bundle.
607     if (!MII->isBundledWithSucc())
608       return Type == AllInBundle;
609   }
610 }
611 
612 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
613                                  MICheckType Check) const {
614   // If opcodes or number of operands are not the same then the two
615   // instructions are obviously not identical.
616   if (Other.getOpcode() != getOpcode() ||
617       Other.getNumOperands() != getNumOperands())
618     return false;
619 
620   if (isBundle()) {
621     // We have passed the test above that both instructions have the same
622     // opcode, so we know that both instructions are bundles here. Let's compare
623     // MIs inside the bundle.
624     assert(Other.isBundle() && "Expected that both instructions are bundles.");
625     MachineBasicBlock::const_instr_iterator I1 = getIterator();
626     MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
627     // Loop until we analysed the last intruction inside at least one of the
628     // bundles.
629     while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
630       ++I1;
631       ++I2;
632       if (!I1->isIdenticalTo(*I2, Check))
633         return false;
634     }
635     // If we've reached the end of just one of the two bundles, but not both,
636     // the instructions are not identical.
637     if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
638       return false;
639   }
640 
641   // Check operands to make sure they match.
642   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
643     const MachineOperand &MO = getOperand(i);
644     const MachineOperand &OMO = Other.getOperand(i);
645     if (!MO.isReg()) {
646       if (!MO.isIdenticalTo(OMO))
647         return false;
648       continue;
649     }
650 
651     // Clients may or may not want to ignore defs when testing for equality.
652     // For example, machine CSE pass only cares about finding common
653     // subexpressions, so it's safe to ignore virtual register defs.
654     if (MO.isDef()) {
655       if (Check == IgnoreDefs)
656         continue;
657       else if (Check == IgnoreVRegDefs) {
658         if (!MO.getReg().isVirtual() || !OMO.getReg().isVirtual())
659           if (!MO.isIdenticalTo(OMO))
660             return false;
661       } else {
662         if (!MO.isIdenticalTo(OMO))
663           return false;
664         if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
665           return false;
666       }
667     } else {
668       if (!MO.isIdenticalTo(OMO))
669         return false;
670       if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
671         return false;
672     }
673   }
674   // If DebugLoc does not match then two debug instructions are not identical.
675   if (isDebugInstr())
676     if (getDebugLoc() && Other.getDebugLoc() &&
677         getDebugLoc() != Other.getDebugLoc())
678       return false;
679   // If pre- or post-instruction symbols do not match then the two instructions
680   // are not identical.
681   if (getPreInstrSymbol() != Other.getPreInstrSymbol() ||
682       getPostInstrSymbol() != Other.getPostInstrSymbol())
683     return false;
684   // Call instructions with different CFI types are not identical.
685   if (isCall() && getCFIType() != Other.getCFIType())
686     return false;
687 
688   return true;
689 }
690 
691 bool MachineInstr::isEquivalentDbgInstr(const MachineInstr &Other) const {
692   if (!isDebugValueLike() || !Other.isDebugValueLike())
693     return false;
694   if (getDebugLoc() != Other.getDebugLoc())
695     return false;
696   if (getDebugVariable() != Other.getDebugVariable())
697     return false;
698   if (getNumDebugOperands() != Other.getNumDebugOperands())
699     return false;
700   for (unsigned OpIdx = 0; OpIdx < getNumDebugOperands(); ++OpIdx)
701     if (!getDebugOperand(OpIdx).isIdenticalTo(Other.getDebugOperand(OpIdx)))
702       return false;
703   if (!DIExpression::isEqualExpression(
704           getDebugExpression(), isIndirectDebugValue(),
705           Other.getDebugExpression(), Other.isIndirectDebugValue()))
706     return false;
707   return true;
708 }
709 
710 const MachineFunction *MachineInstr::getMF() const {
711   return getParent()->getParent();
712 }
713 
714 MachineInstr *MachineInstr::removeFromParent() {
715   assert(getParent() && "Not embedded in a basic block!");
716   return getParent()->remove(this);
717 }
718 
719 MachineInstr *MachineInstr::removeFromBundle() {
720   assert(getParent() && "Not embedded in a basic block!");
721   return getParent()->remove_instr(this);
722 }
723 
724 void MachineInstr::eraseFromParent() {
725   assert(getParent() && "Not embedded in a basic block!");
726   getParent()->erase(this);
727 }
728 
729 void MachineInstr::eraseFromBundle() {
730   assert(getParent() && "Not embedded in a basic block!");
731   getParent()->erase_instr(this);
732 }
733 
734 bool MachineInstr::isCandidateForCallSiteEntry(QueryType Type) const {
735   if (!isCall(Type))
736     return false;
737   switch (getOpcode()) {
738   case TargetOpcode::PATCHPOINT:
739   case TargetOpcode::STACKMAP:
740   case TargetOpcode::STATEPOINT:
741   case TargetOpcode::FENTRY_CALL:
742     return false;
743   }
744   return true;
745 }
746 
747 bool MachineInstr::shouldUpdateCallSiteInfo() const {
748   if (isBundle())
749     return isCandidateForCallSiteEntry(MachineInstr::AnyInBundle);
750   return isCandidateForCallSiteEntry();
751 }
752 
753 unsigned MachineInstr::getNumExplicitOperands() const {
754   unsigned NumOperands = MCID->getNumOperands();
755   if (!MCID->isVariadic())
756     return NumOperands;
757 
758   for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) {
759     const MachineOperand &MO = getOperand(I);
760     // The operands must always be in the following order:
761     // - explicit reg defs,
762     // - other explicit operands (reg uses, immediates, etc.),
763     // - implicit reg defs
764     // - implicit reg uses
765     if (MO.isReg() && MO.isImplicit())
766       break;
767     ++NumOperands;
768   }
769   return NumOperands;
770 }
771 
772 unsigned MachineInstr::getNumExplicitDefs() const {
773   unsigned NumDefs = MCID->getNumDefs();
774   if (!MCID->isVariadic())
775     return NumDefs;
776 
777   for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) {
778     const MachineOperand &MO = getOperand(I);
779     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
780       break;
781     ++NumDefs;
782   }
783   return NumDefs;
784 }
785 
786 void MachineInstr::bundleWithPred() {
787   assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
788   setFlag(BundledPred);
789   MachineBasicBlock::instr_iterator Pred = getIterator();
790   --Pred;
791   assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
792   Pred->setFlag(BundledSucc);
793 }
794 
795 void MachineInstr::bundleWithSucc() {
796   assert(!isBundledWithSucc() && "MI is already bundled with its successor");
797   setFlag(BundledSucc);
798   MachineBasicBlock::instr_iterator Succ = getIterator();
799   ++Succ;
800   assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
801   Succ->setFlag(BundledPred);
802 }
803 
804 void MachineInstr::unbundleFromPred() {
805   assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
806   clearFlag(BundledPred);
807   MachineBasicBlock::instr_iterator Pred = getIterator();
808   --Pred;
809   assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
810   Pred->clearFlag(BundledSucc);
811 }
812 
813 void MachineInstr::unbundleFromSucc() {
814   assert(isBundledWithSucc() && "MI isn't bundled with its successor");
815   clearFlag(BundledSucc);
816   MachineBasicBlock::instr_iterator Succ = getIterator();
817   ++Succ;
818   assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
819   Succ->clearFlag(BundledPred);
820 }
821 
822 bool MachineInstr::isStackAligningInlineAsm() const {
823   if (isInlineAsm()) {
824     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
825     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
826       return true;
827   }
828   return false;
829 }
830 
831 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
832   assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
833   unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
834   return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
835 }
836 
837 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
838                                        unsigned *GroupNo) const {
839   assert(isInlineAsm() && "Expected an inline asm instruction");
840   assert(OpIdx < getNumOperands() && "OpIdx out of range");
841 
842   // Ignore queries about the initial operands.
843   if (OpIdx < InlineAsm::MIOp_FirstOperand)
844     return -1;
845 
846   unsigned Group = 0;
847   unsigned NumOps;
848   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
849        i += NumOps) {
850     const MachineOperand &FlagMO = getOperand(i);
851     // If we reach the implicit register operands, stop looking.
852     if (!FlagMO.isImm())
853       return -1;
854     const InlineAsm::Flag F(FlagMO.getImm());
855     NumOps = 1 + F.getNumOperandRegisters();
856     if (i + NumOps > OpIdx) {
857       if (GroupNo)
858         *GroupNo = Group;
859       return i;
860     }
861     ++Group;
862   }
863   return -1;
864 }
865 
866 const DILabel *MachineInstr::getDebugLabel() const {
867   assert(isDebugLabel() && "not a DBG_LABEL");
868   return cast<DILabel>(getOperand(0).getMetadata());
869 }
870 
871 const MachineOperand &MachineInstr::getDebugVariableOp() const {
872   assert((isDebugValueLike()) && "not a DBG_VALUE*");
873   unsigned VariableOp = isNonListDebugValue() ? 2 : 0;
874   return getOperand(VariableOp);
875 }
876 
877 MachineOperand &MachineInstr::getDebugVariableOp() {
878   assert((isDebugValueLike()) && "not a DBG_VALUE*");
879   unsigned VariableOp = isNonListDebugValue() ? 2 : 0;
880   return getOperand(VariableOp);
881 }
882 
883 const DILocalVariable *MachineInstr::getDebugVariable() const {
884   return cast<DILocalVariable>(getDebugVariableOp().getMetadata());
885 }
886 
887 const MachineOperand &MachineInstr::getDebugExpressionOp() const {
888   assert((isDebugValueLike()) && "not a DBG_VALUE*");
889   unsigned ExpressionOp = isNonListDebugValue() ? 3 : 1;
890   return getOperand(ExpressionOp);
891 }
892 
893 MachineOperand &MachineInstr::getDebugExpressionOp() {
894   assert((isDebugValueLike()) && "not a DBG_VALUE*");
895   unsigned ExpressionOp = isNonListDebugValue() ? 3 : 1;
896   return getOperand(ExpressionOp);
897 }
898 
899 const DIExpression *MachineInstr::getDebugExpression() const {
900   return cast<DIExpression>(getDebugExpressionOp().getMetadata());
901 }
902 
903 bool MachineInstr::isDebugEntryValue() const {
904   return isDebugValue() && getDebugExpression()->isEntryValue();
905 }
906 
907 const TargetRegisterClass*
908 MachineInstr::getRegClassConstraint(unsigned OpIdx,
909                                     const TargetInstrInfo *TII,
910                                     const TargetRegisterInfo *TRI) const {
911   assert(getParent() && "Can't have an MBB reference here!");
912   assert(getMF() && "Can't have an MF reference here!");
913   const MachineFunction &MF = *getMF();
914 
915   // Most opcodes have fixed constraints in their MCInstrDesc.
916   if (!isInlineAsm())
917     return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
918 
919   if (!getOperand(OpIdx).isReg())
920     return nullptr;
921 
922   // For tied uses on inline asm, get the constraint from the def.
923   unsigned DefIdx;
924   if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
925     OpIdx = DefIdx;
926 
927   // Inline asm stores register class constraints in the flag word.
928   int FlagIdx = findInlineAsmFlagIdx(OpIdx);
929   if (FlagIdx < 0)
930     return nullptr;
931 
932   const InlineAsm::Flag F(getOperand(FlagIdx).getImm());
933   unsigned RCID;
934   if ((F.isRegUseKind() || F.isRegDefKind() || F.isRegDefEarlyClobberKind()) &&
935       F.hasRegClassConstraint(RCID))
936     return TRI->getRegClass(RCID);
937 
938   // Assume that all registers in a memory operand are pointers.
939   if (F.isMemKind())
940     return TRI->getPointerRegClass(MF);
941 
942   return nullptr;
943 }
944 
945 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
946     Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
947     const TargetRegisterInfo *TRI, bool ExploreBundle) const {
948   // Check every operands inside the bundle if we have
949   // been asked to.
950   if (ExploreBundle)
951     for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
952          ++OpndIt)
953       CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
954           OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
955   else
956     // Otherwise, just check the current operands.
957     for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
958       CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
959   return CurRC;
960 }
961 
962 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
963     unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
964     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
965   assert(CurRC && "Invalid initial register class");
966   // Check if Reg is constrained by some of its use/def from MI.
967   const MachineOperand &MO = getOperand(OpIdx);
968   if (!MO.isReg() || MO.getReg() != Reg)
969     return CurRC;
970   // If yes, accumulate the constraints through the operand.
971   return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
972 }
973 
974 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
975     unsigned OpIdx, const TargetRegisterClass *CurRC,
976     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
977   const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
978   const MachineOperand &MO = getOperand(OpIdx);
979   assert(MO.isReg() &&
980          "Cannot get register constraints for non-register operand");
981   assert(CurRC && "Invalid initial register class");
982   if (unsigned SubIdx = MO.getSubReg()) {
983     if (OpRC)
984       CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
985     else
986       CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
987   } else if (OpRC)
988     CurRC = TRI->getCommonSubClass(CurRC, OpRC);
989   return CurRC;
990 }
991 
992 /// Return the number of instructions inside the MI bundle, not counting the
993 /// header instruction.
994 unsigned MachineInstr::getBundleSize() const {
995   MachineBasicBlock::const_instr_iterator I = getIterator();
996   unsigned Size = 0;
997   while (I->isBundledWithSucc()) {
998     ++Size;
999     ++I;
1000   }
1001   return Size;
1002 }
1003 
1004 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1005 /// the given register (not considering sub/super-registers).
1006 bool MachineInstr::hasRegisterImplicitUseOperand(Register Reg) const {
1007   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1008     const MachineOperand &MO = getOperand(i);
1009     if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1010       return true;
1011   }
1012   return false;
1013 }
1014 
1015 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1016 /// the specific register or -1 if it is not found. It further tightens
1017 /// the search criteria to a use that kills the register if isKill is true.
1018 int MachineInstr::findRegisterUseOperandIdx(
1019     Register Reg, bool isKill, const TargetRegisterInfo *TRI) const {
1020   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1021     const MachineOperand &MO = getOperand(i);
1022     if (!MO.isReg() || !MO.isUse())
1023       continue;
1024     Register MOReg = MO.getReg();
1025     if (!MOReg)
1026       continue;
1027     if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg)))
1028       if (!isKill || MO.isKill())
1029         return i;
1030   }
1031   return -1;
1032 }
1033 
1034 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1035 /// indicating if this instruction reads or writes Reg. This also considers
1036 /// partial defines.
1037 std::pair<bool,bool>
1038 MachineInstr::readsWritesVirtualRegister(Register Reg,
1039                                          SmallVectorImpl<unsigned> *Ops) const {
1040   bool PartDef = false; // Partial redefine.
1041   bool FullDef = false; // Full define.
1042   bool Use = false;
1043 
1044   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1045     const MachineOperand &MO = getOperand(i);
1046     if (!MO.isReg() || MO.getReg() != Reg)
1047       continue;
1048     if (Ops)
1049       Ops->push_back(i);
1050     if (MO.isUse())
1051       Use |= !MO.isUndef();
1052     else if (MO.getSubReg() && !MO.isUndef())
1053       // A partial def undef doesn't count as reading the register.
1054       PartDef = true;
1055     else
1056       FullDef = true;
1057   }
1058   // A partial redefine uses Reg unless there is also a full define.
1059   return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1060 }
1061 
1062 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1063 /// the specified register or -1 if it is not found. If isDead is true, defs
1064 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1065 /// also checks if there is a def of a super-register.
1066 int
1067 MachineInstr::findRegisterDefOperandIdx(Register Reg, bool isDead, bool Overlap,
1068                                         const TargetRegisterInfo *TRI) const {
1069   bool isPhys = Reg.isPhysical();
1070   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1071     const MachineOperand &MO = getOperand(i);
1072     // Accept regmask operands when Overlap is set.
1073     // Ignore them when looking for a specific def operand (Overlap == false).
1074     if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1075       return i;
1076     if (!MO.isReg() || !MO.isDef())
1077       continue;
1078     Register MOReg = MO.getReg();
1079     bool Found = (MOReg == Reg);
1080     if (!Found && TRI && isPhys && MOReg.isPhysical()) {
1081       if (Overlap)
1082         Found = TRI->regsOverlap(MOReg, Reg);
1083       else
1084         Found = TRI->isSubRegister(MOReg, Reg);
1085     }
1086     if (Found && (!isDead || MO.isDead()))
1087       return i;
1088   }
1089   return -1;
1090 }
1091 
1092 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1093 /// operand list that is used to represent the predicate. It returns -1 if
1094 /// none is found.
1095 int MachineInstr::findFirstPredOperandIdx() const {
1096   // Don't call MCID.findFirstPredOperandIdx() because this variant
1097   // is sometimes called on an instruction that's not yet complete, and
1098   // so the number of operands is less than the MCID indicates. In
1099   // particular, the PTX target does this.
1100   const MCInstrDesc &MCID = getDesc();
1101   if (MCID.isPredicable()) {
1102     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1103       if (MCID.operands()[i].isPredicate())
1104         return i;
1105   }
1106 
1107   return -1;
1108 }
1109 
1110 // MachineOperand::TiedTo is 4 bits wide.
1111 const unsigned TiedMax = 15;
1112 
1113 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1114 ///
1115 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1116 /// field. TiedTo can have these values:
1117 ///
1118 /// 0:              Operand is not tied to anything.
1119 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1120 /// TiedMax:        Tied to an operand >= TiedMax-1.
1121 ///
1122 /// The tied def must be one of the first TiedMax operands on a normal
1123 /// instruction. INLINEASM instructions allow more tied defs.
1124 ///
1125 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1126   MachineOperand &DefMO = getOperand(DefIdx);
1127   MachineOperand &UseMO = getOperand(UseIdx);
1128   assert(DefMO.isDef() && "DefIdx must be a def operand");
1129   assert(UseMO.isUse() && "UseIdx must be a use operand");
1130   assert(!DefMO.isTied() && "Def is already tied to another use");
1131   assert(!UseMO.isTied() && "Use is already tied to another def");
1132 
1133   if (DefIdx < TiedMax)
1134     UseMO.TiedTo = DefIdx + 1;
1135   else {
1136     // Inline asm can use the group descriptors to find tied operands,
1137     // statepoint tied operands are trivial to match (1-1 reg def with reg use),
1138     // but on normal instruction, the tied def must be within the first TiedMax
1139     // operands.
1140     assert((isInlineAsm() || getOpcode() == TargetOpcode::STATEPOINT) &&
1141            "DefIdx out of range");
1142     UseMO.TiedTo = TiedMax;
1143   }
1144 
1145   // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1146   DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1147 }
1148 
1149 /// Given the index of a tied register operand, find the operand it is tied to.
1150 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1151 /// which must exist.
1152 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1153   const MachineOperand &MO = getOperand(OpIdx);
1154   assert(MO.isTied() && "Operand isn't tied");
1155 
1156   // Normally TiedTo is in range.
1157   if (MO.TiedTo < TiedMax)
1158     return MO.TiedTo - 1;
1159 
1160   // Uses on normal instructions can be out of range.
1161   if (!isInlineAsm() && getOpcode() != TargetOpcode::STATEPOINT) {
1162     // Normal tied defs must be in the 0..TiedMax-1 range.
1163     if (MO.isUse())
1164       return TiedMax - 1;
1165     // MO is a def. Search for the tied use.
1166     for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1167       const MachineOperand &UseMO = getOperand(i);
1168       if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1169         return i;
1170     }
1171     llvm_unreachable("Can't find tied use");
1172   }
1173 
1174   if (getOpcode() == TargetOpcode::STATEPOINT) {
1175     // In STATEPOINT defs correspond 1-1 to GC pointer operands passed
1176     // on registers.
1177     StatepointOpers SO(this);
1178     unsigned CurUseIdx = SO.getFirstGCPtrIdx();
1179     assert(CurUseIdx != -1U && "only gc pointer statepoint operands can be tied");
1180     unsigned NumDefs = getNumDefs();
1181     for (unsigned CurDefIdx = 0; CurDefIdx < NumDefs; ++CurDefIdx) {
1182       while (!getOperand(CurUseIdx).isReg())
1183         CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx);
1184       if (OpIdx == CurDefIdx)
1185         return CurUseIdx;
1186       if (OpIdx == CurUseIdx)
1187         return CurDefIdx;
1188       CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx);
1189     }
1190     llvm_unreachable("Can't find tied use");
1191   }
1192 
1193   // Now deal with inline asm by parsing the operand group descriptor flags.
1194   // Find the beginning of each operand group.
1195   SmallVector<unsigned, 8> GroupIdx;
1196   unsigned OpIdxGroup = ~0u;
1197   unsigned NumOps;
1198   for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1199        i += NumOps) {
1200     const MachineOperand &FlagMO = getOperand(i);
1201     assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1202     unsigned CurGroup = GroupIdx.size();
1203     GroupIdx.push_back(i);
1204     const InlineAsm::Flag F(FlagMO.getImm());
1205     NumOps = 1 + F.getNumOperandRegisters();
1206     // OpIdx belongs to this operand group.
1207     if (OpIdx > i && OpIdx < i + NumOps)
1208       OpIdxGroup = CurGroup;
1209     unsigned TiedGroup;
1210     if (!F.isUseOperandTiedToDef(TiedGroup))
1211       continue;
1212     // Operands in this group are tied to operands in TiedGroup which must be
1213     // earlier. Find the number of operands between the two groups.
1214     unsigned Delta = i - GroupIdx[TiedGroup];
1215 
1216     // OpIdx is a use tied to TiedGroup.
1217     if (OpIdxGroup == CurGroup)
1218       return OpIdx - Delta;
1219 
1220     // OpIdx is a def tied to this use group.
1221     if (OpIdxGroup == TiedGroup)
1222       return OpIdx + Delta;
1223   }
1224   llvm_unreachable("Invalid tied operand on inline asm");
1225 }
1226 
1227 /// clearKillInfo - Clears kill flags on all operands.
1228 ///
1229 void MachineInstr::clearKillInfo() {
1230   for (MachineOperand &MO : operands()) {
1231     if (MO.isReg() && MO.isUse())
1232       MO.setIsKill(false);
1233   }
1234 }
1235 
1236 void MachineInstr::substituteRegister(Register FromReg, Register ToReg,
1237                                       unsigned SubIdx,
1238                                       const TargetRegisterInfo &RegInfo) {
1239   if (ToReg.isPhysical()) {
1240     if (SubIdx)
1241       ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1242     for (MachineOperand &MO : operands()) {
1243       if (!MO.isReg() || MO.getReg() != FromReg)
1244         continue;
1245       MO.substPhysReg(ToReg, RegInfo);
1246     }
1247   } else {
1248     for (MachineOperand &MO : operands()) {
1249       if (!MO.isReg() || MO.getReg() != FromReg)
1250         continue;
1251       MO.substVirtReg(ToReg, SubIdx, RegInfo);
1252     }
1253   }
1254 }
1255 
1256 /// isSafeToMove - Return true if it is safe to move this instruction. If
1257 /// SawStore is set to true, it means that there is a store (or call) between
1258 /// the instruction's location and its intended destination.
1259 bool MachineInstr::isSafeToMove(AAResults *AA, bool &SawStore) const {
1260   // Ignore stuff that we obviously can't move.
1261   //
1262   // Treat volatile loads as stores. This is not strictly necessary for
1263   // volatiles, but it is required for atomic loads. It is not allowed to move
1264   // a load across an atomic load with Ordering > Monotonic.
1265   if (mayStore() || isCall() || isPHI() ||
1266       (mayLoad() && hasOrderedMemoryRef())) {
1267     SawStore = true;
1268     return false;
1269   }
1270 
1271   if (isPosition() || isDebugInstr() || isTerminator() ||
1272       mayRaiseFPException() || hasUnmodeledSideEffects() ||
1273       isJumpTableDebugInfo())
1274     return false;
1275 
1276   // See if this instruction does a load.  If so, we have to guarantee that the
1277   // loaded value doesn't change between the load and the its intended
1278   // destination. The check for isInvariantLoad gives the target the chance to
1279   // classify the load as always returning a constant, e.g. a constant pool
1280   // load.
1281   if (mayLoad() && !isDereferenceableInvariantLoad())
1282     // Otherwise, this is a real load.  If there is a store between the load and
1283     // end of block, we can't move it.
1284     return !SawStore;
1285 
1286   return true;
1287 }
1288 
1289 static bool MemOperandsHaveAlias(const MachineFrameInfo &MFI, AAResults *AA,
1290                                  bool UseTBAA, const MachineMemOperand *MMOa,
1291                                  const MachineMemOperand *MMOb) {
1292   // The following interface to AA is fashioned after DAGCombiner::isAlias and
1293   // operates with MachineMemOperand offset with some important assumptions:
1294   //   - LLVM fundamentally assumes flat address spaces.
1295   //   - MachineOperand offset can *only* result from legalization and cannot
1296   //     affect queries other than the trivial case of overlap checking.
1297   //   - These offsets never wrap and never step outside of allocated objects.
1298   //   - There should never be any negative offsets here.
1299   //
1300   // FIXME: Modify API to hide this math from "user"
1301   // Even before we go to AA we can reason locally about some memory objects. It
1302   // can save compile time, and possibly catch some corner cases not currently
1303   // covered.
1304 
1305   int64_t OffsetA = MMOa->getOffset();
1306   int64_t OffsetB = MMOb->getOffset();
1307   int64_t MinOffset = std::min(OffsetA, OffsetB);
1308 
1309   uint64_t WidthA = MMOa->getSize();
1310   uint64_t WidthB = MMOb->getSize();
1311   bool KnownWidthA = WidthA != MemoryLocation::UnknownSize;
1312   bool KnownWidthB = WidthB != MemoryLocation::UnknownSize;
1313 
1314   const Value *ValA = MMOa->getValue();
1315   const Value *ValB = MMOb->getValue();
1316   bool SameVal = (ValA && ValB && (ValA == ValB));
1317   if (!SameVal) {
1318     const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
1319     const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
1320     if (PSVa && ValB && !PSVa->mayAlias(&MFI))
1321       return false;
1322     if (PSVb && ValA && !PSVb->mayAlias(&MFI))
1323       return false;
1324     if (PSVa && PSVb && (PSVa == PSVb))
1325       SameVal = true;
1326   }
1327 
1328   if (SameVal) {
1329     if (!KnownWidthA || !KnownWidthB)
1330       return true;
1331     int64_t MaxOffset = std::max(OffsetA, OffsetB);
1332     int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
1333     return (MinOffset + LowWidth > MaxOffset);
1334   }
1335 
1336   if (!AA)
1337     return true;
1338 
1339   if (!ValA || !ValB)
1340     return true;
1341 
1342   assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
1343   assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
1344 
1345   int64_t OverlapA =
1346       KnownWidthA ? WidthA + OffsetA - MinOffset : MemoryLocation::UnknownSize;
1347   int64_t OverlapB =
1348       KnownWidthB ? WidthB + OffsetB - MinOffset : MemoryLocation::UnknownSize;
1349 
1350   return !AA->isNoAlias(
1351       MemoryLocation(ValA, OverlapA, UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1352       MemoryLocation(ValB, OverlapB,
1353                      UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1354 }
1355 
1356 bool MachineInstr::mayAlias(AAResults *AA, const MachineInstr &Other,
1357                             bool UseTBAA) const {
1358   const MachineFunction *MF = getMF();
1359   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1360   const MachineFrameInfo &MFI = MF->getFrameInfo();
1361 
1362   // Exclude call instruction which may alter the memory but can not be handled
1363   // by this function.
1364   if (isCall() || Other.isCall())
1365     return true;
1366 
1367   // If neither instruction stores to memory, they can't alias in any
1368   // meaningful way, even if they read from the same address.
1369   if (!mayStore() && !Other.mayStore())
1370     return false;
1371 
1372   // Both instructions must be memory operations to be able to alias.
1373   if (!mayLoadOrStore() || !Other.mayLoadOrStore())
1374     return false;
1375 
1376   // Let the target decide if memory accesses cannot possibly overlap.
1377   if (TII->areMemAccessesTriviallyDisjoint(*this, Other))
1378     return false;
1379 
1380   // Memory operations without memory operands may access anything. Be
1381   // conservative and assume `MayAlias`.
1382   if (memoperands_empty() || Other.memoperands_empty())
1383     return true;
1384 
1385   // Skip if there are too many memory operands.
1386   auto NumChecks = getNumMemOperands() * Other.getNumMemOperands();
1387   if (NumChecks > TII->getMemOperandAACheckLimit())
1388     return true;
1389 
1390   // Check each pair of memory operands from both instructions, which can't
1391   // alias only if all pairs won't alias.
1392   for (auto *MMOa : memoperands())
1393     for (auto *MMOb : Other.memoperands())
1394       if (MemOperandsHaveAlias(MFI, AA, UseTBAA, MMOa, MMOb))
1395         return true;
1396 
1397   return false;
1398 }
1399 
1400 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1401 /// or volatile memory reference, or if the information describing the memory
1402 /// reference is not available. Return false if it is known to have no ordered
1403 /// memory references.
1404 bool MachineInstr::hasOrderedMemoryRef() const {
1405   // An instruction known never to access memory won't have a volatile access.
1406   if (!mayStore() &&
1407       !mayLoad() &&
1408       !isCall() &&
1409       !hasUnmodeledSideEffects())
1410     return false;
1411 
1412   // Otherwise, if the instruction has no memory reference information,
1413   // conservatively assume it wasn't preserved.
1414   if (memoperands_empty())
1415     return true;
1416 
1417   // Check if any of our memory operands are ordered.
1418   return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1419     return !MMO->isUnordered();
1420   });
1421 }
1422 
1423 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1424 /// trap and is loading from a location whose value is invariant across a run of
1425 /// this function.
1426 bool MachineInstr::isDereferenceableInvariantLoad() const {
1427   // If the instruction doesn't load at all, it isn't an invariant load.
1428   if (!mayLoad())
1429     return false;
1430 
1431   // If the instruction has lost its memoperands, conservatively assume that
1432   // it may not be an invariant load.
1433   if (memoperands_empty())
1434     return false;
1435 
1436   const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1437 
1438   for (MachineMemOperand *MMO : memoperands()) {
1439     if (!MMO->isUnordered())
1440       // If the memory operand has ordering side effects, we can't move the
1441       // instruction.  Such an instruction is technically an invariant load,
1442       // but the caller code would need updated to expect that.
1443       return false;
1444     if (MMO->isStore()) return false;
1445     if (MMO->isInvariant() && MMO->isDereferenceable())
1446       continue;
1447 
1448     // A load from a constant PseudoSourceValue is invariant.
1449     if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
1450       if (PSV->isConstant(&MFI))
1451         continue;
1452     }
1453 
1454     // Otherwise assume conservatively.
1455     return false;
1456   }
1457 
1458   // Everything checks out.
1459   return true;
1460 }
1461 
1462 /// isConstantValuePHI - If the specified instruction is a PHI that always
1463 /// merges together the same virtual register, return the register, otherwise
1464 /// return 0.
1465 unsigned MachineInstr::isConstantValuePHI() const {
1466   if (!isPHI())
1467     return 0;
1468   assert(getNumOperands() >= 3 &&
1469          "It's illegal to have a PHI without source operands");
1470 
1471   Register Reg = getOperand(1).getReg();
1472   for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1473     if (getOperand(i).getReg() != Reg)
1474       return 0;
1475   return Reg;
1476 }
1477 
1478 bool MachineInstr::hasUnmodeledSideEffects() const {
1479   if (hasProperty(MCID::UnmodeledSideEffects))
1480     return true;
1481   if (isInlineAsm()) {
1482     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1483     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1484       return true;
1485   }
1486 
1487   return false;
1488 }
1489 
1490 bool MachineInstr::isLoadFoldBarrier() const {
1491   return mayStore() || isCall() ||
1492          (hasUnmodeledSideEffects() && !isPseudoProbe());
1493 }
1494 
1495 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1496 ///
1497 bool MachineInstr::allDefsAreDead() const {
1498   for (const MachineOperand &MO : operands()) {
1499     if (!MO.isReg() || MO.isUse())
1500       continue;
1501     if (!MO.isDead())
1502       return false;
1503   }
1504   return true;
1505 }
1506 
1507 bool MachineInstr::allImplicitDefsAreDead() const {
1508   for (const MachineOperand &MO : implicit_operands()) {
1509     if (!MO.isReg() || MO.isUse())
1510       continue;
1511     if (!MO.isDead())
1512       return false;
1513   }
1514   return true;
1515 }
1516 
1517 /// copyImplicitOps - Copy implicit register operands from specified
1518 /// instruction to this instruction.
1519 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1520                                    const MachineInstr &MI) {
1521   for (const MachineOperand &MO :
1522        llvm::drop_begin(MI.operands(), MI.getDesc().getNumOperands()))
1523     if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1524       addOperand(MF, MO);
1525 }
1526 
1527 bool MachineInstr::hasComplexRegisterTies() const {
1528   const MCInstrDesc &MCID = getDesc();
1529   if (MCID.Opcode == TargetOpcode::STATEPOINT)
1530     return true;
1531   for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1532     const auto &Operand = getOperand(I);
1533     if (!Operand.isReg() || Operand.isDef())
1534       // Ignore the defined registers as MCID marks only the uses as tied.
1535       continue;
1536     int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
1537     int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
1538     if (ExpectedTiedIdx != TiedIdx)
1539       return true;
1540   }
1541   return false;
1542 }
1543 
1544 LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1545                                  const MachineRegisterInfo &MRI) const {
1546   const MachineOperand &Op = getOperand(OpIdx);
1547   if (!Op.isReg())
1548     return LLT{};
1549 
1550   if (isVariadic() || OpIdx >= getNumExplicitOperands())
1551     return MRI.getType(Op.getReg());
1552 
1553   auto &OpInfo = getDesc().operands()[OpIdx];
1554   if (!OpInfo.isGenericType())
1555     return MRI.getType(Op.getReg());
1556 
1557   if (PrintedTypes[OpInfo.getGenericTypeIndex()])
1558     return LLT{};
1559 
1560   LLT TypeToPrint = MRI.getType(Op.getReg());
1561   // Don't mark the type index printed if it wasn't actually printed: maybe
1562   // another operand with the same type index has an actual type attached:
1563   if (TypeToPrint.isValid())
1564     PrintedTypes.set(OpInfo.getGenericTypeIndex());
1565   return TypeToPrint;
1566 }
1567 
1568 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1569 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1570   dbgs() << "  ";
1571   print(dbgs());
1572 }
1573 
1574 LLVM_DUMP_METHOD void MachineInstr::dumprImpl(
1575     const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
1576     SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const {
1577   if (Depth >= MaxDepth)
1578     return;
1579   if (!AlreadySeenInstrs.insert(this).second)
1580     return;
1581   // PadToColumn always inserts at least one space.
1582   // Don't mess up the alignment if we don't want any space.
1583   if (Depth)
1584     fdbgs().PadToColumn(Depth * 2);
1585   print(fdbgs());
1586   for (const MachineOperand &MO : operands()) {
1587     if (!MO.isReg() || MO.isDef())
1588       continue;
1589     Register Reg = MO.getReg();
1590     if (Reg.isPhysical())
1591       continue;
1592     const MachineInstr *NewMI = MRI.getUniqueVRegDef(Reg);
1593     if (NewMI == nullptr)
1594       continue;
1595     NewMI->dumprImpl(MRI, Depth + 1, MaxDepth, AlreadySeenInstrs);
1596   }
1597 }
1598 
1599 LLVM_DUMP_METHOD void MachineInstr::dumpr(const MachineRegisterInfo &MRI,
1600                                           unsigned MaxDepth) const {
1601   SmallPtrSet<const MachineInstr *, 16> AlreadySeenInstrs;
1602   dumprImpl(MRI, 0, MaxDepth, AlreadySeenInstrs);
1603 }
1604 #endif
1605 
1606 void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
1607                          bool SkipDebugLoc, bool AddNewLine,
1608                          const TargetInstrInfo *TII) const {
1609   const Module *M = nullptr;
1610   const Function *F = nullptr;
1611   if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1612     F = &MF->getFunction();
1613     M = F->getParent();
1614     if (!TII)
1615       TII = MF->getSubtarget().getInstrInfo();
1616   }
1617 
1618   ModuleSlotTracker MST(M);
1619   if (F)
1620     MST.incorporateFunction(*F);
1621   print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, AddNewLine, TII);
1622 }
1623 
1624 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1625                          bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
1626                          bool AddNewLine, const TargetInstrInfo *TII) const {
1627   // We can be a bit tidier if we know the MachineFunction.
1628   const TargetRegisterInfo *TRI = nullptr;
1629   const MachineRegisterInfo *MRI = nullptr;
1630   const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1631   tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
1632 
1633   if (isCFIInstruction())
1634     assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
1635 
1636   SmallBitVector PrintedTypes(8);
1637   bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
1638   auto getTiedOperandIdx = [&](unsigned OpIdx) {
1639     if (!ShouldPrintRegisterTies)
1640       return 0U;
1641     const MachineOperand &MO = getOperand(OpIdx);
1642     if (MO.isReg() && MO.isTied() && !MO.isDef())
1643       return findTiedOperandIdx(OpIdx);
1644     return 0U;
1645   };
1646   unsigned StartOp = 0;
1647   unsigned e = getNumOperands();
1648 
1649   // Print explicitly defined operands on the left of an assignment syntax.
1650   while (StartOp < e) {
1651     const MachineOperand &MO = getOperand(StartOp);
1652     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
1653       break;
1654 
1655     if (StartOp != 0)
1656       OS << ", ";
1657 
1658     LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
1659     unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
1660     MO.print(OS, MST, TypeToPrint, StartOp, /*PrintDef=*/false, IsStandalone,
1661              ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1662     ++StartOp;
1663   }
1664 
1665   if (StartOp != 0)
1666     OS << " = ";
1667 
1668   if (getFlag(MachineInstr::FrameSetup))
1669     OS << "frame-setup ";
1670   if (getFlag(MachineInstr::FrameDestroy))
1671     OS << "frame-destroy ";
1672   if (getFlag(MachineInstr::FmNoNans))
1673     OS << "nnan ";
1674   if (getFlag(MachineInstr::FmNoInfs))
1675     OS << "ninf ";
1676   if (getFlag(MachineInstr::FmNsz))
1677     OS << "nsz ";
1678   if (getFlag(MachineInstr::FmArcp))
1679     OS << "arcp ";
1680   if (getFlag(MachineInstr::FmContract))
1681     OS << "contract ";
1682   if (getFlag(MachineInstr::FmAfn))
1683     OS << "afn ";
1684   if (getFlag(MachineInstr::FmReassoc))
1685     OS << "reassoc ";
1686   if (getFlag(MachineInstr::NoUWrap))
1687     OS << "nuw ";
1688   if (getFlag(MachineInstr::NoSWrap))
1689     OS << "nsw ";
1690   if (getFlag(MachineInstr::IsExact))
1691     OS << "exact ";
1692   if (getFlag(MachineInstr::NoFPExcept))
1693     OS << "nofpexcept ";
1694   if (getFlag(MachineInstr::NoMerge))
1695     OS << "nomerge ";
1696 
1697   // Print the opcode name.
1698   if (TII)
1699     OS << TII->getName(getOpcode());
1700   else
1701     OS << "UNKNOWN";
1702 
1703   if (SkipOpers)
1704     return;
1705 
1706   // Print the rest of the operands.
1707   bool FirstOp = true;
1708   unsigned AsmDescOp = ~0u;
1709   unsigned AsmOpCount = 0;
1710 
1711   if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1712     // Print asm string.
1713     OS << " ";
1714     const unsigned OpIdx = InlineAsm::MIOp_AsmString;
1715     LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
1716     unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
1717     getOperand(OpIdx).print(OS, MST, TypeToPrint, OpIdx, /*PrintDef=*/true, IsStandalone,
1718                             ShouldPrintRegisterTies, TiedOperandIdx, TRI,
1719                             IntrinsicInfo);
1720 
1721     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1722     unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1723     if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1724       OS << " [sideeffect]";
1725     if (ExtraInfo & InlineAsm::Extra_MayLoad)
1726       OS << " [mayload]";
1727     if (ExtraInfo & InlineAsm::Extra_MayStore)
1728       OS << " [maystore]";
1729     if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1730       OS << " [isconvergent]";
1731     if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1732       OS << " [alignstack]";
1733     if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1734       OS << " [attdialect]";
1735     if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1736       OS << " [inteldialect]";
1737 
1738     StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1739     FirstOp = false;
1740   }
1741 
1742   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1743     const MachineOperand &MO = getOperand(i);
1744 
1745     if (FirstOp) FirstOp = false; else OS << ",";
1746     OS << " ";
1747 
1748     if (isDebugValueLike() && MO.isMetadata()) {
1749       // Pretty print DBG_VALUE* instructions.
1750       auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1751       if (DIV && !DIV->getName().empty())
1752         OS << "!\"" << DIV->getName() << '\"';
1753       else {
1754         LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1755         unsigned TiedOperandIdx = getTiedOperandIdx(i);
1756         MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1757                  ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1758       }
1759     } else if (isDebugLabel() && MO.isMetadata()) {
1760       // Pretty print DBG_LABEL instructions.
1761       auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
1762       if (DIL && !DIL->getName().empty())
1763         OS << "\"" << DIL->getName() << '\"';
1764       else {
1765         LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1766         unsigned TiedOperandIdx = getTiedOperandIdx(i);
1767         MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1768                  ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1769       }
1770     } else if (i == AsmDescOp && MO.isImm()) {
1771       // Pretty print the inline asm operand descriptor.
1772       OS << '$' << AsmOpCount++;
1773       unsigned Flag = MO.getImm();
1774       const InlineAsm::Flag F(Flag);
1775       OS << ":[";
1776       OS << F.getKindName();
1777 
1778       unsigned RCID;
1779       if (!F.isImmKind() && !F.isMemKind() && F.hasRegClassConstraint(RCID)) {
1780         if (TRI) {
1781           OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1782         } else
1783           OS << ":RC" << RCID;
1784       }
1785 
1786       if (F.isMemKind()) {
1787         const InlineAsm::ConstraintCode MCID = F.getMemoryConstraintID();
1788         OS << ":" << InlineAsm::getMemConstraintName(MCID);
1789       }
1790 
1791       unsigned TiedTo;
1792       if (F.isUseOperandTiedToDef(TiedTo))
1793         OS << " tiedto:$" << TiedTo;
1794 
1795       OS << ']';
1796 
1797       // Compute the index of the next operand descriptor.
1798       AsmDescOp += 1 + F.getNumOperandRegisters();
1799     } else {
1800       LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
1801       unsigned TiedOperandIdx = getTiedOperandIdx(i);
1802       if (MO.isImm() && isOperandSubregIdx(i))
1803         MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
1804       else
1805         MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone,
1806                  ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
1807     }
1808   }
1809 
1810   // Print any optional symbols attached to this instruction as-if they were
1811   // operands.
1812   if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
1813     if (!FirstOp) {
1814       FirstOp = false;
1815       OS << ',';
1816     }
1817     OS << " pre-instr-symbol ";
1818     MachineOperand::printSymbol(OS, *PreInstrSymbol);
1819   }
1820   if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
1821     if (!FirstOp) {
1822       FirstOp = false;
1823       OS << ',';
1824     }
1825     OS << " post-instr-symbol ";
1826     MachineOperand::printSymbol(OS, *PostInstrSymbol);
1827   }
1828   if (MDNode *HeapAllocMarker = getHeapAllocMarker()) {
1829     if (!FirstOp) {
1830       FirstOp = false;
1831       OS << ',';
1832     }
1833     OS << " heap-alloc-marker ";
1834     HeapAllocMarker->printAsOperand(OS, MST);
1835   }
1836   if (MDNode *PCSections = getPCSections()) {
1837     if (!FirstOp) {
1838       FirstOp = false;
1839       OS << ',';
1840     }
1841     OS << " pcsections ";
1842     PCSections->printAsOperand(OS, MST);
1843   }
1844   if (uint32_t CFIType = getCFIType()) {
1845     if (!FirstOp)
1846       OS << ',';
1847     OS << " cfi-type " << CFIType;
1848   }
1849 
1850   if (DebugInstrNum) {
1851     if (!FirstOp)
1852       OS << ",";
1853     OS << " debug-instr-number " << DebugInstrNum;
1854   }
1855 
1856   if (!SkipDebugLoc) {
1857     if (const DebugLoc &DL = getDebugLoc()) {
1858       if (!FirstOp)
1859         OS << ',';
1860       OS << " debug-location ";
1861       DL->printAsOperand(OS, MST);
1862     }
1863   }
1864 
1865   if (!memoperands_empty()) {
1866     SmallVector<StringRef, 0> SSNs;
1867     const LLVMContext *Context = nullptr;
1868     std::unique_ptr<LLVMContext> CtxPtr;
1869     const MachineFrameInfo *MFI = nullptr;
1870     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
1871       MFI = &MF->getFrameInfo();
1872       Context = &MF->getFunction().getContext();
1873     } else {
1874       CtxPtr = std::make_unique<LLVMContext>();
1875       Context = CtxPtr.get();
1876     }
1877 
1878     OS << " :: ";
1879     bool NeedComma = false;
1880     for (const MachineMemOperand *Op : memoperands()) {
1881       if (NeedComma)
1882         OS << ", ";
1883       Op->print(OS, MST, SSNs, *Context, MFI, TII);
1884       NeedComma = true;
1885     }
1886   }
1887 
1888   if (SkipDebugLoc)
1889     return;
1890 
1891   bool HaveSemi = false;
1892 
1893   // Print debug location information.
1894   if (const DebugLoc &DL = getDebugLoc()) {
1895     if (!HaveSemi) {
1896       OS << ';';
1897       HaveSemi = true;
1898     }
1899     OS << ' ';
1900     DL.print(OS);
1901   }
1902 
1903   // Print extra comments for DEBUG_VALUE and friends if they are well-formed.
1904   if ((isNonListDebugValue() && getNumOperands() >= 4) ||
1905       (isDebugValueList() && getNumOperands() >= 2) ||
1906       (isDebugRef() && getNumOperands() >= 3)) {
1907     if (getDebugVariableOp().isMetadata()) {
1908       if (!HaveSemi) {
1909         OS << ";";
1910         HaveSemi = true;
1911       }
1912       auto *DV = getDebugVariable();
1913       OS << " line no:" << DV->getLine();
1914       if (isIndirectDebugValue())
1915         OS << " indirect";
1916     }
1917   }
1918   // TODO: DBG_LABEL
1919 
1920   if (AddNewLine)
1921     OS << '\n';
1922 }
1923 
1924 bool MachineInstr::addRegisterKilled(Register IncomingReg,
1925                                      const TargetRegisterInfo *RegInfo,
1926                                      bool AddIfNotFound) {
1927   bool isPhysReg = IncomingReg.isPhysical();
1928   bool hasAliases = isPhysReg &&
1929     MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1930   bool Found = false;
1931   SmallVector<unsigned,4> DeadOps;
1932   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1933     MachineOperand &MO = getOperand(i);
1934     if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1935       continue;
1936 
1937     // DEBUG_VALUE nodes do not contribute to code generation and should
1938     // always be ignored. Failure to do so may result in trying to modify
1939     // KILL flags on DEBUG_VALUE nodes.
1940     if (MO.isDebug())
1941       continue;
1942 
1943     Register Reg = MO.getReg();
1944     if (!Reg)
1945       continue;
1946 
1947     if (Reg == IncomingReg) {
1948       if (!Found) {
1949         if (MO.isKill())
1950           // The register is already marked kill.
1951           return true;
1952         if (isPhysReg && isRegTiedToDefOperand(i))
1953           // Two-address uses of physregs must not be marked kill.
1954           return true;
1955         MO.setIsKill();
1956         Found = true;
1957       }
1958     } else if (hasAliases && MO.isKill() && Reg.isPhysical()) {
1959       // A super-register kill already exists.
1960       if (RegInfo->isSuperRegister(IncomingReg, Reg))
1961         return true;
1962       if (RegInfo->isSubRegister(IncomingReg, Reg))
1963         DeadOps.push_back(i);
1964     }
1965   }
1966 
1967   // Trim unneeded kill operands.
1968   while (!DeadOps.empty()) {
1969     unsigned OpIdx = DeadOps.back();
1970     if (getOperand(OpIdx).isImplicit() &&
1971         (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
1972       removeOperand(OpIdx);
1973     else
1974       getOperand(OpIdx).setIsKill(false);
1975     DeadOps.pop_back();
1976   }
1977 
1978   // If not found, this means an alias of one of the operands is killed. Add a
1979   // new implicit operand if required.
1980   if (!Found && AddIfNotFound) {
1981     addOperand(MachineOperand::CreateReg(IncomingReg,
1982                                          false /*IsDef*/,
1983                                          true  /*IsImp*/,
1984                                          true  /*IsKill*/));
1985     return true;
1986   }
1987   return Found;
1988 }
1989 
1990 void MachineInstr::clearRegisterKills(Register Reg,
1991                                       const TargetRegisterInfo *RegInfo) {
1992   if (!Reg.isPhysical())
1993     RegInfo = nullptr;
1994   for (MachineOperand &MO : operands()) {
1995     if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1996       continue;
1997     Register OpReg = MO.getReg();
1998     if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
1999       MO.setIsKill(false);
2000   }
2001 }
2002 
2003 bool MachineInstr::addRegisterDead(Register Reg,
2004                                    const TargetRegisterInfo *RegInfo,
2005                                    bool AddIfNotFound) {
2006   bool isPhysReg = Reg.isPhysical();
2007   bool hasAliases = isPhysReg &&
2008     MCRegAliasIterator(Reg, RegInfo, false).isValid();
2009   bool Found = false;
2010   SmallVector<unsigned,4> DeadOps;
2011   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2012     MachineOperand &MO = getOperand(i);
2013     if (!MO.isReg() || !MO.isDef())
2014       continue;
2015     Register MOReg = MO.getReg();
2016     if (!MOReg)
2017       continue;
2018 
2019     if (MOReg == Reg) {
2020       MO.setIsDead();
2021       Found = true;
2022     } else if (hasAliases && MO.isDead() && MOReg.isPhysical()) {
2023       // There exists a super-register that's marked dead.
2024       if (RegInfo->isSuperRegister(Reg, MOReg))
2025         return true;
2026       if (RegInfo->isSubRegister(Reg, MOReg))
2027         DeadOps.push_back(i);
2028     }
2029   }
2030 
2031   // Trim unneeded dead operands.
2032   while (!DeadOps.empty()) {
2033     unsigned OpIdx = DeadOps.back();
2034     if (getOperand(OpIdx).isImplicit() &&
2035         (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
2036       removeOperand(OpIdx);
2037     else
2038       getOperand(OpIdx).setIsDead(false);
2039     DeadOps.pop_back();
2040   }
2041 
2042   // If not found, this means an alias of one of the operands is dead. Add a
2043   // new implicit operand if required.
2044   if (Found || !AddIfNotFound)
2045     return Found;
2046 
2047   addOperand(MachineOperand::CreateReg(Reg,
2048                                        true  /*IsDef*/,
2049                                        true  /*IsImp*/,
2050                                        false /*IsKill*/,
2051                                        true  /*IsDead*/));
2052   return true;
2053 }
2054 
2055 void MachineInstr::clearRegisterDeads(Register Reg) {
2056   for (MachineOperand &MO : operands()) {
2057     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2058       continue;
2059     MO.setIsDead(false);
2060   }
2061 }
2062 
2063 void MachineInstr::setRegisterDefReadUndef(Register Reg, bool IsUndef) {
2064   for (MachineOperand &MO : operands()) {
2065     if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2066       continue;
2067     MO.setIsUndef(IsUndef);
2068   }
2069 }
2070 
2071 void MachineInstr::addRegisterDefined(Register Reg,
2072                                       const TargetRegisterInfo *RegInfo) {
2073   if (Reg.isPhysical()) {
2074     MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo);
2075     if (MO)
2076       return;
2077   } else {
2078     for (const MachineOperand &MO : operands()) {
2079       if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2080           MO.getSubReg() == 0)
2081         return;
2082     }
2083   }
2084   addOperand(MachineOperand::CreateReg(Reg,
2085                                        true  /*IsDef*/,
2086                                        true  /*IsImp*/));
2087 }
2088 
2089 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
2090                                          const TargetRegisterInfo &TRI) {
2091   bool HasRegMask = false;
2092   for (MachineOperand &MO : operands()) {
2093     if (MO.isRegMask()) {
2094       HasRegMask = true;
2095       continue;
2096     }
2097     if (!MO.isReg() || !MO.isDef()) continue;
2098     Register Reg = MO.getReg();
2099     if (!Reg.isPhysical())
2100       continue;
2101     // If there are no uses, including partial uses, the def is dead.
2102     if (llvm::none_of(UsedRegs,
2103                       [&](MCRegister Use) { return TRI.regsOverlap(Use, Reg); }))
2104       MO.setIsDead();
2105   }
2106 
2107   // This is a call with a register mask operand.
2108   // Mask clobbers are always dead, so add defs for the non-dead defines.
2109   if (HasRegMask)
2110     for (const Register &UsedReg : UsedRegs)
2111       addRegisterDefined(UsedReg, &TRI);
2112 }
2113 
2114 unsigned
2115 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2116   // Build up a buffer of hash code components.
2117   SmallVector<size_t, 16> HashComponents;
2118   HashComponents.reserve(MI->getNumOperands() + 1);
2119   HashComponents.push_back(MI->getOpcode());
2120   for (const MachineOperand &MO : MI->operands()) {
2121     if (MO.isReg() && MO.isDef() && MO.getReg().isVirtual())
2122       continue;  // Skip virtual register defs.
2123 
2124     HashComponents.push_back(hash_value(MO));
2125   }
2126   return hash_combine_range(HashComponents.begin(), HashComponents.end());
2127 }
2128 
2129 void MachineInstr::emitError(StringRef Msg) const {
2130   // Find the source location cookie.
2131   uint64_t LocCookie = 0;
2132   const MDNode *LocMD = nullptr;
2133   for (unsigned i = getNumOperands(); i != 0; --i) {
2134     if (getOperand(i-1).isMetadata() &&
2135         (LocMD = getOperand(i-1).getMetadata()) &&
2136         LocMD->getNumOperands() != 0) {
2137       if (const ConstantInt *CI =
2138               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2139         LocCookie = CI->getZExtValue();
2140         break;
2141       }
2142     }
2143   }
2144 
2145   if (const MachineBasicBlock *MBB = getParent())
2146     if (const MachineFunction *MF = MBB->getParent())
2147       return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2148   report_fatal_error(Msg);
2149 }
2150 
2151 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2152                                   const MCInstrDesc &MCID, bool IsIndirect,
2153                                   Register Reg, const MDNode *Variable,
2154                                   const MDNode *Expr) {
2155   assert(isa<DILocalVariable>(Variable) && "not a variable");
2156   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2157   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2158          "Expected inlined-at fields to agree");
2159   auto MIB = BuildMI(MF, DL, MCID).addReg(Reg);
2160   if (IsIndirect)
2161     MIB.addImm(0U);
2162   else
2163     MIB.addReg(0U);
2164   return MIB.addMetadata(Variable).addMetadata(Expr);
2165 }
2166 
2167 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2168                                   const MCInstrDesc &MCID, bool IsIndirect,
2169                                   ArrayRef<MachineOperand> DebugOps,
2170                                   const MDNode *Variable, const MDNode *Expr) {
2171   assert(isa<DILocalVariable>(Variable) && "not a variable");
2172   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2173   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2174          "Expected inlined-at fields to agree");
2175   if (MCID.Opcode == TargetOpcode::DBG_VALUE) {
2176     assert(DebugOps.size() == 1 &&
2177            "DBG_VALUE must contain exactly one debug operand");
2178     MachineOperand DebugOp = DebugOps[0];
2179     if (DebugOp.isReg())
2180       return BuildMI(MF, DL, MCID, IsIndirect, DebugOp.getReg(), Variable,
2181                      Expr);
2182 
2183     auto MIB = BuildMI(MF, DL, MCID).add(DebugOp);
2184     if (IsIndirect)
2185       MIB.addImm(0U);
2186     else
2187       MIB.addReg(0U);
2188     return MIB.addMetadata(Variable).addMetadata(Expr);
2189   }
2190 
2191   auto MIB = BuildMI(MF, DL, MCID);
2192   MIB.addMetadata(Variable).addMetadata(Expr);
2193   for (const MachineOperand &DebugOp : DebugOps)
2194     if (DebugOp.isReg())
2195       MIB.addReg(DebugOp.getReg());
2196     else
2197       MIB.add(DebugOp);
2198   return MIB;
2199 }
2200 
2201 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2202                                   MachineBasicBlock::iterator I,
2203                                   const DebugLoc &DL, const MCInstrDesc &MCID,
2204                                   bool IsIndirect, Register Reg,
2205                                   const MDNode *Variable, const MDNode *Expr) {
2206   MachineFunction &MF = *BB.getParent();
2207   MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
2208   BB.insert(I, MI);
2209   return MachineInstrBuilder(MF, MI);
2210 }
2211 
2212 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2213                                   MachineBasicBlock::iterator I,
2214                                   const DebugLoc &DL, const MCInstrDesc &MCID,
2215                                   bool IsIndirect,
2216                                   ArrayRef<MachineOperand> DebugOps,
2217                                   const MDNode *Variable, const MDNode *Expr) {
2218   MachineFunction &MF = *BB.getParent();
2219   MachineInstr *MI =
2220       BuildMI(MF, DL, MCID, IsIndirect, DebugOps, Variable, Expr);
2221   BB.insert(I, MI);
2222   return MachineInstrBuilder(MF, *MI);
2223 }
2224 
2225 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
2226 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
2227 static const DIExpression *
2228 computeExprForSpill(const MachineInstr &MI,
2229                     SmallVectorImpl<const MachineOperand *> &SpilledOperands) {
2230   assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
2231          "Expected inlined-at fields to agree");
2232 
2233   const DIExpression *Expr = MI.getDebugExpression();
2234   if (MI.isIndirectDebugValue()) {
2235     assert(MI.getDebugOffset().getImm() == 0 &&
2236            "DBG_VALUE with nonzero offset");
2237     Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
2238   } else if (MI.isDebugValueList()) {
2239     // We will replace the spilled register with a frame index, so
2240     // immediately deref all references to the spilled register.
2241     std::array<uint64_t, 1> Ops{{dwarf::DW_OP_deref}};
2242     for (const MachineOperand *Op : SpilledOperands) {
2243       unsigned OpIdx = MI.getDebugOperandIndex(Op);
2244       Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx);
2245     }
2246   }
2247   return Expr;
2248 }
2249 static const DIExpression *computeExprForSpill(const MachineInstr &MI,
2250                                                Register SpillReg) {
2251   assert(MI.hasDebugOperandForReg(SpillReg) && "Spill Reg is not used in MI.");
2252   SmallVector<const MachineOperand *> SpillOperands;
2253   for (const MachineOperand &Op : MI.getDebugOperandsForReg(SpillReg))
2254     SpillOperands.push_back(&Op);
2255   return computeExprForSpill(MI, SpillOperands);
2256 }
2257 
2258 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2259                                           MachineBasicBlock::iterator I,
2260                                           const MachineInstr &Orig,
2261                                           int FrameIndex, Register SpillReg) {
2262   assert(!Orig.isDebugRef() &&
2263          "DBG_INSTR_REF should not reference a virtual register.");
2264   const DIExpression *Expr = computeExprForSpill(Orig, SpillReg);
2265   MachineInstrBuilder NewMI =
2266       BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc());
2267   // Non-Variadic Operands: Location, Offset, Variable, Expression
2268   // Variadic Operands:     Variable, Expression, Locations...
2269   if (Orig.isNonListDebugValue())
2270     NewMI.addFrameIndex(FrameIndex).addImm(0U);
2271   NewMI.addMetadata(Orig.getDebugVariable()).addMetadata(Expr);
2272   if (Orig.isDebugValueList()) {
2273     for (const MachineOperand &Op : Orig.debug_operands())
2274       if (Op.isReg() && Op.getReg() == SpillReg)
2275         NewMI.addFrameIndex(FrameIndex);
2276       else
2277         NewMI.add(MachineOperand(Op));
2278   }
2279   return NewMI;
2280 }
2281 MachineInstr *llvm::buildDbgValueForSpill(
2282     MachineBasicBlock &BB, MachineBasicBlock::iterator I,
2283     const MachineInstr &Orig, int FrameIndex,
2284     SmallVectorImpl<const MachineOperand *> &SpilledOperands) {
2285   const DIExpression *Expr = computeExprForSpill(Orig, SpilledOperands);
2286   MachineInstrBuilder NewMI =
2287       BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc());
2288   // Non-Variadic Operands: Location, Offset, Variable, Expression
2289   // Variadic Operands:     Variable, Expression, Locations...
2290   if (Orig.isNonListDebugValue())
2291     NewMI.addFrameIndex(FrameIndex).addImm(0U);
2292   NewMI.addMetadata(Orig.getDebugVariable()).addMetadata(Expr);
2293   if (Orig.isDebugValueList()) {
2294     for (const MachineOperand &Op : Orig.debug_operands())
2295       if (is_contained(SpilledOperands, &Op))
2296         NewMI.addFrameIndex(FrameIndex);
2297       else
2298         NewMI.add(MachineOperand(Op));
2299   }
2300   return NewMI;
2301 }
2302 
2303 void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex,
2304                                   Register Reg) {
2305   const DIExpression *Expr = computeExprForSpill(Orig, Reg);
2306   if (Orig.isNonListDebugValue())
2307     Orig.getDebugOffset().ChangeToImmediate(0U);
2308   for (MachineOperand &Op : Orig.getDebugOperandsForReg(Reg))
2309     Op.ChangeToFrameIndex(FrameIndex);
2310   Orig.getDebugExpressionOp().setMetadata(Expr);
2311 }
2312 
2313 void MachineInstr::collectDebugValues(
2314                                 SmallVectorImpl<MachineInstr *> &DbgValues) {
2315   MachineInstr &MI = *this;
2316   if (!MI.getOperand(0).isReg())
2317     return;
2318 
2319   MachineBasicBlock::iterator DI = MI; ++DI;
2320   for (MachineBasicBlock::iterator DE = MI.getParent()->end();
2321        DI != DE; ++DI) {
2322     if (!DI->isDebugValue())
2323       return;
2324     if (DI->hasDebugOperandForReg(MI.getOperand(0).getReg()))
2325       DbgValues.push_back(&*DI);
2326   }
2327 }
2328 
2329 void MachineInstr::changeDebugValuesDefReg(Register Reg) {
2330   // Collect matching debug values.
2331   SmallVector<MachineInstr *, 2> DbgValues;
2332 
2333   if (!getOperand(0).isReg())
2334     return;
2335 
2336   Register DefReg = getOperand(0).getReg();
2337   auto *MRI = getRegInfo();
2338   for (auto &MO : MRI->use_operands(DefReg)) {
2339     auto *DI = MO.getParent();
2340     if (!DI->isDebugValue())
2341       continue;
2342     if (DI->hasDebugOperandForReg(DefReg)) {
2343       DbgValues.push_back(DI);
2344     }
2345   }
2346 
2347   // Propagate Reg to debug value instructions.
2348   for (auto *DBI : DbgValues)
2349     for (MachineOperand &Op : DBI->getDebugOperandsForReg(DefReg))
2350       Op.setReg(Reg);
2351 }
2352 
2353 using MMOList = SmallVector<const MachineMemOperand *, 2>;
2354 
2355 static unsigned getSpillSlotSize(const MMOList &Accesses,
2356                                  const MachineFrameInfo &MFI) {
2357   unsigned Size = 0;
2358   for (const auto *A : Accesses)
2359     if (MFI.isSpillSlotObjectIndex(
2360             cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
2361                 ->getFrameIndex()))
2362       Size += A->getSize();
2363   return Size;
2364 }
2365 
2366 std::optional<unsigned>
2367 MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
2368   int FI;
2369   if (TII->isStoreToStackSlotPostFE(*this, FI)) {
2370     const MachineFrameInfo &MFI = getMF()->getFrameInfo();
2371     if (MFI.isSpillSlotObjectIndex(FI))
2372       return (*memoperands_begin())->getSize();
2373   }
2374   return std::nullopt;
2375 }
2376 
2377 std::optional<unsigned>
2378 MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
2379   MMOList Accesses;
2380   if (TII->hasStoreToStackSlot(*this, Accesses))
2381     return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
2382   return std::nullopt;
2383 }
2384 
2385 std::optional<unsigned>
2386 MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
2387   int FI;
2388   if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
2389     const MachineFrameInfo &MFI = getMF()->getFrameInfo();
2390     if (MFI.isSpillSlotObjectIndex(FI))
2391       return (*memoperands_begin())->getSize();
2392   }
2393   return std::nullopt;
2394 }
2395 
2396 std::optional<unsigned>
2397 MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
2398   MMOList Accesses;
2399   if (TII->hasLoadFromStackSlot(*this, Accesses))
2400     return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
2401   return std::nullopt;
2402 }
2403 
2404 unsigned MachineInstr::getDebugInstrNum() {
2405   if (DebugInstrNum == 0)
2406     DebugInstrNum = getParent()->getParent()->getNewDebugInstrNum();
2407   return DebugInstrNum;
2408 }
2409 
2410 unsigned MachineInstr::getDebugInstrNum(MachineFunction &MF) {
2411   if (DebugInstrNum == 0)
2412     DebugInstrNum = MF.getNewDebugInstrNum();
2413   return DebugInstrNum;
2414 }
2415 
2416 std::tuple<LLT, LLT> MachineInstr::getFirst2LLTs() const {
2417   return std::tuple(getRegInfo()->getType(getOperand(0).getReg()),
2418                     getRegInfo()->getType(getOperand(1).getReg()));
2419 }
2420 
2421 std::tuple<LLT, LLT, LLT> MachineInstr::getFirst3LLTs() const {
2422   return std::tuple(getRegInfo()->getType(getOperand(0).getReg()),
2423                     getRegInfo()->getType(getOperand(1).getReg()),
2424                     getRegInfo()->getType(getOperand(2).getReg()));
2425 }
2426 
2427 std::tuple<LLT, LLT, LLT, LLT> MachineInstr::getFirst4LLTs() const {
2428   return std::tuple(getRegInfo()->getType(getOperand(0).getReg()),
2429                     getRegInfo()->getType(getOperand(1).getReg()),
2430                     getRegInfo()->getType(getOperand(2).getReg()),
2431                     getRegInfo()->getType(getOperand(3).getReg()));
2432 }
2433 
2434 std::tuple<LLT, LLT, LLT, LLT, LLT> MachineInstr::getFirst5LLTs() const {
2435   return std::tuple(getRegInfo()->getType(getOperand(0).getReg()),
2436                     getRegInfo()->getType(getOperand(1).getReg()),
2437                     getRegInfo()->getType(getOperand(2).getReg()),
2438                     getRegInfo()->getType(getOperand(3).getReg()),
2439                     getRegInfo()->getType(getOperand(4).getReg()));
2440 }
2441 
2442 std::tuple<Register, LLT, Register, LLT>
2443 MachineInstr::getFirst2RegLLTs() const {
2444   Register Reg0 = getOperand(0).getReg();
2445   Register Reg1 = getOperand(1).getReg();
2446   return std::tuple(Reg0, getRegInfo()->getType(Reg0), Reg1,
2447                     getRegInfo()->getType(Reg1));
2448 }
2449 
2450 std::tuple<Register, LLT, Register, LLT, Register, LLT>
2451 MachineInstr::getFirst3RegLLTs() const {
2452   Register Reg0 = getOperand(0).getReg();
2453   Register Reg1 = getOperand(1).getReg();
2454   Register Reg2 = getOperand(2).getReg();
2455   return std::tuple(Reg0, getRegInfo()->getType(Reg0), Reg1,
2456                     getRegInfo()->getType(Reg1), Reg2,
2457                     getRegInfo()->getType(Reg2));
2458 }
2459 
2460 std::tuple<Register, LLT, Register, LLT, Register, LLT, Register, LLT>
2461 MachineInstr::getFirst4RegLLTs() const {
2462   Register Reg0 = getOperand(0).getReg();
2463   Register Reg1 = getOperand(1).getReg();
2464   Register Reg2 = getOperand(2).getReg();
2465   Register Reg3 = getOperand(3).getReg();
2466   return std::tuple(
2467       Reg0, getRegInfo()->getType(Reg0), Reg1, getRegInfo()->getType(Reg1),
2468       Reg2, getRegInfo()->getType(Reg2), Reg3, getRegInfo()->getType(Reg3));
2469 }
2470 
2471 std::tuple<Register, LLT, Register, LLT, Register, LLT, Register, LLT, Register,
2472            LLT>
2473 MachineInstr::getFirst5RegLLTs() const {
2474   Register Reg0 = getOperand(0).getReg();
2475   Register Reg1 = getOperand(1).getReg();
2476   Register Reg2 = getOperand(2).getReg();
2477   Register Reg3 = getOperand(3).getReg();
2478   Register Reg4 = getOperand(4).getReg();
2479   return std::tuple(
2480       Reg0, getRegInfo()->getType(Reg0), Reg1, getRegInfo()->getType(Reg1),
2481       Reg2, getRegInfo()->getType(Reg2), Reg3, getRegInfo()->getType(Reg3),
2482       Reg4, getRegInfo()->getType(Reg4));
2483 }
2484 
2485 void MachineInstr::insert(mop_iterator InsertBefore,
2486                           ArrayRef<MachineOperand> Ops) {
2487   assert(InsertBefore != nullptr && "invalid iterator");
2488   assert(InsertBefore->getParent() == this &&
2489          "iterator points to operand of other inst");
2490   if (Ops.empty())
2491     return;
2492 
2493   // Do one pass to untie operands.
2494   SmallDenseMap<unsigned, unsigned> TiedOpIndices;
2495   for (const MachineOperand &MO : operands()) {
2496     if (MO.isReg() && MO.isTied()) {
2497       unsigned OpNo = getOperandNo(&MO);
2498       unsigned TiedTo = findTiedOperandIdx(OpNo);
2499       TiedOpIndices[OpNo] = TiedTo;
2500       untieRegOperand(OpNo);
2501     }
2502   }
2503 
2504   unsigned OpIdx = getOperandNo(InsertBefore);
2505   unsigned NumOperands = getNumOperands();
2506   unsigned OpsToMove = NumOperands - OpIdx;
2507 
2508   SmallVector<MachineOperand> MovingOps;
2509   MovingOps.reserve(OpsToMove);
2510 
2511   for (unsigned I = 0; I < OpsToMove; ++I) {
2512     MovingOps.emplace_back(getOperand(OpIdx));
2513     removeOperand(OpIdx);
2514   }
2515   for (const MachineOperand &MO : Ops)
2516     addOperand(MO);
2517   for (const MachineOperand &OpMoved : MovingOps)
2518     addOperand(OpMoved);
2519 
2520   // Re-tie operands.
2521   for (auto [Tie1, Tie2] : TiedOpIndices) {
2522     if (Tie1 >= OpIdx)
2523       Tie1 += Ops.size();
2524     if (Tie2 >= OpIdx)
2525       Tie2 += Ops.size();
2526     tieOperands(Tie1, Tie2);
2527   }
2528 }
2529