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