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 debug variable referenced by
412   /// this DBG_VALUE instruction.
413   const DILocalVariable *getDebugVariable() const;
414 
415   /// Return the complex address expression referenced by
416   /// this DBG_VALUE instruction.
417   const DIExpression *getDebugExpression() const;
418 
419   /// Return the debug label referenced by
420   /// this DBG_LABEL instruction.
421   const DILabel *getDebugLabel() const;
422 
423   /// Emit an error referring to the source location of this instruction.
424   /// This should only be used for inline assembly that is somehow
425   /// impossible to compile. Other errors should have been handled much
426   /// earlier.
427   ///
428   /// If this method returns, the caller should try to recover from the error.
429   void emitError(StringRef Msg) const;
430 
431   /// Returns the target instruction descriptor of this MachineInstr.
432   const MCInstrDesc &getDesc() const { return *MCID; }
433 
434   /// Returns the opcode of this MachineInstr.
435   unsigned getOpcode() const { return MCID->Opcode; }
436 
437   /// Retuns the total number of operands.
438   unsigned getNumOperands() const { return NumOperands; }
439 
440   const MachineOperand& getOperand(unsigned i) const {
441     assert(i < getNumOperands() && "getOperand() out of range!");
442     return Operands[i];
443   }
444   MachineOperand& getOperand(unsigned i) {
445     assert(i < getNumOperands() && "getOperand() out of range!");
446     return Operands[i];
447   }
448 
449   /// Returns the total number of definitions.
450   unsigned getNumDefs() const {
451     return getNumExplicitDefs() + MCID->getNumImplicitDefs();
452   }
453 
454   /// Returns true if the instruction has implicit definition.
455   bool hasImplicitDef() const {
456     for (unsigned I = getNumExplicitOperands(), E = getNumOperands();
457       I != E; ++I) {
458       const MachineOperand &MO = getOperand(I);
459       if (MO.isDef() && MO.isImplicit())
460         return true;
461     }
462     return false;
463   }
464 
465   /// Returns the implicit operands number.
466   unsigned getNumImplicitOperands() const {
467     return getNumOperands() - getNumExplicitOperands();
468   }
469 
470   /// Return true if operand \p OpIdx is a subregister index.
471   bool isOperandSubregIdx(unsigned OpIdx) const {
472     assert(getOperand(OpIdx).getType() == MachineOperand::MO_Immediate &&
473            "Expected MO_Immediate operand type.");
474     if (isExtractSubreg() && OpIdx == 2)
475       return true;
476     if (isInsertSubreg() && OpIdx == 3)
477       return true;
478     if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
479       return true;
480     if (isSubregToReg() && OpIdx == 3)
481       return true;
482     return false;
483   }
484 
485   /// Returns the number of non-implicit operands.
486   unsigned getNumExplicitOperands() const;
487 
488   /// Returns the number of non-implicit definitions.
489   unsigned getNumExplicitDefs() const;
490 
491   /// iterator/begin/end - Iterate over all operands of a machine instruction.
492   using mop_iterator = MachineOperand *;
493   using const_mop_iterator = const MachineOperand *;
494 
495   mop_iterator operands_begin() { return Operands; }
496   mop_iterator operands_end() { return Operands + NumOperands; }
497 
498   const_mop_iterator operands_begin() const { return Operands; }
499   const_mop_iterator operands_end() const { return Operands + NumOperands; }
500 
501   iterator_range<mop_iterator> operands() {
502     return make_range(operands_begin(), operands_end());
503   }
504   iterator_range<const_mop_iterator> operands() const {
505     return make_range(operands_begin(), operands_end());
506   }
507   iterator_range<mop_iterator> explicit_operands() {
508     return make_range(operands_begin(),
509                       operands_begin() + getNumExplicitOperands());
510   }
511   iterator_range<const_mop_iterator> explicit_operands() const {
512     return make_range(operands_begin(),
513                       operands_begin() + getNumExplicitOperands());
514   }
515   iterator_range<mop_iterator> implicit_operands() {
516     return make_range(explicit_operands().end(), operands_end());
517   }
518   iterator_range<const_mop_iterator> implicit_operands() const {
519     return make_range(explicit_operands().end(), operands_end());
520   }
521   /// Returns a range over all explicit operands that are register definitions.
522   /// Implicit definition are not included!
523   iterator_range<mop_iterator> defs() {
524     return make_range(operands_begin(),
525                       operands_begin() + getNumExplicitDefs());
526   }
527   /// \copydoc defs()
528   iterator_range<const_mop_iterator> defs() const {
529     return make_range(operands_begin(),
530                       operands_begin() + getNumExplicitDefs());
531   }
532   /// Returns a range that includes all operands that are register uses.
533   /// This may include unrelated operands which are not register uses.
534   iterator_range<mop_iterator> uses() {
535     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
536   }
537   /// \copydoc uses()
538   iterator_range<const_mop_iterator> uses() const {
539     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
540   }
541   iterator_range<mop_iterator> explicit_uses() {
542     return make_range(operands_begin() + getNumExplicitDefs(),
543                       operands_begin() + getNumExplicitOperands());
544   }
545   iterator_range<const_mop_iterator> explicit_uses() const {
546     return make_range(operands_begin() + getNumExplicitDefs(),
547                       operands_begin() + getNumExplicitOperands());
548   }
549 
550   /// Returns the number of the operand iterator \p I points to.
551   unsigned getOperandNo(const_mop_iterator I) const {
552     return I - operands_begin();
553   }
554 
555   /// Access to memory operands of the instruction. If there are none, that does
556   /// not imply anything about whether the function accesses memory. Instead,
557   /// the caller must behave conservatively.
558   ArrayRef<MachineMemOperand *> memoperands() const {
559     if (!Info)
560       return {};
561 
562     if (Info.is<EIIK_MMO>())
563       return makeArrayRef(Info.getAddrOfZeroTagPointer(), 1);
564 
565     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
566       return EI->getMMOs();
567 
568     return {};
569   }
570 
571   /// Access to memory operands of the instruction.
572   ///
573   /// If `memoperands_begin() == memoperands_end()`, that does not imply
574   /// anything about whether the function accesses memory. Instead, the caller
575   /// must behave conservatively.
576   mmo_iterator memoperands_begin() const { return memoperands().begin(); }
577 
578   /// Access to memory operands of the instruction.
579   ///
580   /// If `memoperands_begin() == memoperands_end()`, that does not imply
581   /// anything about whether the function accesses memory. Instead, the caller
582   /// must behave conservatively.
583   mmo_iterator memoperands_end() const { return memoperands().end(); }
584 
585   /// Return true if we don't have any memory operands which described the
586   /// memory access done by this instruction.  If this is true, calling code
587   /// must be conservative.
588   bool memoperands_empty() const { return memoperands().empty(); }
589 
590   /// Return true if this instruction has exactly one MachineMemOperand.
591   bool hasOneMemOperand() const { return memoperands().size() == 1; }
592 
593   /// Return the number of memory operands.
594   unsigned getNumMemOperands() const { return memoperands().size(); }
595 
596   /// Helper to extract a pre-instruction symbol if one has been added.
597   MCSymbol *getPreInstrSymbol() const {
598     if (!Info)
599       return nullptr;
600     if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
601       return S;
602     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
603       return EI->getPreInstrSymbol();
604 
605     return nullptr;
606   }
607 
608   /// Helper to extract a post-instruction symbol if one has been added.
609   MCSymbol *getPostInstrSymbol() const {
610     if (!Info)
611       return nullptr;
612     if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
613       return S;
614     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
615       return EI->getPostInstrSymbol();
616 
617     return nullptr;
618   }
619 
620   /// Helper to extract a heap alloc marker if one has been added.
621   MDNode *getHeapAllocMarker() const {
622     if (!Info)
623       return nullptr;
624     if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
625       return EI->getHeapAllocMarker();
626 
627     return nullptr;
628   }
629 
630   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
631   /// queries but they are bundle aware.
632 
633   enum QueryType {
634     IgnoreBundle,    // Ignore bundles
635     AnyInBundle,     // Return true if any instruction in bundle has property
636     AllInBundle      // Return true if all instructions in bundle have property
637   };
638 
639   /// Return true if the instruction (or in the case of a bundle,
640   /// the instructions inside the bundle) has the specified property.
641   /// The first argument is the property being queried.
642   /// The second argument indicates whether the query should look inside
643   /// instruction bundles.
644   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
645     assert(MCFlag < 64 &&
646            "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.");
647     // Inline the fast path for unbundled or bundle-internal instructions.
648     if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
649       return getDesc().getFlags() & (1ULL << MCFlag);
650 
651     // If this is the first instruction in a bundle, take the slow path.
652     return hasPropertyInBundle(1ULL << MCFlag, Type);
653   }
654 
655   /// Return true if this is an instruction that should go through the usual
656   /// legalization steps.
657   bool isPreISelOpcode(QueryType Type = IgnoreBundle) const {
658     return hasProperty(MCID::PreISelOpcode, Type);
659   }
660 
661   /// Return true if this instruction can have a variable number of operands.
662   /// In this case, the variable operands will be after the normal
663   /// operands but before the implicit definitions and uses (if any are
664   /// present).
665   bool isVariadic(QueryType Type = IgnoreBundle) const {
666     return hasProperty(MCID::Variadic, Type);
667   }
668 
669   /// Set if this instruction has an optional definition, e.g.
670   /// ARM instructions which can set condition code if 's' bit is set.
671   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
672     return hasProperty(MCID::HasOptionalDef, Type);
673   }
674 
675   /// Return true if this is a pseudo instruction that doesn't
676   /// correspond to a real machine instruction.
677   bool isPseudo(QueryType Type = IgnoreBundle) const {
678     return hasProperty(MCID::Pseudo, Type);
679   }
680 
681   bool isReturn(QueryType Type = AnyInBundle) const {
682     return hasProperty(MCID::Return, Type);
683   }
684 
685   /// Return true if this is an instruction that marks the end of an EH scope,
686   /// i.e., a catchpad or a cleanuppad instruction.
687   bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
688     return hasProperty(MCID::EHScopeReturn, Type);
689   }
690 
691   bool isCall(QueryType Type = AnyInBundle) const {
692     return hasProperty(MCID::Call, Type);
693   }
694 
695   /// Return true if this is a call instruction that may have an associated
696   /// call site entry in the debug info.
697   bool isCandidateForCallSiteEntry(QueryType Type = IgnoreBundle) const;
698   /// Return true if copying, moving, or erasing this instruction requires
699   /// updating Call Site Info (see \ref copyCallSiteInfo, \ref moveCallSiteInfo,
700   /// \ref eraseCallSiteInfo).
701   bool shouldUpdateCallSiteInfo() const;
702 
703   /// Returns true if the specified instruction stops control flow
704   /// from executing the instruction immediately following it.  Examples include
705   /// unconditional branches and return instructions.
706   bool isBarrier(QueryType Type = AnyInBundle) const {
707     return hasProperty(MCID::Barrier, Type);
708   }
709 
710   /// Returns true if this instruction part of the terminator for a basic block.
711   /// Typically this is things like return and branch instructions.
712   ///
713   /// Various passes use this to insert code into the bottom of a basic block,
714   /// but before control flow occurs.
715   bool isTerminator(QueryType Type = AnyInBundle) const {
716     return hasProperty(MCID::Terminator, Type);
717   }
718 
719   /// Returns true if this is a conditional, unconditional, or indirect branch.
720   /// Predicates below can be used to discriminate between
721   /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to
722   /// get more information.
723   bool isBranch(QueryType Type = AnyInBundle) const {
724     return hasProperty(MCID::Branch, Type);
725   }
726 
727   /// Return true if this is an indirect branch, such as a
728   /// branch through a register.
729   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
730     return hasProperty(MCID::IndirectBranch, Type);
731   }
732 
733   /// Return true if this is a branch which may fall
734   /// through to the next instruction or may transfer control flow to some other
735   /// block.  The TargetInstrInfo::analyzeBranch method can be used to get more
736   /// information about this branch.
737   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
738     return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type);
739   }
740 
741   /// Return true if this is a branch which always
742   /// transfers control flow to some other block.  The
743   /// TargetInstrInfo::analyzeBranch method can be used to get more information
744   /// about this branch.
745   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
746     return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type);
747   }
748 
749   /// Return true if this instruction has a predicate operand that
750   /// controls execution.  It may be set to 'always', or may be set to other
751   /// values.   There are various methods in TargetInstrInfo that can be used to
752   /// control and modify the predicate in this instruction.
753   bool isPredicable(QueryType Type = AllInBundle) const {
754     // If it's a bundle than all bundled instructions must be predicable for this
755     // to return true.
756     return hasProperty(MCID::Predicable, Type);
757   }
758 
759   /// Return true if this instruction is a comparison.
760   bool isCompare(QueryType Type = IgnoreBundle) const {
761     return hasProperty(MCID::Compare, Type);
762   }
763 
764   /// Return true if this instruction is a move immediate
765   /// (including conditional moves) instruction.
766   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
767     return hasProperty(MCID::MoveImm, Type);
768   }
769 
770   /// Return true if this instruction is a register move.
771   /// (including moving values from subreg to reg)
772   bool isMoveReg(QueryType Type = IgnoreBundle) const {
773     return hasProperty(MCID::MoveReg, Type);
774   }
775 
776   /// Return true if this instruction is a bitcast instruction.
777   bool isBitcast(QueryType Type = IgnoreBundle) const {
778     return hasProperty(MCID::Bitcast, Type);
779   }
780 
781   /// Return true if this instruction is a select instruction.
782   bool isSelect(QueryType Type = IgnoreBundle) const {
783     return hasProperty(MCID::Select, Type);
784   }
785 
786   /// Return true if this instruction cannot be safely duplicated.
787   /// For example, if the instruction has a unique labels attached
788   /// to it, duplicating it would cause multiple definition errors.
789   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
790     return hasProperty(MCID::NotDuplicable, Type);
791   }
792 
793   /// Return true if this instruction is convergent.
794   /// Convergent instructions can not be made control-dependent on any
795   /// additional values.
796   bool isConvergent(QueryType Type = AnyInBundle) const {
797     if (isInlineAsm()) {
798       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
799       if (ExtraInfo & InlineAsm::Extra_IsConvergent)
800         return true;
801     }
802     return hasProperty(MCID::Convergent, Type);
803   }
804 
805   /// Returns true if the specified instruction has a delay slot
806   /// which must be filled by the code generator.
807   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
808     return hasProperty(MCID::DelaySlot, Type);
809   }
810 
811   /// Return true for instructions that can be folded as
812   /// memory operands in other instructions. The most common use for this
813   /// is instructions that are simple loads from memory that don't modify
814   /// the loaded value in any way, but it can also be used for instructions
815   /// that can be expressed as constant-pool loads, such as V_SETALLONES
816   /// on x86, to allow them to be folded when it is beneficial.
817   /// This should only be set on instructions that return a value in their
818   /// only virtual register definition.
819   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
820     return hasProperty(MCID::FoldableAsLoad, Type);
821   }
822 
823   /// Return true if this instruction behaves
824   /// the same way as the generic REG_SEQUENCE instructions.
825   /// E.g., on ARM,
826   /// dX VMOVDRR rY, rZ
827   /// is equivalent to
828   /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
829   ///
830   /// Note that for the optimizers to be able to take advantage of
831   /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
832   /// override accordingly.
833   bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
834     return hasProperty(MCID::RegSequence, Type);
835   }
836 
837   /// Return true if this instruction behaves
838   /// the same way as the generic EXTRACT_SUBREG instructions.
839   /// E.g., on ARM,
840   /// rX, rY VMOVRRD dZ
841   /// is equivalent to two EXTRACT_SUBREG:
842   /// rX = EXTRACT_SUBREG dZ, ssub_0
843   /// rY = EXTRACT_SUBREG dZ, ssub_1
844   ///
845   /// Note that for the optimizers to be able to take advantage of
846   /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
847   /// override accordingly.
848   bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
849     return hasProperty(MCID::ExtractSubreg, Type);
850   }
851 
852   /// Return true if this instruction behaves
853   /// the same way as the generic INSERT_SUBREG instructions.
854   /// E.g., on ARM,
855   /// dX = VSETLNi32 dY, rZ, Imm
856   /// is equivalent to a INSERT_SUBREG:
857   /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
858   ///
859   /// Note that for the optimizers to be able to take advantage of
860   /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
861   /// override accordingly.
862   bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
863     return hasProperty(MCID::InsertSubreg, Type);
864   }
865 
866   //===--------------------------------------------------------------------===//
867   // Side Effect Analysis
868   //===--------------------------------------------------------------------===//
869 
870   /// Return true if this instruction could possibly read memory.
871   /// Instructions with this flag set are not necessarily simple load
872   /// instructions, they may load a value and modify it, for example.
873   bool mayLoad(QueryType Type = AnyInBundle) const {
874     if (isInlineAsm()) {
875       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
876       if (ExtraInfo & InlineAsm::Extra_MayLoad)
877         return true;
878     }
879     return hasProperty(MCID::MayLoad, Type);
880   }
881 
882   /// Return true if this instruction could possibly modify memory.
883   /// Instructions with this flag set are not necessarily simple store
884   /// instructions, they may store a modified value based on their operands, or
885   /// may not actually modify anything, for example.
886   bool mayStore(QueryType Type = AnyInBundle) const {
887     if (isInlineAsm()) {
888       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
889       if (ExtraInfo & InlineAsm::Extra_MayStore)
890         return true;
891     }
892     return hasProperty(MCID::MayStore, Type);
893   }
894 
895   /// Return true if this instruction could possibly read or modify memory.
896   bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
897     return mayLoad(Type) || mayStore(Type);
898   }
899 
900   /// Return true if this instruction could possibly raise a floating-point
901   /// exception.  This is the case if the instruction is a floating-point
902   /// instruction that can in principle raise an exception, as indicated
903   /// by the MCID::MayRaiseFPException property, *and* at the same time,
904   /// the instruction is used in a context where we expect floating-point
905   /// exceptions are not disabled, as indicated by the NoFPExcept MI flag.
906   bool mayRaiseFPException() const {
907     return hasProperty(MCID::MayRaiseFPException) &&
908            !getFlag(MachineInstr::MIFlag::NoFPExcept);
909   }
910 
911   //===--------------------------------------------------------------------===//
912   // Flags that indicate whether an instruction can be modified by a method.
913   //===--------------------------------------------------------------------===//
914 
915   /// Return true if this may be a 2- or 3-address
916   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
917   /// result if Y and Z are exchanged.  If this flag is set, then the
918   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
919   /// instruction.
920   ///
921   /// Note that this flag may be set on instructions that are only commutable
922   /// sometimes.  In these cases, the call to commuteInstruction will fail.
923   /// Also note that some instructions require non-trivial modification to
924   /// commute them.
925   bool isCommutable(QueryType Type = IgnoreBundle) const {
926     return hasProperty(MCID::Commutable, Type);
927   }
928 
929   /// Return true if this is a 2-address instruction
930   /// which can be changed into a 3-address instruction if needed.  Doing this
931   /// transformation can be profitable in the register allocator, because it
932   /// means that the instruction can use a 2-address form if possible, but
933   /// degrade into a less efficient form if the source and dest register cannot
934   /// be assigned to the same register.  For example, this allows the x86
935   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
936   /// is the same speed as the shift but has bigger code size.
937   ///
938   /// If this returns true, then the target must implement the
939   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
940   /// is allowed to fail if the transformation isn't valid for this specific
941   /// instruction (e.g. shl reg, 4 on x86).
942   ///
943   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
944     return hasProperty(MCID::ConvertibleTo3Addr, Type);
945   }
946 
947   /// Return true if this instruction requires
948   /// custom insertion support when the DAG scheduler is inserting it into a
949   /// machine basic block.  If this is true for the instruction, it basically
950   /// means that it is a pseudo instruction used at SelectionDAG time that is
951   /// expanded out into magic code by the target when MachineInstrs are formed.
952   ///
953   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
954   /// is used to insert this into the MachineBasicBlock.
955   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
956     return hasProperty(MCID::UsesCustomInserter, Type);
957   }
958 
959   /// Return true if this instruction requires *adjustment*
960   /// after instruction selection by calling a target hook. For example, this
961   /// can be used to fill in ARM 's' optional operand depending on whether
962   /// the conditional flag register is used.
963   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
964     return hasProperty(MCID::HasPostISelHook, Type);
965   }
966 
967   /// Returns true if this instruction is a candidate for remat.
968   /// This flag is deprecated, please don't use it anymore.  If this
969   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
970   /// verify the instruction is really rematable.
971   bool isRematerializable(QueryType Type = AllInBundle) const {
972     // It's only possible to re-mat a bundle if all bundled instructions are
973     // re-materializable.
974     return hasProperty(MCID::Rematerializable, Type);
975   }
976 
977   /// Returns true if this instruction has the same cost (or less) than a move
978   /// instruction. This is useful during certain types of optimizations
979   /// (e.g., remat during two-address conversion or machine licm)
980   /// where we would like to remat or hoist the instruction, but not if it costs
981   /// more than moving the instruction into the appropriate register. Note, we
982   /// are not marking copies from and to the same register class with this flag.
983   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
984     // Only returns true for a bundle if all bundled instructions are cheap.
985     return hasProperty(MCID::CheapAsAMove, Type);
986   }
987 
988   /// Returns true if this instruction source operands
989   /// have special register allocation requirements that are not captured by the
990   /// operand register classes. e.g. ARM::STRD's two source registers must be an
991   /// even / odd pair, ARM::STM registers have to be in ascending order.
992   /// Post-register allocation passes should not attempt to change allocations
993   /// for sources of instructions with this flag.
994   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
995     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
996   }
997 
998   /// Returns true if this instruction def operands
999   /// have special register allocation requirements that are not captured by the
1000   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
1001   /// even / odd pair, ARM::LDM registers have to be in ascending order.
1002   /// Post-register allocation passes should not attempt to change allocations
1003   /// for definitions of instructions with this flag.
1004   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
1005     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
1006   }
1007 
1008   enum MICheckType {
1009     CheckDefs,      // Check all operands for equality
1010     CheckKillDead,  // Check all operands including kill / dead markers
1011     IgnoreDefs,     // Ignore all definitions
1012     IgnoreVRegDefs  // Ignore virtual register definitions
1013   };
1014 
1015   /// Return true if this instruction is identical to \p Other.
1016   /// Two instructions are identical if they have the same opcode and all their
1017   /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
1018   /// Note that this means liveness related flags (dead, undef, kill) do not
1019   /// affect the notion of identical.
1020   bool isIdenticalTo(const MachineInstr &Other,
1021                      MICheckType Check = CheckDefs) const;
1022 
1023   /// Unlink 'this' from the containing basic block, and return it without
1024   /// deleting it.
1025   ///
1026   /// This function can not be used on bundled instructions, use
1027   /// removeFromBundle() to remove individual instructions from a bundle.
1028   MachineInstr *removeFromParent();
1029 
1030   /// Unlink this instruction from its basic block and return it without
1031   /// deleting it.
1032   ///
1033   /// If the instruction is part of a bundle, the other instructions in the
1034   /// bundle remain bundled.
1035   MachineInstr *removeFromBundle();
1036 
1037   /// Unlink 'this' from the containing basic block and delete it.
1038   ///
1039   /// If this instruction is the header of a bundle, the whole bundle is erased.
1040   /// This function can not be used for instructions inside a bundle, use
1041   /// eraseFromBundle() to erase individual bundled instructions.
1042   void eraseFromParent();
1043 
1044   /// Unlink 'this' from the containing basic block and delete it.
1045   ///
1046   /// For all definitions mark their uses in DBG_VALUE nodes
1047   /// as undefined. Otherwise like eraseFromParent().
1048   void eraseFromParentAndMarkDBGValuesForRemoval();
1049 
1050   /// Unlink 'this' form its basic block and delete it.
1051   ///
1052   /// If the instruction is part of a bundle, the other instructions in the
1053   /// bundle remain bundled.
1054   void eraseFromBundle();
1055 
1056   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
1057   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
1058   bool isAnnotationLabel() const {
1059     return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
1060   }
1061 
1062   /// Returns true if the MachineInstr represents a label.
1063   bool isLabel() const {
1064     return isEHLabel() || isGCLabel() || isAnnotationLabel();
1065   }
1066 
1067   bool isCFIInstruction() const {
1068     return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
1069   }
1070 
1071   // True if the instruction represents a position in the function.
1072   bool isPosition() const { return isLabel() || isCFIInstruction(); }
1073 
1074   bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
1075   bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
1076   bool isDebugInstr() const { return isDebugValue() || isDebugLabel(); }
1077 
1078   /// A DBG_VALUE is indirect iff the first operand is a register and
1079   /// the second operand is an immediate.
1080   bool isIndirectDebugValue() const {
1081     return isDebugValue()
1082       && getOperand(0).isReg()
1083       && getOperand(1).isImm();
1084   }
1085 
1086   /// A DBG_VALUE is an entry value iff its debug expression contains the
1087   /// DW_OP_LLVM_entry_value operation.
1088   bool isDebugEntryValue() const;
1089 
1090   /// Return true if the instruction is a debug value which describes a part of
1091   /// a variable as unavailable.
1092   bool isUndefDebugValue() const {
1093     return isDebugValue() && getOperand(0).isReg() && !getOperand(0).getReg().isValid();
1094   }
1095 
1096   bool isPHI() const {
1097     return getOpcode() == TargetOpcode::PHI ||
1098            getOpcode() == TargetOpcode::G_PHI;
1099   }
1100   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
1101   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
1102   bool isInlineAsm() const {
1103     return getOpcode() == TargetOpcode::INLINEASM ||
1104            getOpcode() == TargetOpcode::INLINEASM_BR;
1105   }
1106 
1107   /// FIXME: Seems like a layering violation that the AsmDialect, which is X86
1108   /// specific, be attached to a generic MachineInstr.
1109   bool isMSInlineAsm() const {
1110     return isInlineAsm() && getInlineAsmDialect() == InlineAsm::AD_Intel;
1111   }
1112 
1113   bool isStackAligningInlineAsm() const;
1114   InlineAsm::AsmDialect getInlineAsmDialect() const;
1115 
1116   bool isInsertSubreg() const {
1117     return getOpcode() == TargetOpcode::INSERT_SUBREG;
1118   }
1119 
1120   bool isSubregToReg() const {
1121     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
1122   }
1123 
1124   bool isRegSequence() const {
1125     return getOpcode() == TargetOpcode::REG_SEQUENCE;
1126   }
1127 
1128   bool isBundle() const {
1129     return getOpcode() == TargetOpcode::BUNDLE;
1130   }
1131 
1132   bool isCopy() const {
1133     return getOpcode() == TargetOpcode::COPY;
1134   }
1135 
1136   bool isFullCopy() const {
1137     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
1138   }
1139 
1140   bool isExtractSubreg() const {
1141     return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
1142   }
1143 
1144   /// Return true if the instruction behaves like a copy.
1145   /// This does not include native copy instructions.
1146   bool isCopyLike() const {
1147     return isCopy() || isSubregToReg();
1148   }
1149 
1150   /// Return true is the instruction is an identity copy.
1151   bool isIdentityCopy() const {
1152     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
1153       getOperand(0).getSubReg() == getOperand(1).getSubReg();
1154   }
1155 
1156   /// Return true if this instruction doesn't produce any output in the form of
1157   /// executable instructions.
1158   bool isMetaInstruction() const {
1159     switch (getOpcode()) {
1160     default:
1161       return false;
1162     case TargetOpcode::IMPLICIT_DEF:
1163     case TargetOpcode::KILL:
1164     case TargetOpcode::CFI_INSTRUCTION:
1165     case TargetOpcode::EH_LABEL:
1166     case TargetOpcode::GC_LABEL:
1167     case TargetOpcode::DBG_VALUE:
1168     case TargetOpcode::DBG_LABEL:
1169     case TargetOpcode::LIFETIME_START:
1170     case TargetOpcode::LIFETIME_END:
1171       return true;
1172     }
1173   }
1174 
1175   /// Return true if this is a transient instruction that is either very likely
1176   /// to be eliminated during register allocation (such as copy-like
1177   /// instructions), or if this instruction doesn't have an execution-time cost.
1178   bool isTransient() const {
1179     switch (getOpcode()) {
1180     default:
1181       return isMetaInstruction();
1182     // Copy-like instructions are usually eliminated during register allocation.
1183     case TargetOpcode::PHI:
1184     case TargetOpcode::G_PHI:
1185     case TargetOpcode::COPY:
1186     case TargetOpcode::INSERT_SUBREG:
1187     case TargetOpcode::SUBREG_TO_REG:
1188     case TargetOpcode::REG_SEQUENCE:
1189       return true;
1190     }
1191   }
1192 
1193   /// Return the number of instructions inside the MI bundle, excluding the
1194   /// bundle header.
1195   ///
1196   /// This is the number of instructions that MachineBasicBlock::iterator
1197   /// skips, 0 for unbundled instructions.
1198   unsigned getBundleSize() const;
1199 
1200   /// Return true if the MachineInstr reads the specified register.
1201   /// If TargetRegisterInfo is passed, then it also checks if there
1202   /// is a read of a super-register.
1203   /// This does not count partial redefines of virtual registers as reads:
1204   ///   %reg1024:6 = OP.
1205   bool readsRegister(Register Reg,
1206                      const TargetRegisterInfo *TRI = nullptr) const {
1207     return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
1208   }
1209 
1210   /// Return true if the MachineInstr reads the specified virtual register.
1211   /// Take into account that a partial define is a
1212   /// read-modify-write operation.
1213   bool readsVirtualRegister(Register Reg) const {
1214     return readsWritesVirtualRegister(Reg).first;
1215   }
1216 
1217   /// Return a pair of bools (reads, writes) indicating if this instruction
1218   /// reads or writes Reg. This also considers partial defines.
1219   /// If Ops is not null, all operand indices for Reg are added.
1220   std::pair<bool,bool> readsWritesVirtualRegister(Register Reg,
1221                                 SmallVectorImpl<unsigned> *Ops = nullptr) const;
1222 
1223   /// Return true if the MachineInstr kills the specified register.
1224   /// If TargetRegisterInfo is passed, then it also checks if there is
1225   /// a kill of a super-register.
1226   bool killsRegister(Register Reg,
1227                      const TargetRegisterInfo *TRI = nullptr) const {
1228     return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
1229   }
1230 
1231   /// Return true if the MachineInstr fully defines the specified register.
1232   /// If TargetRegisterInfo is passed, then it also checks
1233   /// if there is a def of a super-register.
1234   /// NOTE: It's ignoring subreg indices on virtual registers.
1235   bool definesRegister(Register Reg,
1236                        const TargetRegisterInfo *TRI = nullptr) const {
1237     return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
1238   }
1239 
1240   /// Return true if the MachineInstr modifies (fully define or partially
1241   /// define) the specified register.
1242   /// NOTE: It's ignoring subreg indices on virtual registers.
1243   bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const {
1244     return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
1245   }
1246 
1247   /// Returns true if the register is dead in this machine instruction.
1248   /// If TargetRegisterInfo is passed, then it also checks
1249   /// if there is a dead def of a super-register.
1250   bool registerDefIsDead(Register Reg,
1251                          const TargetRegisterInfo *TRI = nullptr) const {
1252     return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
1253   }
1254 
1255   /// Returns true if the MachineInstr has an implicit-use operand of exactly
1256   /// the given register (not considering sub/super-registers).
1257   bool hasRegisterImplicitUseOperand(Register Reg) const;
1258 
1259   /// Returns the operand index that is a use of the specific register or -1
1260   /// if it is not found. It further tightens the search criteria to a use
1261   /// that kills the register if isKill is true.
1262   int findRegisterUseOperandIdx(Register Reg, bool isKill = false,
1263                                 const TargetRegisterInfo *TRI = nullptr) const;
1264 
1265   /// Wrapper for findRegisterUseOperandIdx, it returns
1266   /// a pointer to the MachineOperand rather than an index.
1267   MachineOperand *findRegisterUseOperand(Register Reg, bool isKill = false,
1268                                       const TargetRegisterInfo *TRI = nullptr) {
1269     int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
1270     return (Idx == -1) ? nullptr : &getOperand(Idx);
1271   }
1272 
1273   const MachineOperand *findRegisterUseOperand(
1274     Register Reg, bool isKill = false,
1275     const TargetRegisterInfo *TRI = nullptr) const {
1276     return const_cast<MachineInstr *>(this)->
1277       findRegisterUseOperand(Reg, isKill, TRI);
1278   }
1279 
1280   /// Returns the operand index that is a def of the specified register or
1281   /// -1 if it is not found. If isDead is true, defs that are not dead are
1282   /// skipped. If Overlap is true, then it also looks for defs that merely
1283   /// overlap the specified register. If TargetRegisterInfo is non-null,
1284   /// then it also checks if there is a def of a super-register.
1285   /// This may also return a register mask operand when Overlap is true.
1286   int findRegisterDefOperandIdx(Register Reg,
1287                                 bool isDead = false, bool Overlap = false,
1288                                 const TargetRegisterInfo *TRI = nullptr) const;
1289 
1290   /// Wrapper for findRegisterDefOperandIdx, it returns
1291   /// a pointer to the MachineOperand rather than an index.
1292   MachineOperand *
1293   findRegisterDefOperand(Register Reg, bool isDead = false,
1294                          bool Overlap = false,
1295                          const TargetRegisterInfo *TRI = nullptr) {
1296     int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI);
1297     return (Idx == -1) ? nullptr : &getOperand(Idx);
1298   }
1299 
1300   const MachineOperand *
1301   findRegisterDefOperand(Register Reg, bool isDead = false,
1302                          bool Overlap = false,
1303                          const TargetRegisterInfo *TRI = nullptr) const {
1304     return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
1305         Reg, isDead, Overlap, TRI);
1306   }
1307 
1308   /// Find the index of the first operand in the
1309   /// operand list that is used to represent the predicate. It returns -1 if
1310   /// none is found.
1311   int findFirstPredOperandIdx() const;
1312 
1313   /// Find the index of the flag word operand that
1314   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
1315   /// getOperand(OpIdx) does not belong to an inline asm operand group.
1316   ///
1317   /// If GroupNo is not NULL, it will receive the number of the operand group
1318   /// containing OpIdx.
1319   ///
1320   /// The flag operand is an immediate that can be decoded with methods like
1321   /// InlineAsm::hasRegClassConstraint().
1322   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1323 
1324   /// Compute the static register class constraint for operand OpIdx.
1325   /// For normal instructions, this is derived from the MCInstrDesc.
1326   /// For inline assembly it is derived from the flag words.
1327   ///
1328   /// Returns NULL if the static register class constraint cannot be
1329   /// determined.
1330   const TargetRegisterClass*
1331   getRegClassConstraint(unsigned OpIdx,
1332                         const TargetInstrInfo *TII,
1333                         const TargetRegisterInfo *TRI) const;
1334 
1335   /// Applies the constraints (def/use) implied by this MI on \p Reg to
1336   /// the given \p CurRC.
1337   /// If \p ExploreBundle is set and MI is part of a bundle, all the
1338   /// instructions inside the bundle will be taken into account. In other words,
1339   /// this method accumulates all the constraints of the operand of this MI and
1340   /// the related bundle if MI is a bundle or inside a bundle.
1341   ///
1342   /// Returns the register class that satisfies both \p CurRC and the
1343   /// constraints set by MI. Returns NULL if such a register class does not
1344   /// exist.
1345   ///
1346   /// \pre CurRC must not be NULL.
1347   const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1348       Register Reg, const TargetRegisterClass *CurRC,
1349       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1350       bool ExploreBundle = false) const;
1351 
1352   /// Applies the constraints (def/use) implied by the \p OpIdx operand
1353   /// to the given \p CurRC.
1354   ///
1355   /// Returns the register class that satisfies both \p CurRC and the
1356   /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1357   /// does not exist.
1358   ///
1359   /// \pre CurRC must not be NULL.
1360   /// \pre The operand at \p OpIdx must be a register.
1361   const TargetRegisterClass *
1362   getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1363                               const TargetInstrInfo *TII,
1364                               const TargetRegisterInfo *TRI) const;
1365 
1366   /// Add a tie between the register operands at DefIdx and UseIdx.
1367   /// The tie will cause the register allocator to ensure that the two
1368   /// operands are assigned the same physical register.
1369   ///
1370   /// Tied operands are managed automatically for explicit operands in the
1371   /// MCInstrDesc. This method is for exceptional cases like inline asm.
1372   void tieOperands(unsigned DefIdx, unsigned UseIdx);
1373 
1374   /// Given the index of a tied register operand, find the
1375   /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1376   /// index of the tied operand which must exist.
1377   unsigned findTiedOperandIdx(unsigned OpIdx) const;
1378 
1379   /// Given the index of a register def operand,
1380   /// check if the register def is tied to a source operand, due to either
1381   /// two-address elimination or inline assembly constraints. Returns the
1382   /// first tied use operand index by reference if UseOpIdx is not null.
1383   bool isRegTiedToUseOperand(unsigned DefOpIdx,
1384                              unsigned *UseOpIdx = nullptr) const {
1385     const MachineOperand &MO = getOperand(DefOpIdx);
1386     if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1387       return false;
1388     if (UseOpIdx)
1389       *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1390     return true;
1391   }
1392 
1393   /// Return true if the use operand of the specified index is tied to a def
1394   /// operand. It also returns the def operand index by reference if DefOpIdx
1395   /// is not null.
1396   bool isRegTiedToDefOperand(unsigned UseOpIdx,
1397                              unsigned *DefOpIdx = nullptr) const {
1398     const MachineOperand &MO = getOperand(UseOpIdx);
1399     if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1400       return false;
1401     if (DefOpIdx)
1402       *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1403     return true;
1404   }
1405 
1406   /// Clears kill flags on all operands.
1407   void clearKillInfo();
1408 
1409   /// Replace all occurrences of FromReg with ToReg:SubIdx,
1410   /// properly composing subreg indices where necessary.
1411   void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx,
1412                           const TargetRegisterInfo &RegInfo);
1413 
1414   /// We have determined MI kills a register. Look for the
1415   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1416   /// add a implicit operand if it's not found. Returns true if the operand
1417   /// exists / is added.
1418   bool addRegisterKilled(Register IncomingReg,
1419                          const TargetRegisterInfo *RegInfo,
1420                          bool AddIfNotFound = false);
1421 
1422   /// Clear all kill flags affecting Reg.  If RegInfo is provided, this includes
1423   /// all aliasing registers.
1424   void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo);
1425 
1426   /// We have determined MI defined a register without a use.
1427   /// Look for the operand that defines it and mark it as IsDead. If
1428   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1429   /// true if the operand exists / is added.
1430   bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo,
1431                        bool AddIfNotFound = false);
1432 
1433   /// Clear all dead flags on operands defining register @p Reg.
1434   void clearRegisterDeads(Register Reg);
1435 
1436   /// Mark all subregister defs of register @p Reg with the undef flag.
1437   /// This function is used when we determined to have a subregister def in an
1438   /// otherwise undefined super register.
1439   void setRegisterDefReadUndef(Register Reg, bool IsUndef = true);
1440 
1441   /// We have determined MI defines a register. Make sure there is an operand
1442   /// defining Reg.
1443   void addRegisterDefined(Register Reg,
1444                           const TargetRegisterInfo *RegInfo = nullptr);
1445 
1446   /// Mark every physreg used by this instruction as
1447   /// dead except those in the UsedRegs list.
1448   ///
1449   /// On instructions with register mask operands, also add implicit-def
1450   /// operands for all registers in UsedRegs.
1451   void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
1452                              const TargetRegisterInfo &TRI);
1453 
1454   /// Return true if it is safe to move this instruction. If
1455   /// SawStore is set to true, it means that there is a store (or call) between
1456   /// the instruction's location and its intended destination.
1457   bool isSafeToMove(AAResults *AA, bool &SawStore) const;
1458 
1459   /// Returns true if this instruction's memory access aliases the memory
1460   /// access of Other.
1461   //
1462   /// Assumes any physical registers used to compute addresses
1463   /// have the same value for both instructions.  Returns false if neither
1464   /// instruction writes to memory.
1465   ///
1466   /// @param AA Optional alias analysis, used to compare memory operands.
1467   /// @param Other MachineInstr to check aliasing against.
1468   /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1469   bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const;
1470 
1471   /// Return true if this instruction may have an ordered
1472   /// or volatile memory reference, or if the information describing the memory
1473   /// reference is not available. Return false if it is known to have no
1474   /// ordered or volatile memory references.
1475   bool hasOrderedMemoryRef() const;
1476 
1477   /// Return true if this load instruction never traps and points to a memory
1478   /// location whose value doesn't change during the execution of this function.
1479   ///
1480   /// Examples include loading a value from the constant pool or from the
1481   /// argument area of a function (if it does not change).  If the instruction
1482   /// does multiple loads, this returns true only if all of the loads are
1483   /// dereferenceable and invariant.
1484   bool isDereferenceableInvariantLoad(AAResults *AA) const;
1485 
1486   /// If the specified instruction is a PHI that always merges together the
1487   /// same virtual register, return the register, otherwise return 0.
1488   unsigned isConstantValuePHI() const;
1489 
1490   /// Return true if this instruction has side effects that are not modeled
1491   /// by mayLoad / mayStore, etc.
1492   /// For all instructions, the property is encoded in MCInstrDesc::Flags
1493   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1494   /// INLINEASM instruction, in which case the side effect property is encoded
1495   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1496   ///
1497   bool hasUnmodeledSideEffects() const;
1498 
1499   /// Returns true if it is illegal to fold a load across this instruction.
1500   bool isLoadFoldBarrier() const;
1501 
1502   /// Return true if all the defs of this instruction are dead.
1503   bool allDefsAreDead() const;
1504 
1505   /// Return a valid size if the instruction is a spill instruction.
1506   Optional<unsigned> getSpillSize(const TargetInstrInfo *TII) const;
1507 
1508   /// Return a valid size if the instruction is a folded spill instruction.
1509   Optional<unsigned> getFoldedSpillSize(const TargetInstrInfo *TII) const;
1510 
1511   /// Return a valid size if the instruction is a restore instruction.
1512   Optional<unsigned> getRestoreSize(const TargetInstrInfo *TII) const;
1513 
1514   /// Return a valid size if the instruction is a folded restore instruction.
1515   Optional<unsigned>
1516   getFoldedRestoreSize(const TargetInstrInfo *TII) const;
1517 
1518   /// Copy implicit register operands from specified
1519   /// instruction to this instruction.
1520   void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1521 
1522   /// Debugging support
1523   /// @{
1524   /// Determine the generic type to be printed (if needed) on uses and defs.
1525   LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1526                      const MachineRegisterInfo &MRI) const;
1527 
1528   /// Return true when an instruction has tied register that can't be determined
1529   /// by the instruction's descriptor. This is useful for MIR printing, to
1530   /// determine whether we need to print the ties or not.
1531   bool hasComplexRegisterTies() const;
1532 
1533   /// Print this MI to \p OS.
1534   /// Don't print information that can be inferred from other instructions if
1535   /// \p IsStandalone is false. It is usually true when only a fragment of the
1536   /// function is printed.
1537   /// Only print the defs and the opcode if \p SkipOpers is true.
1538   /// Otherwise, also print operands if \p SkipDebugLoc is true.
1539   /// Otherwise, also print the debug loc, with a terminating newline.
1540   /// \p TII is used to print the opcode name.  If it's not present, but the
1541   /// MI is in a function, the opcode will be printed using the function's TII.
1542   void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1543              bool SkipDebugLoc = false, bool AddNewLine = true,
1544              const TargetInstrInfo *TII = nullptr) const;
1545   void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1546              bool SkipOpers = false, bool SkipDebugLoc = false,
1547              bool AddNewLine = true,
1548              const TargetInstrInfo *TII = nullptr) const;
1549   void dump() const;
1550   /// Print on dbgs() the current instruction and the instructions defining its
1551   /// operands and so on until we reach \p MaxDepth.
1552   void dumpr(const MachineRegisterInfo &MRI,
1553              unsigned MaxDepth = UINT_MAX) const;
1554   /// @}
1555 
1556   //===--------------------------------------------------------------------===//
1557   // Accessors used to build up machine instructions.
1558 
1559   /// Add the specified operand to the instruction.  If it is an implicit
1560   /// operand, it is added to the end of the operand list.  If it is an
1561   /// explicit operand it is added at the end of the explicit operand list
1562   /// (before the first implicit operand).
1563   ///
1564   /// MF must be the machine function that was used to allocate this
1565   /// instruction.
1566   ///
1567   /// MachineInstrBuilder provides a more convenient interface for creating
1568   /// instructions and adding operands.
1569   void addOperand(MachineFunction &MF, const MachineOperand &Op);
1570 
1571   /// Add an operand without providing an MF reference. This only works for
1572   /// instructions that are inserted in a basic block.
1573   ///
1574   /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1575   /// preferred.
1576   void addOperand(const MachineOperand &Op);
1577 
1578   /// Replace the instruction descriptor (thus opcode) of
1579   /// the current instruction with a new one.
1580   void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1581 
1582   /// Replace current source information with new such.
1583   /// Avoid using this, the constructor argument is preferable.
1584   void setDebugLoc(DebugLoc dl) {
1585     debugLoc = std::move(dl);
1586     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1587   }
1588 
1589   /// Erase an operand from an instruction, leaving it with one
1590   /// fewer operand than it started with.
1591   void RemoveOperand(unsigned OpNo);
1592 
1593   /// Clear this MachineInstr's memory reference descriptor list.  This resets
1594   /// the memrefs to their most conservative state.  This should be used only
1595   /// as a last resort since it greatly pessimizes our knowledge of the memory
1596   /// access performed by the instruction.
1597   void dropMemRefs(MachineFunction &MF);
1598 
1599   /// Assign this MachineInstr's memory reference descriptor list.
1600   ///
1601   /// Unlike other methods, this *will* allocate them into a new array
1602   /// associated with the provided `MachineFunction`.
1603   void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
1604 
1605   /// Add a MachineMemOperand to the machine instruction.
1606   /// This function should be used only occasionally. The setMemRefs function
1607   /// is the primary method for setting up a MachineInstr's MemRefs list.
1608   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1609 
1610   /// Clone another MachineInstr's memory reference descriptor list and replace
1611   /// ours with it.
1612   ///
1613   /// Note that `*this` may be the incoming MI!
1614   ///
1615   /// Prefer this API whenever possible as it can avoid allocations in common
1616   /// cases.
1617   void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
1618 
1619   /// Clone the merge of multiple MachineInstrs' memory reference descriptors
1620   /// list and replace ours with it.
1621   ///
1622   /// Note that `*this` may be one of the incoming MIs!
1623   ///
1624   /// Prefer this API whenever possible as it can avoid allocations in common
1625   /// cases.
1626   void cloneMergedMemRefs(MachineFunction &MF,
1627                           ArrayRef<const MachineInstr *> MIs);
1628 
1629   /// Set a symbol that will be emitted just prior to the instruction itself.
1630   ///
1631   /// Setting this to a null pointer will remove any such symbol.
1632   ///
1633   /// FIXME: This is not fully implemented yet.
1634   void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1635 
1636   /// Set a symbol that will be emitted just after the instruction itself.
1637   ///
1638   /// Setting this to a null pointer will remove any such symbol.
1639   ///
1640   /// FIXME: This is not fully implemented yet.
1641   void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1642 
1643   /// Clone another MachineInstr's pre- and post- instruction symbols and
1644   /// replace ours with it.
1645   void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
1646 
1647   /// Set a marker on instructions that denotes where we should create and emit
1648   /// heap alloc site labels. This waits until after instruction selection and
1649   /// optimizations to create the label, so it should still work if the
1650   /// instruction is removed or duplicated.
1651   void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
1652 
1653   /// Return the MIFlags which represent both MachineInstrs. This
1654   /// should be used when merging two MachineInstrs into one. This routine does
1655   /// not modify the MIFlags of this MachineInstr.
1656   uint16_t mergeFlagsWith(const MachineInstr& Other) const;
1657 
1658   static uint16_t copyFlagsFromInstruction(const Instruction &I);
1659 
1660   /// Copy all flags to MachineInst MIFlags
1661   void copyIRFlags(const Instruction &I);
1662 
1663   /// Break any tie involving OpIdx.
1664   void untieRegOperand(unsigned OpIdx) {
1665     MachineOperand &MO = getOperand(OpIdx);
1666     if (MO.isReg() && MO.isTied()) {
1667       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1668       MO.TiedTo = 0;
1669     }
1670   }
1671 
1672   /// Add all implicit def and use operands to this instruction.
1673   void addImplicitDefUseOperands(MachineFunction &MF);
1674 
1675   /// Scan instructions immediately following MI and collect any matching
1676   /// DBG_VALUEs.
1677   void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
1678 
1679   /// Find all DBG_VALUEs that point to the register def in this instruction
1680   /// and point them to \p Reg instead.
1681   void changeDebugValuesDefReg(Register Reg);
1682 
1683   /// Returns the Intrinsic::ID for this instruction.
1684   /// \pre Must have an intrinsic ID operand.
1685   unsigned getIntrinsicID() const {
1686     return getOperand(getNumExplicitDefs()).getIntrinsicID();
1687   }
1688 
1689 private:
1690   /// If this instruction is embedded into a MachineFunction, return the
1691   /// MachineRegisterInfo object for the current function, otherwise
1692   /// return null.
1693   MachineRegisterInfo *getRegInfo();
1694 
1695   /// Unlink all of the register operands in this instruction from their
1696   /// respective use lists.  This requires that the operands already be on their
1697   /// use lists.
1698   void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1699 
1700   /// Add all of the register operands in this instruction from their
1701   /// respective use lists.  This requires that the operands not be on their
1702   /// use lists yet.
1703   void AddRegOperandsToUseLists(MachineRegisterInfo&);
1704 
1705   /// Slow path for hasProperty when we're dealing with a bundle.
1706   bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
1707 
1708   /// Implements the logic of getRegClassConstraintEffectForVReg for the
1709   /// this MI and the given operand index \p OpIdx.
1710   /// If the related operand does not constrained Reg, this returns CurRC.
1711   const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1712       unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
1713       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1714 
1715   /// Stores extra instruction information inline or allocates as ExtraInfo
1716   /// based on the number of pointers.
1717   void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
1718                     MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
1719                     MDNode *HeapAllocMarker);
1720 };
1721 
1722 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1723 /// instruction rather than by pointer value.
1724 /// The hashing and equality testing functions ignore definitions so this is
1725 /// useful for CSE, etc.
1726 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1727   static inline MachineInstr *getEmptyKey() {
1728     return nullptr;
1729   }
1730 
1731   static inline MachineInstr *getTombstoneKey() {
1732     return reinterpret_cast<MachineInstr*>(-1);
1733   }
1734 
1735   static unsigned getHashValue(const MachineInstr* const &MI);
1736 
1737   static bool isEqual(const MachineInstr* const &LHS,
1738                       const MachineInstr* const &RHS) {
1739     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1740         LHS == getEmptyKey() || LHS == getTombstoneKey())
1741       return LHS == RHS;
1742     return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
1743   }
1744 };
1745 
1746 //===----------------------------------------------------------------------===//
1747 // Debugging Support
1748 
1749 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1750   MI.print(OS);
1751   return OS;
1752 }
1753 
1754 } // end namespace llvm
1755 
1756 #endif // LLVM_CODEGEN_MACHINEINSTR_H
1757