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