1 //===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- C++ -*-===//
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 // This file contains the declaration of the MachineInstr class, which is the
10 // basic representation for all target dependent machine instructions used by
11 // the back end.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
16 #define LLVM_CODEGEN_MACHINEINSTR_H
17 
18 #include "llvm/ADT/DenseMapInfo.h"
19 #include "llvm/ADT/PointerSumType.h"
20 #include "llvm/ADT/ilist.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/CodeGen/MachineMemOperand.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/TargetOpcodes.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/ArrayRecycler.h"
31 #include "llvm/Support/TrailingObjects.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstdint>
35 #include <utility>
36 
37 namespace llvm {
38 
39 class AAResults;
40 template <typename T> class ArrayRef;
41 class DIExpression;
42 class DILocalVariable;
43 class MachineBasicBlock;
44 class MachineFunction;
45 class MachineRegisterInfo;
46 class ModuleSlotTracker;
47 class raw_ostream;
48 template <typename T> class SmallVectorImpl;
49 class SmallBitVector;
50 class StringRef;
51 class TargetInstrInfo;
52 class TargetRegisterClass;
53 class TargetRegisterInfo;
54 
55 //===----------------------------------------------------------------------===//
56 /// Representation of each machine instruction.
57 ///
58 /// This class isn't a POD type, but it must have a trivial destructor. When a
59 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
60 /// without having their destructor called.
61 ///
62 class MachineInstr
63     : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
64                                     ilist_sentinel_tracking<true>> {
65 public:
66   using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator;
67 
68   /// Flags to specify different kinds of comments to output in
69   /// assembly code.  These flags carry semantic information not
70   /// otherwise easily derivable from the IR text.
71   ///
72   enum CommentFlag {
73     ReloadReuse = 0x1,    // higher bits are reserved for target dep comments.
74     NoSchedComment = 0x2,
75     TAsmComments = 0x4    // Target Asm comments should start from this value.
76   };
77 
78   enum MIFlag {
79     NoFlags      = 0,
80     FrameSetup   = 1 << 0,              // Instruction is used as a part of
81                                         // function frame setup code.
82     FrameDestroy = 1 << 1,              // Instruction is used as a part of
83                                         // function frame destruction code.
84     BundledPred  = 1 << 2,              // Instruction has bundled predecessors.
85     BundledSucc  = 1 << 3,              // Instruction has bundled successors.
86     FmNoNans     = 1 << 4,              // Instruction does not support Fast
87                                         // math nan values.
88     FmNoInfs     = 1 << 5,              // Instruction does not support Fast
89                                         // math infinity values.
90     FmNsz        = 1 << 6,              // Instruction is not required to retain
91                                         // signed zero values.
92     FmArcp       = 1 << 7,              // Instruction supports Fast math
93                                         // reciprocal approximations.
94     FmContract   = 1 << 8,              // Instruction supports Fast math
95                                         // contraction operations like fma.
96     FmAfn        = 1 << 9,              // Instruction may map to Fast math
97                                         // instrinsic approximation.
98     FmReassoc    = 1 << 10,             // Instruction supports Fast math
99                                         // reassociation of operand order.
100     NoUWrap      = 1 << 11,             // Instruction supports binary operator
101                                         // no unsigned wrap.
102     NoSWrap      = 1 << 12,             // Instruction supports binary operator
103                                         // no signed wrap.
104     IsExact      = 1 << 13,             // Instruction supports division is
105                                         // known to be exact.
106     NoFPExcept   = 1 << 14,             // Instruction does not raise
107                                         // floatint-point exceptions.
108     NoMerge      = 1 << 15,             // Passes that drop source location info
109                                         // (e.g. branch folding) should skip
110                                         // this instruction.
111   };
112 
113 private:
114   const MCInstrDesc *MCID;              // Instruction descriptor.
115   MachineBasicBlock *Parent = nullptr;  // Pointer to the owning basic block.
116 
117   // Operands are allocated by an ArrayRecycler.
118   MachineOperand *Operands = nullptr;   // Pointer to the first operand.
119   unsigned NumOperands = 0;             // Number of operands on instruction.
120 
121   uint16_t Flags = 0;                   // Various bits of additional
122                                         // information about machine
123                                         // instruction.
124 
125   uint8_t AsmPrinterFlags = 0;          // Various bits of information used by
126                                         // the AsmPrinter to emit helpful
127                                         // comments.  This is *not* semantic
128                                         // information.  Do not use this for
129                                         // anything other than to convey comment
130                                         // information to AsmPrinter.
131 
132   // OperandCapacity has uint8_t size, so it should be next to AsmPrinterFlags
133   // to properly pack.
134   using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
135   OperandCapacity CapOperands;          // Capacity of the Operands array.
136 
137   /// Internal implementation detail class that provides out-of-line storage for
138   /// extra info used by the machine instruction when this info cannot be stored
139   /// in-line within the instruction itself.
140   ///
141   /// This has to be defined eagerly due to the implementation constraints of
142   /// `PointerSumType` where it is used.
143   class ExtraInfo final
144       : TrailingObjects<ExtraInfo, MachineMemOperand *, MCSymbol *, MDNode *> {
145   public:
146     static ExtraInfo *create(BumpPtrAllocator &Allocator,
147                              ArrayRef<MachineMemOperand *> MMOs,
148                              MCSymbol *PreInstrSymbol = nullptr,
149                              MCSymbol *PostInstrSymbol = nullptr,
150                              MDNode *HeapAllocMarker = nullptr) {
151       bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
152       bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
153       bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
154       auto *Result = new (Allocator.Allocate(
155           totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *>(
156               MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol,
157               HasHeapAllocMarker),
158           alignof(ExtraInfo)))
159           ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol,
160                     HasHeapAllocMarker);
161 
162       // Copy the actual data into the trailing objects.
163       std::copy(MMOs.begin(), MMOs.end(),
164                 Result->getTrailingObjects<MachineMemOperand *>());
165 
166       if (HasPreInstrSymbol)
167         Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol;
168       if (HasPostInstrSymbol)
169         Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] =
170             PostInstrSymbol;
171       if (HasHeapAllocMarker)
172         Result->getTrailingObjects<MDNode *>()[0] = HeapAllocMarker;
173 
174       return Result;
175     }
176 
177     ArrayRef<MachineMemOperand *> getMMOs() const {
178       return makeArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs);
179     }
180 
181     MCSymbol *getPreInstrSymbol() const {
182       return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr;
183     }
184 
185     MCSymbol *getPostInstrSymbol() const {
186       return HasPostInstrSymbol
187                  ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol]
188                  : nullptr;
189     }
190 
191     MDNode *getHeapAllocMarker() const {
192       return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr;
193     }
194 
195   private:
196     friend TrailingObjects;
197 
198     // Description of the extra info, used to interpret the actual optional
199     // data appended.
200     //
201     // Note that this is not terribly space optimized. This leaves a great deal
202     // of flexibility to fit more in here later.
203     const int NumMMOs;
204     const bool HasPreInstrSymbol;
205     const bool HasPostInstrSymbol;
206     const bool HasHeapAllocMarker;
207 
208     // Implement the `TrailingObjects` internal API.
209     size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const {
210       return NumMMOs;
211     }
212     size_t numTrailingObjects(OverloadToken<MCSymbol *>) const {
213       return HasPreInstrSymbol + HasPostInstrSymbol;
214     }
215     size_t numTrailingObjects(OverloadToken<MDNode *>) const {
216       return HasHeapAllocMarker;
217     }
218 
219     // Just a boring constructor to allow us to initialize the sizes. Always use
220     // the `create` routine above.
221     ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol,
222               bool HasHeapAllocMarker)
223         : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol),
224           HasPostInstrSymbol(HasPostInstrSymbol),
225           HasHeapAllocMarker(HasHeapAllocMarker) {}
226   };
227 
228   /// Enumeration of the kinds of inline extra info available. It is important
229   /// that the `MachineMemOperand` inline kind has a tag value of zero to make
230   /// it accessible as an `ArrayRef`.
231   enum ExtraInfoInlineKinds {
232     EIIK_MMO = 0,
233     EIIK_PreInstrSymbol,
234     EIIK_PostInstrSymbol,
235     EIIK_OutOfLine
236   };
237 
238   // We store extra information about the instruction here. The common case is
239   // expected to be nothing or a single pointer (typically a MMO or a symbol).
240   // We work to optimize this common case by storing it inline here rather than
241   // requiring a separate allocation, but we fall back to an allocation when
242   // multiple pointers are needed.
243   PointerSumType<ExtraInfoInlineKinds,
244                  PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>,
245                  PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>,
246                  PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>,
247                  PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>>
248       Info;
249 
250   DebugLoc debugLoc;                    // Source line information.
251 
252   // Intrusive list support
253   friend struct ilist_traits<MachineInstr>;
254   friend struct ilist_callback_traits<MachineBasicBlock>;
255   void setParent(MachineBasicBlock *P) { Parent = P; }
256 
257   /// This constructor creates a copy of the given
258   /// MachineInstr in the given MachineFunction.
259   MachineInstr(MachineFunction &, const MachineInstr &);
260 
261   /// This constructor create a MachineInstr and add the implicit operands.
262   /// It reserves space for number of operands specified by
263   /// MCInstrDesc.  An explicit DebugLoc is supplied.
264   MachineInstr(MachineFunction &, const MCInstrDesc &tid, DebugLoc dl,
265                bool NoImp = false);
266 
267   // MachineInstrs are pool-allocated and owned by MachineFunction.
268   friend class MachineFunction;
269 
270   void
271   dumprImpl(const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
272             SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const;
273 
274 public:
275   MachineInstr(const MachineInstr &) = delete;
276   MachineInstr &operator=(const MachineInstr &) = delete;
277   // Use MachineFunction::DeleteMachineInstr() instead.
278   ~MachineInstr() = delete;
279 
280   const MachineBasicBlock* getParent() const { return Parent; }
281   MachineBasicBlock* getParent() { return Parent; }
282 
283   /// Return the function that contains the basic block that this instruction
284   /// belongs to.
285   ///
286   /// Note: this is undefined behaviour if the instruction does not have a
287   /// parent.
288   const MachineFunction *getMF() const;
289   MachineFunction *getMF() {
290     return const_cast<MachineFunction *>(
291         static_cast<const MachineInstr *>(this)->getMF());
292   }
293 
294   /// Return the asm printer flags bitvector.
295   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
296 
297   /// Clear the AsmPrinter bitvector.
298   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
299 
300   /// Return whether an AsmPrinter flag is set.
301   bool getAsmPrinterFlag(CommentFlag Flag) const {
302     return AsmPrinterFlags & Flag;
303   }
304 
305   /// Set a flag for the AsmPrinter.
306   void setAsmPrinterFlag(uint8_t Flag) {
307     AsmPrinterFlags |= Flag;
308   }
309 
310   /// Clear specific AsmPrinter flags.
311   void clearAsmPrinterFlag(CommentFlag Flag) {
312     AsmPrinterFlags &= ~Flag;
313   }
314 
315   /// Return the MI flags bitvector.
316   uint16_t getFlags() const {
317     return Flags;
318   }
319 
320   /// Return whether an MI flag is set.
321   bool getFlag(MIFlag Flag) const {
322     return Flags & Flag;
323   }
324 
325   /// Set a MI flag.
326   void setFlag(MIFlag Flag) {
327     Flags |= (uint16_t)Flag;
328   }
329 
330   void setFlags(unsigned flags) {
331     // Filter out the automatically maintained flags.
332     unsigned Mask = BundledPred | BundledSucc;
333     Flags = (Flags & Mask) | (flags & ~Mask);
334   }
335 
336   /// clearFlag - Clear a MI flag.
337   void clearFlag(MIFlag Flag) {
338     Flags &= ~((uint16_t)Flag);
339   }
340 
341   /// Return true if MI is in a bundle (but not the first MI in a bundle).
342   ///
343   /// A bundle looks like this before it's finalized:
344   ///   ----------------
345   ///   |      MI      |
346   ///   ----------------
347   ///          |
348   ///   ----------------
349   ///   |      MI    * |
350   ///   ----------------
351   ///          |
352   ///   ----------------
353   ///   |      MI    * |
354   ///   ----------------
355   /// In this case, the first MI starts a bundle but is not inside a bundle, the
356   /// next 2 MIs are considered "inside" the bundle.
357   ///
358   /// After a bundle is finalized, it looks like this:
359   ///   ----------------
360   ///   |    Bundle    |
361   ///   ----------------
362   ///          |
363   ///   ----------------
364   ///   |      MI    * |
365   ///   ----------------
366   ///          |
367   ///   ----------------
368   ///   |      MI    * |
369   ///   ----------------
370   ///          |
371   ///   ----------------
372   ///   |      MI    * |
373   ///   ----------------
374   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
375   /// a bundle, but the next three MIs are.
376   bool isInsideBundle() const {
377     return getFlag(BundledPred);
378   }
379 
380   /// Return true if this instruction part of a bundle. This is true
381   /// if either itself or its following instruction is marked "InsideBundle".
382   bool isBundled() const {
383     return isBundledWithPred() || isBundledWithSucc();
384   }
385 
386   /// Return true if this instruction is part of a bundle, and it is not the
387   /// first instruction in the bundle.
388   bool isBundledWithPred() const { return getFlag(BundledPred); }
389 
390   /// Return true if this instruction is part of a bundle, and it is not the
391   /// last instruction in the bundle.
392   bool isBundledWithSucc() const { return getFlag(BundledSucc); }
393 
394   /// Bundle this instruction with its predecessor. This can be an unbundled
395   /// instruction, or it can be the first instruction in a bundle.
396   void bundleWithPred();
397 
398   /// Bundle this instruction with its successor. This can be an unbundled
399   /// instruction, or it can be the last instruction in a bundle.
400   void bundleWithSucc();
401 
402   /// Break bundle above this instruction.
403   void unbundleFromPred();
404 
405   /// Break bundle below this instruction.
406   void unbundleFromSucc();
407 
408   /// Returns the debug location id of this MachineInstr.
409   const DebugLoc &getDebugLoc() const { return debugLoc; }
410 
411   /// Return the operand containing the offset to be used if this DBG_VALUE
412   /// instruction is indirect; will be an invalid register if this value is
413   /// not indirect, and an immediate with value 0 otherwise.
414   const MachineOperand &getDebugOffset() const {
415     assert(isDebugValue() && "not a DBG_VALUE");
416     return getOperand(1);
417   }
418   MachineOperand &getDebugOffset() {
419     assert(isDebugValue() && "not a DBG_VALUE");
420     return getOperand(1);
421   }
422 
423   /// Return the operand for the debug variable referenced by
424   /// this DBG_VALUE instruction.
425   const MachineOperand &getDebugVariableOp() const;
426   MachineOperand &getDebugVariableOp();
427 
428   /// Return the debug variable referenced by
429   /// this DBG_VALUE instruction.
430   const DILocalVariable *getDebugVariable() const;
431 
432   /// Return the operand for the complex address expression referenced by
433   /// this DBG_VALUE instruction.
434   MachineOperand &getDebugExpressionOp();
435 
436   /// Return the complex address expression referenced by
437   /// this DBG_VALUE instruction.
438   const DIExpression *getDebugExpression() const;
439 
440   /// Return the debug label referenced by
441   /// this DBG_LABEL instruction.
442   const DILabel *getDebugLabel() const;
443 
444   /// Emit an error referring to the source location of this instruction.
445   /// This should only be used for inline assembly that is somehow
446   /// impossible to compile. Other errors should have been handled much
447   /// earlier.
448   ///
449   /// If this method returns, the caller should try to recover from the error.
450   void emitError(StringRef Msg) const;
451 
452   /// Returns the target instruction descriptor of this MachineInstr.
453   const MCInstrDesc &getDesc() const { return *MCID; }
454 
455   /// Returns the opcode of this MachineInstr.
456   unsigned getOpcode() const { return MCID->Opcode; }
457 
458   /// Retuns the total number of operands.
459   unsigned getNumOperands() const { return NumOperands; }
460 
461   /// Returns the total number of operands which are debug locations.
462   unsigned getNumDebugOperands() const {
463     return std::distance(debug_operands().begin(), debug_operands().end());
464   }
465 
466   const MachineOperand& getOperand(unsigned i) const {
467     assert(i < getNumOperands() && "getOperand() out of range!");
468     return Operands[i];
469   }
470   MachineOperand& getOperand(unsigned i) {
471     assert(i < getNumOperands() && "getOperand() out of range!");
472     return Operands[i];
473   }
474 
475   MachineOperand &getDebugOperand(unsigned Index) {
476     assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!");
477     return *(debug_operands().begin() + Index);
478   }
479   const MachineOperand &getDebugOperand(unsigned Index) const {
480     assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!");
481     return *(debug_operands().begin() + Index);
482   }
483 
484   /// Returns a pointer to the operand corresponding to a debug use of Reg, or
485   /// nullptr if Reg is not used in any debug operand.
486   const MachineOperand *getDebugOperandForReg(Register Reg) const {
487     const MachineOperand *RegOp =
488         find_if(debug_operands(), [Reg](const MachineOperand &Op) {
489           return Op.isReg() && Op.getReg() == Reg;
490         });
491     return RegOp == adl_end(debug_operands()) ? nullptr : RegOp;
492   }
493   MachineOperand *getDebugOperandForReg(Register Reg) {
494     MachineOperand *RegOp =
495         find_if(debug_operands(), [Reg](const MachineOperand &Op) {
496           return Op.isReg() && Op.getReg() == Reg;
497         });
498     return RegOp == adl_end(debug_operands()) ? nullptr : RegOp;
499   }
500 
501   unsigned getDebugOperandIndex(const MachineOperand *Op) const {
502     assert(Op >= adl_begin(debug_operands()) &&
503            Op <= adl_end(debug_operands()) && "Expected a debug operand.");
504     return std::distance(adl_begin(debug_operands()), Op);
505   }
506 
507   /// Returns the total number of definitions.
508   unsigned getNumDefs() const {
509     return getNumExplicitDefs() + MCID->getNumImplicitDefs();
510   }
511 
512   /// Returns true if the instruction has implicit definition.
513   bool hasImplicitDef() const {
514     for (unsigned I = getNumExplicitOperands(), E = getNumOperands();
515       I != E; ++I) {
516       const MachineOperand &MO = getOperand(I);
517       if (MO.isDef() && MO.isImplicit())
518         return true;
519     }
520     return false;
521   }
522 
523   /// Returns the implicit operands number.
524   unsigned getNumImplicitOperands() const {
525     return getNumOperands() - getNumExplicitOperands();
526   }
527 
528   /// Return true if operand \p OpIdx is a subregister index.
529   bool isOperandSubregIdx(unsigned OpIdx) const {
530     assert(getOperand(OpIdx).getType() == MachineOperand::MO_Immediate &&
531            "Expected MO_Immediate operand type.");
532     if (isExtractSubreg() && OpIdx == 2)
533       return true;
534     if (isInsertSubreg() && OpIdx == 3)
535       return true;
536     if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
537       return true;
538     if (isSubregToReg() && OpIdx == 3)
539       return true;
540     return false;
541   }
542 
543   /// Returns the number of non-implicit operands.
544   unsigned getNumExplicitOperands() const;
545 
546   /// Returns the number of non-implicit definitions.
547   unsigned getNumExplicitDefs() const;
548 
549   /// iterator/begin/end - Iterate over all operands of a machine instruction.
550   using mop_iterator = MachineOperand *;
551   using const_mop_iterator = const MachineOperand *;
552 
553   mop_iterator operands_begin() { return Operands; }
554   mop_iterator operands_end() { return Operands + NumOperands; }
555 
556   const_mop_iterator operands_begin() const { return Operands; }
557   const_mop_iterator operands_end() const { return Operands + NumOperands; }
558 
559   iterator_range<mop_iterator> operands() {
560     return make_range(operands_begin(), operands_end());
561   }
562   iterator_range<const_mop_iterator> operands() const {
563     return make_range(operands_begin(), operands_end());
564   }
565   iterator_range<mop_iterator> explicit_operands() {
566     return make_range(operands_begin(),
567                       operands_begin() + getNumExplicitOperands());
568   }
569   iterator_range<const_mop_iterator> explicit_operands() const {
570     return make_range(operands_begin(),
571                       operands_begin() + getNumExplicitOperands());
572   }
573   iterator_range<mop_iterator> implicit_operands() {
574     return make_range(explicit_operands().end(), operands_end());
575   }
576   iterator_range<const_mop_iterator> implicit_operands() const {
577     return make_range(explicit_operands().end(), operands_end());
578   }
579   /// Returns a range over all operands that are used to determine the variable
580   /// location for this DBG_VALUE instruction.
581   iterator_range<mop_iterator> debug_operands() {
582     assert(isDebugValue() && "Must be a debug value instruction.");
583     return make_range(operands_begin(), operands_begin() + 1);
584   }
585   /// \copydoc debug_operands()
586   iterator_range<const_mop_iterator> debug_operands() const {
587     assert(isDebugValue() && "Must be a debug value instruction.");
588     return make_range(operands_begin(), operands_begin() + 1);
589   }
590   /// Returns a range over all explicit operands that are register definitions.
591   /// Implicit definition are not included!
592   iterator_range<mop_iterator> defs() {
593     return make_range(operands_begin(),
594                       operands_begin() + getNumExplicitDefs());
595   }
596   /// \copydoc defs()
597   iterator_range<const_mop_iterator> defs() const {
598     return make_range(operands_begin(),
599                       operands_begin() + getNumExplicitDefs());
600   }
601   /// Returns a range that includes all operands that are register uses.
602   /// This may include unrelated operands which are not register uses.
603   iterator_range<mop_iterator> uses() {
604     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
605   }
606   /// \copydoc uses()
607   iterator_range<const_mop_iterator> uses() const {
608     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
609   }
610   iterator_range<mop_iterator> explicit_uses() {
611     return make_range(operands_begin() + getNumExplicitDefs(),
612                       operands_begin() + getNumExplicitOperands());
613   }
614   iterator_range<const_mop_iterator> explicit_uses() const {
615     return make_range(operands_begin() + getNumExplicitDefs(),
616                       operands_begin() + getNumExplicitOperands());
617   }
618 
619   /// Returns the number of the operand iterator \p I points to.
620   unsigned getOperandNo(const_mop_iterator I) const {
621     return I - operands_begin();
622   }
623 
624   /// Access to memory operands of the instruction. If there are none, that does
625   /// not imply anything about whether the function accesses memory. Instead,
626   /// the caller must behave conservatively.
627   ArrayRef<MachineMemOperand *> memoperands() const {
628     if (!Info)
629       return {};
630 
631     if (Info.is<EIIK_MMO>())
632       return makeArrayRef(Info.getAddrOfZeroTagPointer(), 1);
633 
634     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
635       return EI->getMMOs();
636 
637     return {};
638   }
639 
640   /// Access to memory operands of the instruction.
641   ///
642   /// If `memoperands_begin() == memoperands_end()`, that does not imply
643   /// anything about whether the function accesses memory. Instead, the caller
644   /// must behave conservatively.
645   mmo_iterator memoperands_begin() const { return memoperands().begin(); }
646 
647   /// Access to memory operands of the instruction.
648   ///
649   /// If `memoperands_begin() == memoperands_end()`, that does not imply
650   /// anything about whether the function accesses memory. Instead, the caller
651   /// must behave conservatively.
652   mmo_iterator memoperands_end() const { return memoperands().end(); }
653 
654   /// Return true if we don't have any memory operands which described the
655   /// memory access done by this instruction.  If this is true, calling code
656   /// must be conservative.
657   bool memoperands_empty() const { return memoperands().empty(); }
658 
659   /// Return true if this instruction has exactly one MachineMemOperand.
660   bool hasOneMemOperand() const { return memoperands().size() == 1; }
661 
662   /// Return the number of memory operands.
663   unsigned getNumMemOperands() const { return memoperands().size(); }
664 
665   /// Helper to extract a pre-instruction symbol if one has been added.
666   MCSymbol *getPreInstrSymbol() const {
667     if (!Info)
668       return nullptr;
669     if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
670       return S;
671     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
672       return EI->getPreInstrSymbol();
673 
674     return nullptr;
675   }
676 
677   /// Helper to extract a post-instruction symbol if one has been added.
678   MCSymbol *getPostInstrSymbol() const {
679     if (!Info)
680       return nullptr;
681     if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
682       return S;
683     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
684       return EI->getPostInstrSymbol();
685 
686     return nullptr;
687   }
688 
689   /// Helper to extract a heap alloc marker if one has been added.
690   MDNode *getHeapAllocMarker() const {
691     if (!Info)
692       return nullptr;
693     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
694       return EI->getHeapAllocMarker();
695 
696     return nullptr;
697   }
698 
699   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
700   /// queries but they are bundle aware.
701 
702   enum QueryType {
703     IgnoreBundle,    // Ignore bundles
704     AnyInBundle,     // Return true if any instruction in bundle has property
705     AllInBundle      // Return true if all instructions in bundle have property
706   };
707 
708   /// Return true if the instruction (or in the case of a bundle,
709   /// the instructions inside the bundle) has the specified property.
710   /// The first argument is the property being queried.
711   /// The second argument indicates whether the query should look inside
712   /// instruction bundles.
713   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
714     assert(MCFlag < 64 &&
715            "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.");
716     // Inline the fast path for unbundled or bundle-internal instructions.
717     if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
718       return getDesc().getFlags() & (1ULL << MCFlag);
719 
720     // If this is the first instruction in a bundle, take the slow path.
721     return hasPropertyInBundle(1ULL << MCFlag, Type);
722   }
723 
724   /// Return true if this is an instruction that should go through the usual
725   /// legalization steps.
726   bool isPreISelOpcode(QueryType Type = IgnoreBundle) const {
727     return hasProperty(MCID::PreISelOpcode, Type);
728   }
729 
730   /// Return true if this instruction can have a variable number of operands.
731   /// In this case, the variable operands will be after the normal
732   /// operands but before the implicit definitions and uses (if any are
733   /// present).
734   bool isVariadic(QueryType Type = IgnoreBundle) const {
735     return hasProperty(MCID::Variadic, Type);
736   }
737 
738   /// Set if this instruction has an optional definition, e.g.
739   /// ARM instructions which can set condition code if 's' bit is set.
740   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
741     return hasProperty(MCID::HasOptionalDef, Type);
742   }
743 
744   /// Return true if this is a pseudo instruction that doesn't
745   /// correspond to a real machine instruction.
746   bool isPseudo(QueryType Type = IgnoreBundle) const {
747     return hasProperty(MCID::Pseudo, Type);
748   }
749 
750   bool isReturn(QueryType Type = AnyInBundle) const {
751     return hasProperty(MCID::Return, Type);
752   }
753 
754   /// Return true if this is an instruction that marks the end of an EH scope,
755   /// i.e., a catchpad or a cleanuppad instruction.
756   bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
757     return hasProperty(MCID::EHScopeReturn, Type);
758   }
759 
760   bool isCall(QueryType Type = AnyInBundle) const {
761     return hasProperty(MCID::Call, Type);
762   }
763 
764   /// Return true if this is a call instruction that may have an associated
765   /// call site entry in the debug info.
766   bool isCandidateForCallSiteEntry(QueryType Type = IgnoreBundle) const;
767   /// Return true if copying, moving, or erasing this instruction requires
768   /// updating Call Site Info (see \ref copyCallSiteInfo, \ref moveCallSiteInfo,
769   /// \ref eraseCallSiteInfo).
770   bool shouldUpdateCallSiteInfo() const;
771 
772   /// Returns true if the specified instruction stops control flow
773   /// from executing the instruction immediately following it.  Examples include
774   /// unconditional branches and return instructions.
775   bool isBarrier(QueryType Type = AnyInBundle) const {
776     return hasProperty(MCID::Barrier, Type);
777   }
778 
779   /// Returns true if this instruction part of the terminator for a basic block.
780   /// Typically this is things like return and branch instructions.
781   ///
782   /// Various passes use this to insert code into the bottom of a basic block,
783   /// but before control flow occurs.
784   bool isTerminator(QueryType Type = AnyInBundle) const {
785     return hasProperty(MCID::Terminator, Type);
786   }
787 
788   /// Returns true if this is a conditional, unconditional, or indirect branch.
789   /// Predicates below can be used to discriminate between
790   /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to
791   /// get more information.
792   bool isBranch(QueryType Type = AnyInBundle) const {
793     return hasProperty(MCID::Branch, Type);
794   }
795 
796   /// Return true if this is an indirect branch, such as a
797   /// branch through a register.
798   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
799     return hasProperty(MCID::IndirectBranch, Type);
800   }
801 
802   /// Return true if this is a branch which may fall
803   /// through to the next instruction or may transfer control flow to some other
804   /// block.  The TargetInstrInfo::analyzeBranch method can be used to get more
805   /// information about this branch.
806   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
807     return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type);
808   }
809 
810   /// Return true if this is a branch which always
811   /// transfers control flow to some other block.  The
812   /// TargetInstrInfo::analyzeBranch method can be used to get more information
813   /// about this branch.
814   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
815     return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type);
816   }
817 
818   /// Return true if this instruction has a predicate operand that
819   /// controls execution.  It may be set to 'always', or may be set to other
820   /// values.   There are various methods in TargetInstrInfo that can be used to
821   /// control and modify the predicate in this instruction.
822   bool isPredicable(QueryType Type = AllInBundle) const {
823     // If it's a bundle than all bundled instructions must be predicable for this
824     // to return true.
825     return hasProperty(MCID::Predicable, Type);
826   }
827 
828   /// Return true if this instruction is a comparison.
829   bool isCompare(QueryType Type = IgnoreBundle) const {
830     return hasProperty(MCID::Compare, Type);
831   }
832 
833   /// Return true if this instruction is a move immediate
834   /// (including conditional moves) instruction.
835   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
836     return hasProperty(MCID::MoveImm, Type);
837   }
838 
839   /// Return true if this instruction is a register move.
840   /// (including moving values from subreg to reg)
841   bool isMoveReg(QueryType Type = IgnoreBundle) const {
842     return hasProperty(MCID::MoveReg, Type);
843   }
844 
845   /// Return true if this instruction is a bitcast instruction.
846   bool isBitcast(QueryType Type = IgnoreBundle) const {
847     return hasProperty(MCID::Bitcast, Type);
848   }
849 
850   /// Return true if this instruction is a select instruction.
851   bool isSelect(QueryType Type = IgnoreBundle) const {
852     return hasProperty(MCID::Select, Type);
853   }
854 
855   /// Return true if this instruction cannot be safely duplicated.
856   /// For example, if the instruction has a unique labels attached
857   /// to it, duplicating it would cause multiple definition errors.
858   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
859     return hasProperty(MCID::NotDuplicable, Type);
860   }
861 
862   /// Return true if this instruction is convergent.
863   /// Convergent instructions can not be made control-dependent on any
864   /// additional values.
865   bool isConvergent(QueryType Type = AnyInBundle) const {
866     if (isInlineAsm()) {
867       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
868       if (ExtraInfo & InlineAsm::Extra_IsConvergent)
869         return true;
870     }
871     return hasProperty(MCID::Convergent, Type);
872   }
873 
874   /// Returns true if the specified instruction has a delay slot
875   /// which must be filled by the code generator.
876   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
877     return hasProperty(MCID::DelaySlot, Type);
878   }
879 
880   /// Return true for instructions that can be folded as
881   /// memory operands in other instructions. The most common use for this
882   /// is instructions that are simple loads from memory that don't modify
883   /// the loaded value in any way, but it can also be used for instructions
884   /// that can be expressed as constant-pool loads, such as V_SETALLONES
885   /// on x86, to allow them to be folded when it is beneficial.
886   /// This should only be set on instructions that return a value in their
887   /// only virtual register definition.
888   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
889     return hasProperty(MCID::FoldableAsLoad, Type);
890   }
891 
892   /// Return true if this instruction behaves
893   /// the same way as the generic REG_SEQUENCE instructions.
894   /// E.g., on ARM,
895   /// dX VMOVDRR rY, rZ
896   /// is equivalent to
897   /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
898   ///
899   /// Note that for the optimizers to be able to take advantage of
900   /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
901   /// override accordingly.
902   bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
903     return hasProperty(MCID::RegSequence, Type);
904   }
905 
906   /// Return true if this instruction behaves
907   /// the same way as the generic EXTRACT_SUBREG instructions.
908   /// E.g., on ARM,
909   /// rX, rY VMOVRRD dZ
910   /// is equivalent to two EXTRACT_SUBREG:
911   /// rX = EXTRACT_SUBREG dZ, ssub_0
912   /// rY = EXTRACT_SUBREG dZ, ssub_1
913   ///
914   /// Note that for the optimizers to be able to take advantage of
915   /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
916   /// override accordingly.
917   bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
918     return hasProperty(MCID::ExtractSubreg, Type);
919   }
920 
921   /// Return true if this instruction behaves
922   /// the same way as the generic INSERT_SUBREG instructions.
923   /// E.g., on ARM,
924   /// dX = VSETLNi32 dY, rZ, Imm
925   /// is equivalent to a INSERT_SUBREG:
926   /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
927   ///
928   /// Note that for the optimizers to be able to take advantage of
929   /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
930   /// override accordingly.
931   bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
932     return hasProperty(MCID::InsertSubreg, Type);
933   }
934 
935   //===--------------------------------------------------------------------===//
936   // Side Effect Analysis
937   //===--------------------------------------------------------------------===//
938 
939   /// Return true if this instruction could possibly read memory.
940   /// Instructions with this flag set are not necessarily simple load
941   /// instructions, they may load a value and modify it, for example.
942   bool mayLoad(QueryType Type = AnyInBundle) const {
943     if (isInlineAsm()) {
944       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
945       if (ExtraInfo & InlineAsm::Extra_MayLoad)
946         return true;
947     }
948     return hasProperty(MCID::MayLoad, Type);
949   }
950 
951   /// Return true if this instruction could possibly modify memory.
952   /// Instructions with this flag set are not necessarily simple store
953   /// instructions, they may store a modified value based on their operands, or
954   /// may not actually modify anything, for example.
955   bool mayStore(QueryType Type = AnyInBundle) const {
956     if (isInlineAsm()) {
957       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
958       if (ExtraInfo & InlineAsm::Extra_MayStore)
959         return true;
960     }
961     return hasProperty(MCID::MayStore, Type);
962   }
963 
964   /// Return true if this instruction could possibly read or modify memory.
965   bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
966     return mayLoad(Type) || mayStore(Type);
967   }
968 
969   /// Return true if this instruction could possibly raise a floating-point
970   /// exception.  This is the case if the instruction is a floating-point
971   /// instruction that can in principle raise an exception, as indicated
972   /// by the MCID::MayRaiseFPException property, *and* at the same time,
973   /// the instruction is used in a context where we expect floating-point
974   /// exceptions are not disabled, as indicated by the NoFPExcept MI flag.
975   bool mayRaiseFPException() const {
976     return hasProperty(MCID::MayRaiseFPException) &&
977            !getFlag(MachineInstr::MIFlag::NoFPExcept);
978   }
979 
980   //===--------------------------------------------------------------------===//
981   // Flags that indicate whether an instruction can be modified by a method.
982   //===--------------------------------------------------------------------===//
983 
984   /// Return true if this may be a 2- or 3-address
985   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
986   /// result if Y and Z are exchanged.  If this flag is set, then the
987   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
988   /// instruction.
989   ///
990   /// Note that this flag may be set on instructions that are only commutable
991   /// sometimes.  In these cases, the call to commuteInstruction will fail.
992   /// Also note that some instructions require non-trivial modification to
993   /// commute them.
994   bool isCommutable(QueryType Type = IgnoreBundle) const {
995     return hasProperty(MCID::Commutable, Type);
996   }
997 
998   /// Return true if this is a 2-address instruction
999   /// which can be changed into a 3-address instruction if needed.  Doing this
1000   /// transformation can be profitable in the register allocator, because it
1001   /// means that the instruction can use a 2-address form if possible, but
1002   /// degrade into a less efficient form if the source and dest register cannot
1003   /// be assigned to the same register.  For example, this allows the x86
1004   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
1005   /// is the same speed as the shift but has bigger code size.
1006   ///
1007   /// If this returns true, then the target must implement the
1008   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
1009   /// is allowed to fail if the transformation isn't valid for this specific
1010   /// instruction (e.g. shl reg, 4 on x86).
1011   ///
1012   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
1013     return hasProperty(MCID::ConvertibleTo3Addr, Type);
1014   }
1015 
1016   /// Return true if this instruction requires
1017   /// custom insertion support when the DAG scheduler is inserting it into a
1018   /// machine basic block.  If this is true for the instruction, it basically
1019   /// means that it is a pseudo instruction used at SelectionDAG time that is
1020   /// expanded out into magic code by the target when MachineInstrs are formed.
1021   ///
1022   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
1023   /// is used to insert this into the MachineBasicBlock.
1024   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
1025     return hasProperty(MCID::UsesCustomInserter, Type);
1026   }
1027 
1028   /// Return true if this instruction requires *adjustment*
1029   /// after instruction selection by calling a target hook. For example, this
1030   /// can be used to fill in ARM 's' optional operand depending on whether
1031   /// the conditional flag register is used.
1032   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
1033     return hasProperty(MCID::HasPostISelHook, Type);
1034   }
1035 
1036   /// Returns true if this instruction is a candidate for remat.
1037   /// This flag is deprecated, please don't use it anymore.  If this
1038   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
1039   /// verify the instruction is really rematable.
1040   bool isRematerializable(QueryType Type = AllInBundle) const {
1041     // It's only possible to re-mat a bundle if all bundled instructions are
1042     // re-materializable.
1043     return hasProperty(MCID::Rematerializable, Type);
1044   }
1045 
1046   /// Returns true if this instruction has the same cost (or less) than a move
1047   /// instruction. This is useful during certain types of optimizations
1048   /// (e.g., remat during two-address conversion or machine licm)
1049   /// where we would like to remat or hoist the instruction, but not if it costs
1050   /// more than moving the instruction into the appropriate register. Note, we
1051   /// are not marking copies from and to the same register class with this flag.
1052   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
1053     // Only returns true for a bundle if all bundled instructions are cheap.
1054     return hasProperty(MCID::CheapAsAMove, Type);
1055   }
1056 
1057   /// Returns true if this instruction source operands
1058   /// have special register allocation requirements that are not captured by the
1059   /// operand register classes. e.g. ARM::STRD's two source registers must be an
1060   /// even / odd pair, ARM::STM registers have to be in ascending order.
1061   /// Post-register allocation passes should not attempt to change allocations
1062   /// for sources of instructions with this flag.
1063   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
1064     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
1065   }
1066 
1067   /// Returns true if this instruction def operands
1068   /// have special register allocation requirements that are not captured by the
1069   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
1070   /// even / odd pair, ARM::LDM registers have to be in ascending order.
1071   /// Post-register allocation passes should not attempt to change allocations
1072   /// for definitions of instructions with this flag.
1073   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
1074     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
1075   }
1076 
1077   enum MICheckType {
1078     CheckDefs,      // Check all operands for equality
1079     CheckKillDead,  // Check all operands including kill / dead markers
1080     IgnoreDefs,     // Ignore all definitions
1081     IgnoreVRegDefs  // Ignore virtual register definitions
1082   };
1083 
1084   /// Return true if this instruction is identical to \p Other.
1085   /// Two instructions are identical if they have the same opcode and all their
1086   /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
1087   /// Note that this means liveness related flags (dead, undef, kill) do not
1088   /// affect the notion of identical.
1089   bool isIdenticalTo(const MachineInstr &Other,
1090                      MICheckType Check = CheckDefs) const;
1091 
1092   /// Unlink 'this' from the containing basic block, and return it without
1093   /// deleting it.
1094   ///
1095   /// This function can not be used on bundled instructions, use
1096   /// removeFromBundle() to remove individual instructions from a bundle.
1097   MachineInstr *removeFromParent();
1098 
1099   /// Unlink this instruction from its basic block and return it without
1100   /// deleting it.
1101   ///
1102   /// If the instruction is part of a bundle, the other instructions in the
1103   /// bundle remain bundled.
1104   MachineInstr *removeFromBundle();
1105 
1106   /// Unlink 'this' from the containing basic block and delete it.
1107   ///
1108   /// If this instruction is the header of a bundle, the whole bundle is erased.
1109   /// This function can not be used for instructions inside a bundle, use
1110   /// eraseFromBundle() to erase individual bundled instructions.
1111   void eraseFromParent();
1112 
1113   /// Unlink 'this' from the containing basic block and delete it.
1114   ///
1115   /// For all definitions mark their uses in DBG_VALUE nodes
1116   /// as undefined. Otherwise like eraseFromParent().
1117   void eraseFromParentAndMarkDBGValuesForRemoval();
1118 
1119   /// Unlink 'this' form its basic block and delete it.
1120   ///
1121   /// If the instruction is part of a bundle, the other instructions in the
1122   /// bundle remain bundled.
1123   void eraseFromBundle();
1124 
1125   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
1126   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
1127   bool isAnnotationLabel() const {
1128     return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
1129   }
1130 
1131   /// Returns true if the MachineInstr represents a label.
1132   bool isLabel() const {
1133     return isEHLabel() || isGCLabel() || isAnnotationLabel();
1134   }
1135 
1136   bool isCFIInstruction() const {
1137     return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
1138   }
1139 
1140   // True if the instruction represents a position in the function.
1141   bool isPosition() const { return isLabel() || isCFIInstruction(); }
1142 
1143   bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
1144   bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
1145   bool isDebugInstr() const { return isDebugValue() || isDebugLabel(); }
1146 
1147   bool isDebugOffsetImm() const { return getDebugOffset().isImm(); }
1148 
1149   /// A DBG_VALUE is indirect iff the location operand is a register and
1150   /// the offset operand is an immediate.
1151   bool isIndirectDebugValue() const {
1152     return isDebugValue() && getDebugOperand(0).isReg() && isDebugOffsetImm();
1153   }
1154 
1155   /// A DBG_VALUE is an entry value iff its debug expression contains the
1156   /// DW_OP_LLVM_entry_value operation.
1157   bool isDebugEntryValue() const;
1158 
1159   /// Return true if the instruction is a debug value which describes a part of
1160   /// a variable as unavailable.
1161   bool isUndefDebugValue() const {
1162     return isDebugValue() && getDebugOperand(0).isReg() &&
1163            !getDebugOperand(0).getReg().isValid();
1164   }
1165 
1166   bool isPHI() const {
1167     return getOpcode() == TargetOpcode::PHI ||
1168            getOpcode() == TargetOpcode::G_PHI;
1169   }
1170   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
1171   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
1172   bool isInlineAsm() const {
1173     return getOpcode() == TargetOpcode::INLINEASM ||
1174            getOpcode() == TargetOpcode::INLINEASM_BR;
1175   }
1176 
1177   /// FIXME: Seems like a layering violation that the AsmDialect, which is X86
1178   /// specific, be attached to a generic MachineInstr.
1179   bool isMSInlineAsm() const {
1180     return isInlineAsm() && getInlineAsmDialect() == InlineAsm::AD_Intel;
1181   }
1182 
1183   bool isStackAligningInlineAsm() const;
1184   InlineAsm::AsmDialect getInlineAsmDialect() const;
1185 
1186   bool isInsertSubreg() const {
1187     return getOpcode() == TargetOpcode::INSERT_SUBREG;
1188   }
1189 
1190   bool isSubregToReg() const {
1191     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
1192   }
1193 
1194   bool isRegSequence() const {
1195     return getOpcode() == TargetOpcode::REG_SEQUENCE;
1196   }
1197 
1198   bool isBundle() const {
1199     return getOpcode() == TargetOpcode::BUNDLE;
1200   }
1201 
1202   bool isCopy() const {
1203     return getOpcode() == TargetOpcode::COPY;
1204   }
1205 
1206   bool isFullCopy() const {
1207     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
1208   }
1209 
1210   bool isExtractSubreg() const {
1211     return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
1212   }
1213 
1214   /// Return true if the instruction behaves like a copy.
1215   /// This does not include native copy instructions.
1216   bool isCopyLike() const {
1217     return isCopy() || isSubregToReg();
1218   }
1219 
1220   /// Return true is the instruction is an identity copy.
1221   bool isIdentityCopy() const {
1222     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
1223       getOperand(0).getSubReg() == getOperand(1).getSubReg();
1224   }
1225 
1226   /// Return true if this instruction doesn't produce any output in the form of
1227   /// executable instructions.
1228   bool isMetaInstruction() const {
1229     switch (getOpcode()) {
1230     default:
1231       return false;
1232     case TargetOpcode::IMPLICIT_DEF:
1233     case TargetOpcode::KILL:
1234     case TargetOpcode::CFI_INSTRUCTION:
1235     case TargetOpcode::EH_LABEL:
1236     case TargetOpcode::GC_LABEL:
1237     case TargetOpcode::DBG_VALUE:
1238     case TargetOpcode::DBG_LABEL:
1239     case TargetOpcode::LIFETIME_START:
1240     case TargetOpcode::LIFETIME_END:
1241       return true;
1242     }
1243   }
1244 
1245   /// Return true if this is a transient instruction that is either very likely
1246   /// to be eliminated during register allocation (such as copy-like
1247   /// instructions), or if this instruction doesn't have an execution-time cost.
1248   bool isTransient() const {
1249     switch (getOpcode()) {
1250     default:
1251       return isMetaInstruction();
1252     // Copy-like instructions are usually eliminated during register allocation.
1253     case TargetOpcode::PHI:
1254     case TargetOpcode::G_PHI:
1255     case TargetOpcode::COPY:
1256     case TargetOpcode::INSERT_SUBREG:
1257     case TargetOpcode::SUBREG_TO_REG:
1258     case TargetOpcode::REG_SEQUENCE:
1259       return true;
1260     }
1261   }
1262 
1263   /// Return the number of instructions inside the MI bundle, excluding the
1264   /// bundle header.
1265   ///
1266   /// This is the number of instructions that MachineBasicBlock::iterator
1267   /// skips, 0 for unbundled instructions.
1268   unsigned getBundleSize() const;
1269 
1270   /// Return true if the MachineInstr reads the specified register.
1271   /// If TargetRegisterInfo is passed, then it also checks if there
1272   /// is a read of a super-register.
1273   /// This does not count partial redefines of virtual registers as reads:
1274   ///   %reg1024:6 = OP.
1275   bool readsRegister(Register Reg,
1276                      const TargetRegisterInfo *TRI = nullptr) const {
1277     return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
1278   }
1279 
1280   /// Return true if the MachineInstr reads the specified virtual register.
1281   /// Take into account that a partial define is a
1282   /// read-modify-write operation.
1283   bool readsVirtualRegister(Register Reg) const {
1284     return readsWritesVirtualRegister(Reg).first;
1285   }
1286 
1287   /// Return a pair of bools (reads, writes) indicating if this instruction
1288   /// reads or writes Reg. This also considers partial defines.
1289   /// If Ops is not null, all operand indices for Reg are added.
1290   std::pair<bool,bool> readsWritesVirtualRegister(Register Reg,
1291                                 SmallVectorImpl<unsigned> *Ops = nullptr) const;
1292 
1293   /// Return true if the MachineInstr kills the specified register.
1294   /// If TargetRegisterInfo is passed, then it also checks if there is
1295   /// a kill of a super-register.
1296   bool killsRegister(Register Reg,
1297                      const TargetRegisterInfo *TRI = nullptr) const {
1298     return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
1299   }
1300 
1301   /// Return true if the MachineInstr fully defines the specified register.
1302   /// If TargetRegisterInfo is passed, then it also checks
1303   /// if there is a def of a super-register.
1304   /// NOTE: It's ignoring subreg indices on virtual registers.
1305   bool definesRegister(Register Reg,
1306                        const TargetRegisterInfo *TRI = nullptr) const {
1307     return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
1308   }
1309 
1310   /// Return true if the MachineInstr modifies (fully define or partially
1311   /// define) the specified register.
1312   /// NOTE: It's ignoring subreg indices on virtual registers.
1313   bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1314     return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
1315   }
1316 
1317   /// Returns true if the register is dead in this machine instruction.
1318   /// If TargetRegisterInfo is passed, then it also checks
1319   /// if there is a dead def of a super-register.
1320   bool registerDefIsDead(Register Reg,
1321                          const TargetRegisterInfo *TRI = nullptr) const {
1322     return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
1323   }
1324 
1325   /// Returns true if the MachineInstr has an implicit-use operand of exactly
1326   /// the given register (not considering sub/super-registers).
1327   bool hasRegisterImplicitUseOperand(Register Reg) const;
1328 
1329   /// Returns the operand index that is a use of the specific register or -1
1330   /// if it is not found. It further tightens the search criteria to a use
1331   /// that kills the register if isKill is true.
1332   int findRegisterUseOperandIdx(Register Reg, bool isKill = false,
1333                                 const TargetRegisterInfo *TRI = nullptr) const;
1334 
1335   /// Wrapper for findRegisterUseOperandIdx, it returns
1336   /// a pointer to the MachineOperand rather than an index.
1337   MachineOperand *findRegisterUseOperand(Register Reg, bool isKill = false,
1338                                       const TargetRegisterInfo *TRI = nullptr) {
1339     int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
1340     return (Idx == -1) ? nullptr : &getOperand(Idx);
1341   }
1342 
1343   const MachineOperand *findRegisterUseOperand(
1344     Register Reg, bool isKill = false,
1345     const TargetRegisterInfo *TRI = nullptr) const {
1346     return const_cast<MachineInstr *>(this)->
1347       findRegisterUseOperand(Reg, isKill, TRI);
1348   }
1349 
1350   /// Returns the operand index that is a def of the specified register or
1351   /// -1 if it is not found. If isDead is true, defs that are not dead are
1352   /// skipped. If Overlap is true, then it also looks for defs that merely
1353   /// overlap the specified register. If TargetRegisterInfo is non-null,
1354   /// then it also checks if there is a def of a super-register.
1355   /// This may also return a register mask operand when Overlap is true.
1356   int findRegisterDefOperandIdx(Register Reg,
1357                                 bool isDead = false, bool Overlap = false,
1358                                 const TargetRegisterInfo *TRI = nullptr) const;
1359 
1360   /// Wrapper for findRegisterDefOperandIdx, it returns
1361   /// a pointer to the MachineOperand rather than an index.
1362   MachineOperand *
1363   findRegisterDefOperand(Register Reg, bool isDead = false,
1364                          bool Overlap = false,
1365                          const TargetRegisterInfo *TRI = nullptr) {
1366     int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI);
1367     return (Idx == -1) ? nullptr : &getOperand(Idx);
1368   }
1369 
1370   const MachineOperand *
1371   findRegisterDefOperand(Register Reg, bool isDead = false,
1372                          bool Overlap = false,
1373                          const TargetRegisterInfo *TRI = nullptr) const {
1374     return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
1375         Reg, isDead, Overlap, TRI);
1376   }
1377 
1378   /// Find the index of the first operand in the
1379   /// operand list that is used to represent the predicate. It returns -1 if
1380   /// none is found.
1381   int findFirstPredOperandIdx() const;
1382 
1383   /// Find the index of the flag word operand that
1384   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
1385   /// getOperand(OpIdx) does not belong to an inline asm operand group.
1386   ///
1387   /// If GroupNo is not NULL, it will receive the number of the operand group
1388   /// containing OpIdx.
1389   ///
1390   /// The flag operand is an immediate that can be decoded with methods like
1391   /// InlineAsm::hasRegClassConstraint().
1392   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1393 
1394   /// Compute the static register class constraint for operand OpIdx.
1395   /// For normal instructions, this is derived from the MCInstrDesc.
1396   /// For inline assembly it is derived from the flag words.
1397   ///
1398   /// Returns NULL if the static register class constraint cannot be
1399   /// determined.
1400   const TargetRegisterClass*
1401   getRegClassConstraint(unsigned OpIdx,
1402                         const TargetInstrInfo *TII,
1403                         const TargetRegisterInfo *TRI) const;
1404 
1405   /// Applies the constraints (def/use) implied by this MI on \p Reg to
1406   /// the given \p CurRC.
1407   /// If \p ExploreBundle is set and MI is part of a bundle, all the
1408   /// instructions inside the bundle will be taken into account. In other words,
1409   /// this method accumulates all the constraints of the operand of this MI and
1410   /// the related bundle if MI is a bundle or inside a bundle.
1411   ///
1412   /// Returns the register class that satisfies both \p CurRC and the
1413   /// constraints set by MI. Returns NULL if such a register class does not
1414   /// exist.
1415   ///
1416   /// \pre CurRC must not be NULL.
1417   const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1418       Register Reg, const TargetRegisterClass *CurRC,
1419       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1420       bool ExploreBundle = false) const;
1421 
1422   /// Applies the constraints (def/use) implied by the \p OpIdx operand
1423   /// to the given \p CurRC.
1424   ///
1425   /// Returns the register class that satisfies both \p CurRC and the
1426   /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1427   /// does not exist.
1428   ///
1429   /// \pre CurRC must not be NULL.
1430   /// \pre The operand at \p OpIdx must be a register.
1431   const TargetRegisterClass *
1432   getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1433                               const TargetInstrInfo *TII,
1434                               const TargetRegisterInfo *TRI) const;
1435 
1436   /// Add a tie between the register operands at DefIdx and UseIdx.
1437   /// The tie will cause the register allocator to ensure that the two
1438   /// operands are assigned the same physical register.
1439   ///
1440   /// Tied operands are managed automatically for explicit operands in the
1441   /// MCInstrDesc. This method is for exceptional cases like inline asm.
1442   void tieOperands(unsigned DefIdx, unsigned UseIdx);
1443 
1444   /// Given the index of a tied register operand, find the
1445   /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1446   /// index of the tied operand which must exist.
1447   unsigned findTiedOperandIdx(unsigned OpIdx) const;
1448 
1449   /// Given the index of a register def operand,
1450   /// check if the register def is tied to a source operand, due to either
1451   /// two-address elimination or inline assembly constraints. Returns the
1452   /// first tied use operand index by reference if UseOpIdx is not null.
1453   bool isRegTiedToUseOperand(unsigned DefOpIdx,
1454                              unsigned *UseOpIdx = nullptr) const {
1455     const MachineOperand &MO = getOperand(DefOpIdx);
1456     if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1457       return false;
1458     if (UseOpIdx)
1459       *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1460     return true;
1461   }
1462 
1463   /// Return true if the use operand of the specified index is tied to a def
1464   /// operand. It also returns the def operand index by reference if DefOpIdx
1465   /// is not null.
1466   bool isRegTiedToDefOperand(unsigned UseOpIdx,
1467                              unsigned *DefOpIdx = nullptr) const {
1468     const MachineOperand &MO = getOperand(UseOpIdx);
1469     if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1470       return false;
1471     if (DefOpIdx)
1472       *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1473     return true;
1474   }
1475 
1476   /// Clears kill flags on all operands.
1477   void clearKillInfo();
1478 
1479   /// Replace all occurrences of FromReg with ToReg:SubIdx,
1480   /// properly composing subreg indices where necessary.
1481   void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx,
1482                           const TargetRegisterInfo &RegInfo);
1483 
1484   /// We have determined MI kills a register. Look for the
1485   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1486   /// add a implicit operand if it's not found. Returns true if the operand
1487   /// exists / is added.
1488   bool addRegisterKilled(Register IncomingReg,
1489                          const TargetRegisterInfo *RegInfo,
1490                          bool AddIfNotFound = false);
1491 
1492   /// Clear all kill flags affecting Reg.  If RegInfo is provided, this includes
1493   /// all aliasing registers.
1494   void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo);
1495 
1496   /// We have determined MI defined a register without a use.
1497   /// Look for the operand that defines it and mark it as IsDead. If
1498   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1499   /// true if the operand exists / is added.
1500   bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo,
1501                        bool AddIfNotFound = false);
1502 
1503   /// Clear all dead flags on operands defining register @p Reg.
1504   void clearRegisterDeads(Register Reg);
1505 
1506   /// Mark all subregister defs of register @p Reg with the undef flag.
1507   /// This function is used when we determined to have a subregister def in an
1508   /// otherwise undefined super register.
1509   void setRegisterDefReadUndef(Register Reg, bool IsUndef = true);
1510 
1511   /// We have determined MI defines a register. Make sure there is an operand
1512   /// defining Reg.
1513   void addRegisterDefined(Register Reg,
1514                           const TargetRegisterInfo *RegInfo = nullptr);
1515 
1516   /// Mark every physreg used by this instruction as
1517   /// dead except those in the UsedRegs list.
1518   ///
1519   /// On instructions with register mask operands, also add implicit-def
1520   /// operands for all registers in UsedRegs.
1521   void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
1522                              const TargetRegisterInfo &TRI);
1523 
1524   /// Return true if it is safe to move this instruction. If
1525   /// SawStore is set to true, it means that there is a store (or call) between
1526   /// the instruction's location and its intended destination.
1527   bool isSafeToMove(AAResults *AA, bool &SawStore) const;
1528 
1529   /// Returns true if this instruction's memory access aliases the memory
1530   /// access of Other.
1531   //
1532   /// Assumes any physical registers used to compute addresses
1533   /// have the same value for both instructions.  Returns false if neither
1534   /// instruction writes to memory.
1535   ///
1536   /// @param AA Optional alias analysis, used to compare memory operands.
1537   /// @param Other MachineInstr to check aliasing against.
1538   /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1539   bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const;
1540 
1541   /// Return true if this instruction may have an ordered
1542   /// or volatile memory reference, or if the information describing the memory
1543   /// reference is not available. Return false if it is known to have no
1544   /// ordered or volatile memory references.
1545   bool hasOrderedMemoryRef() const;
1546 
1547   /// Return true if this load instruction never traps and points to a memory
1548   /// location whose value doesn't change during the execution of this function.
1549   ///
1550   /// Examples include loading a value from the constant pool or from the
1551   /// argument area of a function (if it does not change).  If the instruction
1552   /// does multiple loads, this returns true only if all of the loads are
1553   /// dereferenceable and invariant.
1554   bool isDereferenceableInvariantLoad(AAResults *AA) const;
1555 
1556   /// If the specified instruction is a PHI that always merges together the
1557   /// same virtual register, return the register, otherwise return 0.
1558   unsigned isConstantValuePHI() const;
1559 
1560   /// Return true if this instruction has side effects that are not modeled
1561   /// by mayLoad / mayStore, etc.
1562   /// For all instructions, the property is encoded in MCInstrDesc::Flags
1563   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1564   /// INLINEASM instruction, in which case the side effect property is encoded
1565   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1566   ///
1567   bool hasUnmodeledSideEffects() const;
1568 
1569   /// Returns true if it is illegal to fold a load across this instruction.
1570   bool isLoadFoldBarrier() const;
1571 
1572   /// Return true if all the defs of this instruction are dead.
1573   bool allDefsAreDead() const;
1574 
1575   /// Return a valid size if the instruction is a spill instruction.
1576   Optional<unsigned> getSpillSize(const TargetInstrInfo *TII) const;
1577 
1578   /// Return a valid size if the instruction is a folded spill instruction.
1579   Optional<unsigned> getFoldedSpillSize(const TargetInstrInfo *TII) const;
1580 
1581   /// Return a valid size if the instruction is a restore instruction.
1582   Optional<unsigned> getRestoreSize(const TargetInstrInfo *TII) const;
1583 
1584   /// Return a valid size if the instruction is a folded restore instruction.
1585   Optional<unsigned>
1586   getFoldedRestoreSize(const TargetInstrInfo *TII) const;
1587 
1588   /// Copy implicit register operands from specified
1589   /// instruction to this instruction.
1590   void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1591 
1592   /// Debugging support
1593   /// @{
1594   /// Determine the generic type to be printed (if needed) on uses and defs.
1595   LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1596                      const MachineRegisterInfo &MRI) const;
1597 
1598   /// Return true when an instruction has tied register that can't be determined
1599   /// by the instruction's descriptor. This is useful for MIR printing, to
1600   /// determine whether we need to print the ties or not.
1601   bool hasComplexRegisterTies() const;
1602 
1603   /// Print this MI to \p OS.
1604   /// Don't print information that can be inferred from other instructions if
1605   /// \p IsStandalone is false. It is usually true when only a fragment of the
1606   /// function is printed.
1607   /// Only print the defs and the opcode if \p SkipOpers is true.
1608   /// Otherwise, also print operands if \p SkipDebugLoc is true.
1609   /// Otherwise, also print the debug loc, with a terminating newline.
1610   /// \p TII is used to print the opcode name.  If it's not present, but the
1611   /// MI is in a function, the opcode will be printed using the function's TII.
1612   void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1613              bool SkipDebugLoc = false, bool AddNewLine = true,
1614              const TargetInstrInfo *TII = nullptr) const;
1615   void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1616              bool SkipOpers = false, bool SkipDebugLoc = false,
1617              bool AddNewLine = true,
1618              const TargetInstrInfo *TII = nullptr) const;
1619   void dump() const;
1620   /// Print on dbgs() the current instruction and the instructions defining its
1621   /// operands and so on until we reach \p MaxDepth.
1622   void dumpr(const MachineRegisterInfo &MRI,
1623              unsigned MaxDepth = UINT_MAX) const;
1624   /// @}
1625 
1626   //===--------------------------------------------------------------------===//
1627   // Accessors used to build up machine instructions.
1628 
1629   /// Add the specified operand to the instruction.  If it is an implicit
1630   /// operand, it is added to the end of the operand list.  If it is an
1631   /// explicit operand it is added at the end of the explicit operand list
1632   /// (before the first implicit operand).
1633   ///
1634   /// MF must be the machine function that was used to allocate this
1635   /// instruction.
1636   ///
1637   /// MachineInstrBuilder provides a more convenient interface for creating
1638   /// instructions and adding operands.
1639   void addOperand(MachineFunction &MF, const MachineOperand &Op);
1640 
1641   /// Add an operand without providing an MF reference. This only works for
1642   /// instructions that are inserted in a basic block.
1643   ///
1644   /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1645   /// preferred.
1646   void addOperand(const MachineOperand &Op);
1647 
1648   /// Replace the instruction descriptor (thus opcode) of
1649   /// the current instruction with a new one.
1650   void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1651 
1652   /// Replace current source information with new such.
1653   /// Avoid using this, the constructor argument is preferable.
1654   void setDebugLoc(DebugLoc dl) {
1655     debugLoc = std::move(dl);
1656     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1657   }
1658 
1659   /// Erase an operand from an instruction, leaving it with one
1660   /// fewer operand than it started with.
1661   void RemoveOperand(unsigned OpNo);
1662 
1663   /// Clear this MachineInstr's memory reference descriptor list.  This resets
1664   /// the memrefs to their most conservative state.  This should be used only
1665   /// as a last resort since it greatly pessimizes our knowledge of the memory
1666   /// access performed by the instruction.
1667   void dropMemRefs(MachineFunction &MF);
1668 
1669   /// Assign this MachineInstr's memory reference descriptor list.
1670   ///
1671   /// Unlike other methods, this *will* allocate them into a new array
1672   /// associated with the provided `MachineFunction`.
1673   void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
1674 
1675   /// Add a MachineMemOperand to the machine instruction.
1676   /// This function should be used only occasionally. The setMemRefs function
1677   /// is the primary method for setting up a MachineInstr's MemRefs list.
1678   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1679 
1680   /// Clone another MachineInstr's memory reference descriptor list and replace
1681   /// ours with it.
1682   ///
1683   /// Note that `*this` may be the incoming MI!
1684   ///
1685   /// Prefer this API whenever possible as it can avoid allocations in common
1686   /// cases.
1687   void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
1688 
1689   /// Clone the merge of multiple MachineInstrs' memory reference descriptors
1690   /// list and replace ours with it.
1691   ///
1692   /// Note that `*this` may be one of the incoming MIs!
1693   ///
1694   /// Prefer this API whenever possible as it can avoid allocations in common
1695   /// cases.
1696   void cloneMergedMemRefs(MachineFunction &MF,
1697                           ArrayRef<const MachineInstr *> MIs);
1698 
1699   /// Set a symbol that will be emitted just prior to the instruction itself.
1700   ///
1701   /// Setting this to a null pointer will remove any such symbol.
1702   ///
1703   /// FIXME: This is not fully implemented yet.
1704   void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1705 
1706   /// Set a symbol that will be emitted just after the instruction itself.
1707   ///
1708   /// Setting this to a null pointer will remove any such symbol.
1709   ///
1710   /// FIXME: This is not fully implemented yet.
1711   void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1712 
1713   /// Clone another MachineInstr's pre- and post- instruction symbols and
1714   /// replace ours with it.
1715   void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
1716 
1717   /// Set a marker on instructions that denotes where we should create and emit
1718   /// heap alloc site labels. This waits until after instruction selection and
1719   /// optimizations to create the label, so it should still work if the
1720   /// instruction is removed or duplicated.
1721   void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
1722 
1723   /// Return the MIFlags which represent both MachineInstrs. This
1724   /// should be used when merging two MachineInstrs into one. This routine does
1725   /// not modify the MIFlags of this MachineInstr.
1726   uint16_t mergeFlagsWith(const MachineInstr& Other) const;
1727 
1728   static uint16_t copyFlagsFromInstruction(const Instruction &I);
1729 
1730   /// Copy all flags to MachineInst MIFlags
1731   void copyIRFlags(const Instruction &I);
1732 
1733   /// Break any tie involving OpIdx.
1734   void untieRegOperand(unsigned OpIdx) {
1735     MachineOperand &MO = getOperand(OpIdx);
1736     if (MO.isReg() && MO.isTied()) {
1737       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1738       MO.TiedTo = 0;
1739     }
1740   }
1741 
1742   /// Add all implicit def and use operands to this instruction.
1743   void addImplicitDefUseOperands(MachineFunction &MF);
1744 
1745   /// Scan instructions immediately following MI and collect any matching
1746   /// DBG_VALUEs.
1747   void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
1748 
1749   /// Find all DBG_VALUEs that point to the register def in this instruction
1750   /// and point them to \p Reg instead.
1751   void changeDebugValuesDefReg(Register Reg);
1752 
1753   /// Returns the Intrinsic::ID for this instruction.
1754   /// \pre Must have an intrinsic ID operand.
1755   unsigned getIntrinsicID() const {
1756     return getOperand(getNumExplicitDefs()).getIntrinsicID();
1757   }
1758 
1759   /// Sets all register debug operands in this debug value instruction to be
1760   /// undef.
1761   void setDebugValueUndef() {
1762     assert(isDebugValue() && "Must be a debug value instruction.");
1763     for (MachineOperand &MO : debug_operands()) {
1764       if (MO.isReg())
1765         MO.setReg(0);
1766     }
1767   }
1768 
1769 private:
1770   /// If this instruction is embedded into a MachineFunction, return the
1771   /// MachineRegisterInfo object for the current function, otherwise
1772   /// return null.
1773   MachineRegisterInfo *getRegInfo();
1774 
1775   /// Unlink all of the register operands in this instruction from their
1776   /// respective use lists.  This requires that the operands already be on their
1777   /// use lists.
1778   void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1779 
1780   /// Add all of the register operands in this instruction from their
1781   /// respective use lists.  This requires that the operands not be on their
1782   /// use lists yet.
1783   void AddRegOperandsToUseLists(MachineRegisterInfo&);
1784 
1785   /// Slow path for hasProperty when we're dealing with a bundle.
1786   bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
1787 
1788   /// Implements the logic of getRegClassConstraintEffectForVReg for the
1789   /// this MI and the given operand index \p OpIdx.
1790   /// If the related operand does not constrained Reg, this returns CurRC.
1791   const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1792       unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
1793       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1794 
1795   /// Stores extra instruction information inline or allocates as ExtraInfo
1796   /// based on the number of pointers.
1797   void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
1798                     MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
1799                     MDNode *HeapAllocMarker);
1800 };
1801 
1802 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1803 /// instruction rather than by pointer value.
1804 /// The hashing and equality testing functions ignore definitions so this is
1805 /// useful for CSE, etc.
1806 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1807   static inline MachineInstr *getEmptyKey() {
1808     return nullptr;
1809   }
1810 
1811   static inline MachineInstr *getTombstoneKey() {
1812     return reinterpret_cast<MachineInstr*>(-1);
1813   }
1814 
1815   static unsigned getHashValue(const MachineInstr* const &MI);
1816 
1817   static bool isEqual(const MachineInstr* const &LHS,
1818                       const MachineInstr* const &RHS) {
1819     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1820         LHS == getEmptyKey() || LHS == getTombstoneKey())
1821       return LHS == RHS;
1822     return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
1823   }
1824 };
1825 
1826 //===----------------------------------------------------------------------===//
1827 // Debugging Support
1828 
1829 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1830   MI.print(OS);
1831   return OS;
1832 }
1833 
1834 } // end namespace llvm
1835 
1836 #endif // LLVM_CODEGEN_MACHINEINSTR_H
1837