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