1 //===-- llvm/CodeGen/MachineInstr.h - MachineInstr class --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the declaration of the MachineInstr class, which is the
11 // basic representation for all target dependent machine instructions used by
12 // the back end.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
17 #define LLVM_CODEGEN_MACHINEINSTR_H
18 
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/ilist_node.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DebugLoc.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/Support/ArrayRecycler.h"
33 #include "llvm/Target/TargetOpcodes.h"
34 
35 namespace llvm {
36 
37 template <typename T> class SmallVectorImpl;
38 class TargetInstrInfo;
39 class TargetRegisterClass;
40 class TargetRegisterInfo;
41 class MachineFunction;
42 class MachineMemOperand;
43 
44 //===----------------------------------------------------------------------===//
45 /// Representation of each machine instruction.
46 ///
47 /// This class isn't a POD type, but it must have a trivial destructor. When a
48 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
49 /// without having their destructor called.
50 ///
51 class MachineInstr
52     : public ilist_node_with_parent<MachineInstr, MachineBasicBlock> {
53 public:
54   typedef MachineMemOperand **mmo_iterator;
55 
56   /// Flags to specify different kinds of comments to output in
57   /// assembly code.  These flags carry semantic information not
58   /// otherwise easily derivable from the IR text.
59   ///
60   enum CommentFlag {
61     ReloadReuse = 0x1
62   };
63 
64   enum MIFlag {
65     NoFlags      = 0,
66     FrameSetup   = 1 << 0,              // Instruction is used as a part of
67                                         // function frame setup code.
68     FrameDestroy = 1 << 1,              // Instruction is used as a part of
69                                         // function frame destruction code.
70     BundledPred  = 1 << 2,              // Instruction has bundled predecessors.
71     BundledSucc  = 1 << 3               // Instruction has bundled successors.
72   };
73 private:
74   const MCInstrDesc *MCID;              // Instruction descriptor.
75   MachineBasicBlock *Parent;            // Pointer to the owning basic block.
76 
77   // Operands are allocated by an ArrayRecycler.
78   MachineOperand *Operands;             // Pointer to the first operand.
79   unsigned NumOperands;                 // Number of operands on instruction.
80   typedef ArrayRecycler<MachineOperand>::Capacity OperandCapacity;
81   OperandCapacity CapOperands;          // Capacity of the Operands array.
82 
83   uint8_t Flags;                        // Various bits of additional
84                                         // information about machine
85                                         // instruction.
86 
87   uint8_t AsmPrinterFlags;              // Various bits of information used by
88                                         // the AsmPrinter to emit helpful
89                                         // comments.  This is *not* semantic
90                                         // information.  Do not use this for
91                                         // anything other than to convey comment
92                                         // information to AsmPrinter.
93 
94   uint8_t NumMemRefs;                   // Information on memory references.
95   // Note that MemRefs == nullptr,  means 'don't know', not 'no memory access'.
96   // Calling code must treat missing information conservatively.  If the number
97   // of memory operands required to be precise exceeds the maximum value of
98   // NumMemRefs - currently 256 - we remove the operands entirely. Note also
99   // that this is a non-owning reference to a shared copy on write buffer owned
100   // by the MachineFunction and created via MF.allocateMemRefsArray.
101   mmo_iterator MemRefs;
102 
103   DebugLoc debugLoc;                    // Source line information.
104 
105   MachineInstr(const MachineInstr&) = delete;
106   void operator=(const MachineInstr&) = delete;
107   // Use MachineFunction::DeleteMachineInstr() instead.
108   ~MachineInstr() = delete;
109 
110   // Intrusive list support
111   friend struct ilist_traits<MachineInstr>;
112   friend struct ilist_traits<MachineBasicBlock>;
113   void setParent(MachineBasicBlock *P) { Parent = P; }
114 
115   /// This constructor creates a copy of the given
116   /// MachineInstr in the given MachineFunction.
117   MachineInstr(MachineFunction &, const MachineInstr &);
118 
119   /// This constructor create a MachineInstr and add the implicit operands.
120   /// It reserves space for number of operands specified by
121   /// MCInstrDesc.  An explicit DebugLoc is supplied.
122   MachineInstr(MachineFunction &, const MCInstrDesc &MCID, DebugLoc dl,
123                bool NoImp = false);
124 
125   // MachineInstrs are pool-allocated and owned by MachineFunction.
126   friend class MachineFunction;
127 
128 public:
129   const MachineBasicBlock* getParent() const { return Parent; }
130   MachineBasicBlock* getParent() { return Parent; }
131 
132   /// Return the asm printer flags bitvector.
133   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
134 
135   /// Clear the AsmPrinter bitvector.
136   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
137 
138   /// Return whether an AsmPrinter flag is set.
139   bool getAsmPrinterFlag(CommentFlag Flag) const {
140     return AsmPrinterFlags & Flag;
141   }
142 
143   /// Set a flag for the AsmPrinter.
144   void setAsmPrinterFlag(CommentFlag Flag) {
145     AsmPrinterFlags |= (uint8_t)Flag;
146   }
147 
148   /// Clear specific AsmPrinter flags.
149   void clearAsmPrinterFlag(CommentFlag Flag) {
150     AsmPrinterFlags &= ~Flag;
151   }
152 
153   /// Return the MI flags bitvector.
154   uint8_t getFlags() const {
155     return Flags;
156   }
157 
158   /// Return whether an MI flag is set.
159   bool getFlag(MIFlag Flag) const {
160     return Flags & Flag;
161   }
162 
163   /// Set a MI flag.
164   void setFlag(MIFlag Flag) {
165     Flags |= (uint8_t)Flag;
166   }
167 
168   void setFlags(unsigned flags) {
169     // Filter out the automatically maintained flags.
170     unsigned Mask = BundledPred | BundledSucc;
171     Flags = (Flags & Mask) | (flags & ~Mask);
172   }
173 
174   /// clearFlag - Clear a MI flag.
175   void clearFlag(MIFlag Flag) {
176     Flags &= ~((uint8_t)Flag);
177   }
178 
179   /// Return true if MI is in a bundle (but not the first MI in a bundle).
180   ///
181   /// A bundle looks like this before it's finalized:
182   ///   ----------------
183   ///   |      MI      |
184   ///   ----------------
185   ///          |
186   ///   ----------------
187   ///   |      MI    * |
188   ///   ----------------
189   ///          |
190   ///   ----------------
191   ///   |      MI    * |
192   ///   ----------------
193   /// In this case, the first MI starts a bundle but is not inside a bundle, the
194   /// next 2 MIs are considered "inside" the bundle.
195   ///
196   /// After a bundle is finalized, it looks like this:
197   ///   ----------------
198   ///   |    Bundle    |
199   ///   ----------------
200   ///          |
201   ///   ----------------
202   ///   |      MI    * |
203   ///   ----------------
204   ///          |
205   ///   ----------------
206   ///   |      MI    * |
207   ///   ----------------
208   ///          |
209   ///   ----------------
210   ///   |      MI    * |
211   ///   ----------------
212   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
213   /// a bundle, but the next three MIs are.
214   bool isInsideBundle() const {
215     return getFlag(BundledPred);
216   }
217 
218   /// Return true if this instruction part of a bundle. This is true
219   /// if either itself or its following instruction is marked "InsideBundle".
220   bool isBundled() const {
221     return isBundledWithPred() || isBundledWithSucc();
222   }
223 
224   /// Return true if this instruction is part of a bundle, and it is not the
225   /// first instruction in the bundle.
226   bool isBundledWithPred() const { return getFlag(BundledPred); }
227 
228   /// Return true if this instruction is part of a bundle, and it is not the
229   /// last instruction in the bundle.
230   bool isBundledWithSucc() const { return getFlag(BundledSucc); }
231 
232   /// Bundle this instruction with its predecessor. This can be an unbundled
233   /// instruction, or it can be the first instruction in a bundle.
234   void bundleWithPred();
235 
236   /// Bundle this instruction with its successor. This can be an unbundled
237   /// instruction, or it can be the last instruction in a bundle.
238   void bundleWithSucc();
239 
240   /// Break bundle above this instruction.
241   void unbundleFromPred();
242 
243   /// Break bundle below this instruction.
244   void unbundleFromSucc();
245 
246   /// Returns the debug location id of this MachineInstr.
247   const DebugLoc &getDebugLoc() const { return debugLoc; }
248 
249   /// Return the debug variable referenced by
250   /// this DBG_VALUE instruction.
251   const DILocalVariable *getDebugVariable() const {
252     assert(isDebugValue() && "not a DBG_VALUE");
253     return cast<DILocalVariable>(getOperand(2).getMetadata());
254   }
255 
256   /// Return the complex address expression referenced by
257   /// this DBG_VALUE instruction.
258   const DIExpression *getDebugExpression() const {
259     assert(isDebugValue() && "not a DBG_VALUE");
260     return cast<DIExpression>(getOperand(3).getMetadata());
261   }
262 
263   /// Emit an error referring to the source location of this instruction.
264   /// This should only be used for inline assembly that is somehow
265   /// impossible to compile. Other errors should have been handled much
266   /// earlier.
267   ///
268   /// If this method returns, the caller should try to recover from the error.
269   ///
270   void emitError(StringRef Msg) const;
271 
272   /// Returns the target instruction descriptor of this MachineInstr.
273   const MCInstrDesc &getDesc() const { return *MCID; }
274 
275   /// Returns the opcode of this MachineInstr.
276   unsigned getOpcode() const { return MCID->Opcode; }
277 
278   /// Access to explicit operands of the instruction.
279   ///
280   unsigned getNumOperands() const { return NumOperands; }
281 
282   const MachineOperand& getOperand(unsigned i) const {
283     assert(i < getNumOperands() && "getOperand() out of range!");
284     return Operands[i];
285   }
286   MachineOperand& getOperand(unsigned i) {
287     assert(i < getNumOperands() && "getOperand() out of range!");
288     return Operands[i];
289   }
290 
291   /// Returns the number of non-implicit operands.
292   unsigned getNumExplicitOperands() const;
293 
294   /// iterator/begin/end - Iterate over all operands of a machine instruction.
295   typedef MachineOperand *mop_iterator;
296   typedef const MachineOperand *const_mop_iterator;
297 
298   mop_iterator operands_begin() { return Operands; }
299   mop_iterator operands_end() { return Operands + NumOperands; }
300 
301   const_mop_iterator operands_begin() const { return Operands; }
302   const_mop_iterator operands_end() const { return Operands + NumOperands; }
303 
304   iterator_range<mop_iterator> operands() {
305     return make_range(operands_begin(), operands_end());
306   }
307   iterator_range<const_mop_iterator> operands() const {
308     return make_range(operands_begin(), operands_end());
309   }
310   iterator_range<mop_iterator> explicit_operands() {
311     return make_range(operands_begin(),
312                       operands_begin() + getNumExplicitOperands());
313   }
314   iterator_range<const_mop_iterator> explicit_operands() const {
315     return make_range(operands_begin(),
316                       operands_begin() + getNumExplicitOperands());
317   }
318   iterator_range<mop_iterator> implicit_operands() {
319     return make_range(explicit_operands().end(), operands_end());
320   }
321   iterator_range<const_mop_iterator> implicit_operands() const {
322     return make_range(explicit_operands().end(), operands_end());
323   }
324   /// Returns a range over all explicit operands that are register definitions.
325   /// Implicit definition are not included!
326   iterator_range<mop_iterator> defs() {
327     return make_range(operands_begin(),
328                       operands_begin() + getDesc().getNumDefs());
329   }
330   /// \copydoc defs()
331   iterator_range<const_mop_iterator> defs() const {
332     return make_range(operands_begin(),
333                       operands_begin() + getDesc().getNumDefs());
334   }
335   /// Returns a range that includes all operands that are register uses.
336   /// This may include unrelated operands which are not register uses.
337   iterator_range<mop_iterator> uses() {
338     return make_range(operands_begin() + getDesc().getNumDefs(),
339                       operands_end());
340   }
341   /// \copydoc uses()
342   iterator_range<const_mop_iterator> uses() const {
343     return make_range(operands_begin() + getDesc().getNumDefs(),
344                       operands_end());
345   }
346   iterator_range<mop_iterator> explicit_uses() {
347     return make_range(operands_begin() + getDesc().getNumDefs(),
348                       operands_begin() + getNumExplicitOperands() );
349   }
350   iterator_range<const_mop_iterator> explicit_uses() const {
351     return make_range(operands_begin() + getDesc().getNumDefs(),
352                       operands_begin() + getNumExplicitOperands() );
353   }
354 
355   /// Returns the number of the operand iterator \p I points to.
356   unsigned getOperandNo(const_mop_iterator I) const {
357     return I - operands_begin();
358   }
359 
360   /// Access to memory operands of the instruction
361   mmo_iterator memoperands_begin() const { return MemRefs; }
362   mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
363   /// Return true if we don't have any memory operands which described the the
364   /// memory access done by this instruction.  If this is true, calling code
365   /// must be conservative.
366   bool memoperands_empty() const { return NumMemRefs == 0; }
367 
368   iterator_range<mmo_iterator>  memoperands() {
369     return make_range(memoperands_begin(), memoperands_end());
370   }
371   iterator_range<mmo_iterator> memoperands() const {
372     return make_range(memoperands_begin(), memoperands_end());
373   }
374 
375   /// Return true if this instruction has exactly one MachineMemOperand.
376   bool hasOneMemOperand() const {
377     return NumMemRefs == 1;
378   }
379 
380   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
381   /// queries but they are bundle aware.
382 
383   enum QueryType {
384     IgnoreBundle,    // Ignore bundles
385     AnyInBundle,     // Return true if any instruction in bundle has property
386     AllInBundle      // Return true if all instructions in bundle have property
387   };
388 
389   /// Return true if the instruction (or in the case of a bundle,
390   /// the instructions inside the bundle) has the specified property.
391   /// The first argument is the property being queried.
392   /// The second argument indicates whether the query should look inside
393   /// instruction bundles.
394   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
395     // Inline the fast path for unbundled or bundle-internal instructions.
396     if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
397       return getDesc().getFlags() & (1 << MCFlag);
398 
399     // If this is the first instruction in a bundle, take the slow path.
400     return hasPropertyInBundle(1 << MCFlag, Type);
401   }
402 
403   /// Return true if this instruction can have a variable number of operands.
404   /// In this case, the variable operands will be after the normal
405   /// operands but before the implicit definitions and uses (if any are
406   /// present).
407   bool isVariadic(QueryType Type = IgnoreBundle) const {
408     return hasProperty(MCID::Variadic, Type);
409   }
410 
411   /// Set if this instruction has an optional definition, e.g.
412   /// ARM instructions which can set condition code if 's' bit is set.
413   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
414     return hasProperty(MCID::HasOptionalDef, Type);
415   }
416 
417   /// Return true if this is a pseudo instruction that doesn't
418   /// correspond to a real machine instruction.
419   bool isPseudo(QueryType Type = IgnoreBundle) const {
420     return hasProperty(MCID::Pseudo, Type);
421   }
422 
423   bool isReturn(QueryType Type = AnyInBundle) const {
424     return hasProperty(MCID::Return, Type);
425   }
426 
427   bool isCall(QueryType Type = AnyInBundle) const {
428     return hasProperty(MCID::Call, Type);
429   }
430 
431   /// Returns true if the specified instruction stops control flow
432   /// from executing the instruction immediately following it.  Examples include
433   /// unconditional branches and return instructions.
434   bool isBarrier(QueryType Type = AnyInBundle) const {
435     return hasProperty(MCID::Barrier, Type);
436   }
437 
438   /// Returns true if this instruction part of the terminator for a basic block.
439   /// Typically this is things like return and branch instructions.
440   ///
441   /// Various passes use this to insert code into the bottom of a basic block,
442   /// but before control flow occurs.
443   bool isTerminator(QueryType Type = AnyInBundle) const {
444     return hasProperty(MCID::Terminator, Type);
445   }
446 
447   /// Returns true if this is a conditional, unconditional, or indirect branch.
448   /// Predicates below can be used to discriminate between
449   /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
450   /// get more information.
451   bool isBranch(QueryType Type = AnyInBundle) const {
452     return hasProperty(MCID::Branch, Type);
453   }
454 
455   /// Return true if this is an indirect branch, such as a
456   /// branch through a register.
457   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
458     return hasProperty(MCID::IndirectBranch, Type);
459   }
460 
461   /// Return true if this is a branch which may fall
462   /// through to the next instruction or may transfer control flow to some other
463   /// block.  The TargetInstrInfo::AnalyzeBranch method can be used to get more
464   /// information about this branch.
465   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
466     return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
467   }
468 
469   /// Return true if this is a branch which always
470   /// transfers control flow to some other block.  The
471   /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
472   /// about this branch.
473   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
474     return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
475   }
476 
477   /// Return true if this instruction has a predicate operand that
478   /// controls execution.  It may be set to 'always', or may be set to other
479   /// values.   There are various methods in TargetInstrInfo that can be used to
480   /// control and modify the predicate in this instruction.
481   bool isPredicable(QueryType Type = AllInBundle) const {
482     // If it's a bundle than all bundled instructions must be predicable for this
483     // to return true.
484     return hasProperty(MCID::Predicable, Type);
485   }
486 
487   /// Return true if this instruction is a comparison.
488   bool isCompare(QueryType Type = IgnoreBundle) const {
489     return hasProperty(MCID::Compare, Type);
490   }
491 
492   /// Return true if this instruction is a move immediate
493   /// (including conditional moves) instruction.
494   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
495     return hasProperty(MCID::MoveImm, Type);
496   }
497 
498   /// Return true if this instruction is a bitcast instruction.
499   bool isBitcast(QueryType Type = IgnoreBundle) const {
500     return hasProperty(MCID::Bitcast, Type);
501   }
502 
503   /// Return true if this instruction is a select instruction.
504   bool isSelect(QueryType Type = IgnoreBundle) const {
505     return hasProperty(MCID::Select, Type);
506   }
507 
508   /// Return true if this instruction cannot be safely duplicated.
509   /// For example, if the instruction has a unique labels attached
510   /// to it, duplicating it would cause multiple definition errors.
511   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
512     return hasProperty(MCID::NotDuplicable, Type);
513   }
514 
515   /// Return true if this instruction is convergent.
516   /// Convergent instructions can not be made control-dependent on any
517   /// additional values.
518   bool isConvergent(QueryType Type = AnyInBundle) const {
519     return hasProperty(MCID::Convergent, Type);
520   }
521 
522   /// Returns true if the specified instruction has a delay slot
523   /// which must be filled by the code generator.
524   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
525     return hasProperty(MCID::DelaySlot, Type);
526   }
527 
528   /// Return true for instructions that can be folded as
529   /// memory operands in other instructions. The most common use for this
530   /// is instructions that are simple loads from memory that don't modify
531   /// the loaded value in any way, but it can also be used for instructions
532   /// that can be expressed as constant-pool loads, such as V_SETALLONES
533   /// on x86, to allow them to be folded when it is beneficial.
534   /// This should only be set on instructions that return a value in their
535   /// only virtual register definition.
536   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
537     return hasProperty(MCID::FoldableAsLoad, Type);
538   }
539 
540   /// \brief Return true if this instruction behaves
541   /// the same way as the generic REG_SEQUENCE instructions.
542   /// E.g., on ARM,
543   /// dX VMOVDRR rY, rZ
544   /// is equivalent to
545   /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
546   ///
547   /// Note that for the optimizers to be able to take advantage of
548   /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
549   /// override accordingly.
550   bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
551     return hasProperty(MCID::RegSequence, Type);
552   }
553 
554   /// \brief Return true if this instruction behaves
555   /// the same way as the generic EXTRACT_SUBREG instructions.
556   /// E.g., on ARM,
557   /// rX, rY VMOVRRD dZ
558   /// is equivalent to two EXTRACT_SUBREG:
559   /// rX = EXTRACT_SUBREG dZ, ssub_0
560   /// rY = EXTRACT_SUBREG dZ, ssub_1
561   ///
562   /// Note that for the optimizers to be able to take advantage of
563   /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
564   /// override accordingly.
565   bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
566     return hasProperty(MCID::ExtractSubreg, Type);
567   }
568 
569   /// \brief Return true if this instruction behaves
570   /// the same way as the generic INSERT_SUBREG instructions.
571   /// E.g., on ARM,
572   /// dX = VSETLNi32 dY, rZ, Imm
573   /// is equivalent to a INSERT_SUBREG:
574   /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
575   ///
576   /// Note that for the optimizers to be able to take advantage of
577   /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
578   /// override accordingly.
579   bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
580     return hasProperty(MCID::InsertSubreg, Type);
581   }
582 
583   //===--------------------------------------------------------------------===//
584   // Side Effect Analysis
585   //===--------------------------------------------------------------------===//
586 
587   /// Return true if this instruction could possibly read memory.
588   /// Instructions with this flag set are not necessarily simple load
589   /// instructions, they may load a value and modify it, for example.
590   bool mayLoad(QueryType Type = AnyInBundle) const {
591     if (isInlineAsm()) {
592       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
593       if (ExtraInfo & InlineAsm::Extra_MayLoad)
594         return true;
595     }
596     return hasProperty(MCID::MayLoad, Type);
597   }
598 
599   /// Return true if this instruction could possibly modify memory.
600   /// Instructions with this flag set are not necessarily simple store
601   /// instructions, they may store a modified value based on their operands, or
602   /// may not actually modify anything, for example.
603   bool mayStore(QueryType Type = AnyInBundle) const {
604     if (isInlineAsm()) {
605       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
606       if (ExtraInfo & InlineAsm::Extra_MayStore)
607         return true;
608     }
609     return hasProperty(MCID::MayStore, Type);
610   }
611 
612   /// Return true if this instruction could possibly read or modify memory.
613   bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
614     return mayLoad(Type) || mayStore(Type);
615   }
616 
617   //===--------------------------------------------------------------------===//
618   // Flags that indicate whether an instruction can be modified by a method.
619   //===--------------------------------------------------------------------===//
620 
621   /// Return true if this may be a 2- or 3-address
622   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
623   /// result if Y and Z are exchanged.  If this flag is set, then the
624   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
625   /// instruction.
626   ///
627   /// Note that this flag may be set on instructions that are only commutable
628   /// sometimes.  In these cases, the call to commuteInstruction will fail.
629   /// Also note that some instructions require non-trivial modification to
630   /// commute them.
631   bool isCommutable(QueryType Type = IgnoreBundle) const {
632     return hasProperty(MCID::Commutable, Type);
633   }
634 
635   /// Return true if this is a 2-address instruction
636   /// which can be changed into a 3-address instruction if needed.  Doing this
637   /// transformation can be profitable in the register allocator, because it
638   /// means that the instruction can use a 2-address form if possible, but
639   /// degrade into a less efficient form if the source and dest register cannot
640   /// be assigned to the same register.  For example, this allows the x86
641   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
642   /// is the same speed as the shift but has bigger code size.
643   ///
644   /// If this returns true, then the target must implement the
645   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
646   /// is allowed to fail if the transformation isn't valid for this specific
647   /// instruction (e.g. shl reg, 4 on x86).
648   ///
649   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
650     return hasProperty(MCID::ConvertibleTo3Addr, Type);
651   }
652 
653   /// Return true if this instruction requires
654   /// custom insertion support when the DAG scheduler is inserting it into a
655   /// machine basic block.  If this is true for the instruction, it basically
656   /// means that it is a pseudo instruction used at SelectionDAG time that is
657   /// expanded out into magic code by the target when MachineInstrs are formed.
658   ///
659   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
660   /// is used to insert this into the MachineBasicBlock.
661   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
662     return hasProperty(MCID::UsesCustomInserter, Type);
663   }
664 
665   /// Return true if this instruction requires *adjustment*
666   /// after instruction selection by calling a target hook. For example, this
667   /// can be used to fill in ARM 's' optional operand depending on whether
668   /// the conditional flag register is used.
669   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
670     return hasProperty(MCID::HasPostISelHook, Type);
671   }
672 
673   /// Returns true if this instruction is a candidate for remat.
674   /// This flag is deprecated, please don't use it anymore.  If this
675   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
676   /// verify the instruction is really rematable.
677   bool isRematerializable(QueryType Type = AllInBundle) const {
678     // It's only possible to re-mat a bundle if all bundled instructions are
679     // re-materializable.
680     return hasProperty(MCID::Rematerializable, Type);
681   }
682 
683   /// Returns true if this instruction has the same cost (or less) than a move
684   /// instruction. This is useful during certain types of optimizations
685   /// (e.g., remat during two-address conversion or machine licm)
686   /// where we would like to remat or hoist the instruction, but not if it costs
687   /// more than moving the instruction into the appropriate register. Note, we
688   /// are not marking copies from and to the same register class with this flag.
689   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
690     // Only returns true for a bundle if all bundled instructions are cheap.
691     return hasProperty(MCID::CheapAsAMove, Type);
692   }
693 
694   /// Returns true if this instruction source operands
695   /// have special register allocation requirements that are not captured by the
696   /// operand register classes. e.g. ARM::STRD's two source registers must be an
697   /// even / odd pair, ARM::STM registers have to be in ascending order.
698   /// Post-register allocation passes should not attempt to change allocations
699   /// for sources of instructions with this flag.
700   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
701     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
702   }
703 
704   /// Returns true if this instruction def operands
705   /// have special register allocation requirements that are not captured by the
706   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
707   /// even / odd pair, ARM::LDM registers have to be in ascending order.
708   /// Post-register allocation passes should not attempt to change allocations
709   /// for definitions of instructions with this flag.
710   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
711     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
712   }
713 
714 
715   enum MICheckType {
716     CheckDefs,      // Check all operands for equality
717     CheckKillDead,  // Check all operands including kill / dead markers
718     IgnoreDefs,     // Ignore all definitions
719     IgnoreVRegDefs  // Ignore virtual register definitions
720   };
721 
722   /// Return true if this instruction is identical to (same
723   /// opcode and same operands as) the specified instruction.
724   bool isIdenticalTo(const MachineInstr *Other,
725                      MICheckType Check = CheckDefs) const;
726 
727   /// Unlink 'this' from the containing basic block, and return it without
728   /// deleting it.
729   ///
730   /// This function can not be used on bundled instructions, use
731   /// removeFromBundle() to remove individual instructions from a bundle.
732   MachineInstr *removeFromParent();
733 
734   /// Unlink this instruction from its basic block and return it without
735   /// deleting it.
736   ///
737   /// If the instruction is part of a bundle, the other instructions in the
738   /// bundle remain bundled.
739   MachineInstr *removeFromBundle();
740 
741   /// Unlink 'this' from the containing basic block and delete it.
742   ///
743   /// If this instruction is the header of a bundle, the whole bundle is erased.
744   /// This function can not be used for instructions inside a bundle, use
745   /// eraseFromBundle() to erase individual bundled instructions.
746   void eraseFromParent();
747 
748   /// Unlink 'this' from the containing basic block and delete it.
749   ///
750   /// For all definitions mark their uses in DBG_VALUE nodes
751   /// as undefined. Otherwise like eraseFromParent().
752   void eraseFromParentAndMarkDBGValuesForRemoval();
753 
754   /// Unlink 'this' form its basic block and delete it.
755   ///
756   /// If the instruction is part of a bundle, the other instructions in the
757   /// bundle remain bundled.
758   void eraseFromBundle();
759 
760   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
761   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
762 
763   /// Returns true if the MachineInstr represents a label.
764   bool isLabel() const { return isEHLabel() || isGCLabel(); }
765   bool isCFIInstruction() const {
766     return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
767   }
768 
769   // True if the instruction represents a position in the function.
770   bool isPosition() const { return isLabel() || isCFIInstruction(); }
771 
772   bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
773   /// A DBG_VALUE is indirect iff the first operand is a register and
774   /// the second operand is an immediate.
775   bool isIndirectDebugValue() const {
776     return isDebugValue()
777       && getOperand(0).isReg()
778       && getOperand(1).isImm();
779   }
780 
781   bool isPHI() const { return getOpcode() == TargetOpcode::PHI; }
782   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
783   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
784   bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
785   bool isMSInlineAsm() const {
786     return getOpcode() == TargetOpcode::INLINEASM && getInlineAsmDialect();
787   }
788   bool isStackAligningInlineAsm() const;
789   InlineAsm::AsmDialect getInlineAsmDialect() const;
790   bool isInsertSubreg() const {
791     return getOpcode() == TargetOpcode::INSERT_SUBREG;
792   }
793   bool isSubregToReg() const {
794     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
795   }
796   bool isRegSequence() const {
797     return getOpcode() == TargetOpcode::REG_SEQUENCE;
798   }
799   bool isBundle() const {
800     return getOpcode() == TargetOpcode::BUNDLE;
801   }
802   bool isCopy() const {
803     return getOpcode() == TargetOpcode::COPY;
804   }
805   bool isFullCopy() const {
806     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
807   }
808   bool isExtractSubreg() const {
809     return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
810   }
811 
812   /// Return true if the instruction behaves like a copy.
813   /// This does not include native copy instructions.
814   bool isCopyLike() const {
815     return isCopy() || isSubregToReg();
816   }
817 
818   /// Return true is the instruction is an identity copy.
819   bool isIdentityCopy() const {
820     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
821       getOperand(0).getSubReg() == getOperand(1).getSubReg();
822   }
823 
824   /// Return true if this is a transient instruction that is
825   /// either very likely to be eliminated during register allocation (such as
826   /// copy-like instructions), or if this instruction doesn't have an
827   /// execution-time cost.
828   bool isTransient() const {
829     switch(getOpcode()) {
830     default: return false;
831     // Copy-like instructions are usually eliminated during register allocation.
832     case TargetOpcode::PHI:
833     case TargetOpcode::COPY:
834     case TargetOpcode::INSERT_SUBREG:
835     case TargetOpcode::SUBREG_TO_REG:
836     case TargetOpcode::REG_SEQUENCE:
837     // Pseudo-instructions that don't produce any real output.
838     case TargetOpcode::IMPLICIT_DEF:
839     case TargetOpcode::KILL:
840     case TargetOpcode::CFI_INSTRUCTION:
841     case TargetOpcode::EH_LABEL:
842     case TargetOpcode::GC_LABEL:
843     case TargetOpcode::DBG_VALUE:
844       return true;
845     }
846   }
847 
848   /// Return the number of instructions inside the MI bundle, excluding the
849   /// bundle header.
850   ///
851   /// This is the number of instructions that MachineBasicBlock::iterator
852   /// skips, 0 for unbundled instructions.
853   unsigned getBundleSize() const;
854 
855   /// Return true if the MachineInstr reads the specified register.
856   /// If TargetRegisterInfo is passed, then it also checks if there
857   /// is a read of a super-register.
858   /// This does not count partial redefines of virtual registers as reads:
859   ///   %reg1024:6 = OP.
860   bool readsRegister(unsigned Reg,
861                      const TargetRegisterInfo *TRI = nullptr) const {
862     return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
863   }
864 
865   /// Return true if the MachineInstr reads the specified virtual register.
866   /// Take into account that a partial define is a
867   /// read-modify-write operation.
868   bool readsVirtualRegister(unsigned Reg) const {
869     return readsWritesVirtualRegister(Reg).first;
870   }
871 
872   /// Return a pair of bools (reads, writes) indicating if this instruction
873   /// reads or writes Reg. This also considers partial defines.
874   /// If Ops is not null, all operand indices for Reg are added.
875   std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
876                                 SmallVectorImpl<unsigned> *Ops = nullptr) const;
877 
878   /// Return true if the MachineInstr kills the specified register.
879   /// If TargetRegisterInfo is passed, then it also checks if there is
880   /// a kill of a super-register.
881   bool killsRegister(unsigned Reg,
882                      const TargetRegisterInfo *TRI = nullptr) const {
883     return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
884   }
885 
886   /// Return true if the MachineInstr fully defines the specified register.
887   /// If TargetRegisterInfo is passed, then it also checks
888   /// if there is a def of a super-register.
889   /// NOTE: It's ignoring subreg indices on virtual registers.
890   bool definesRegister(unsigned Reg,
891                        const TargetRegisterInfo *TRI = nullptr) const {
892     return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
893   }
894 
895   /// Return true if the MachineInstr modifies (fully define or partially
896   /// define) the specified register.
897   /// NOTE: It's ignoring subreg indices on virtual registers.
898   bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
899     return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
900   }
901 
902   /// Returns true if the register is dead in this machine instruction.
903   /// If TargetRegisterInfo is passed, then it also checks
904   /// if there is a dead def of a super-register.
905   bool registerDefIsDead(unsigned Reg,
906                          const TargetRegisterInfo *TRI = nullptr) const {
907     return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
908   }
909 
910   /// Returns the operand index that is a use of the specific register or -1
911   /// if it is not found. It further tightens the search criteria to a use
912   /// that kills the register if isKill is true.
913   int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
914                                 const TargetRegisterInfo *TRI = nullptr) const;
915 
916   /// Wrapper for findRegisterUseOperandIdx, it returns
917   /// a pointer to the MachineOperand rather than an index.
918   MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
919                                       const TargetRegisterInfo *TRI = nullptr) {
920     int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
921     return (Idx == -1) ? nullptr : &getOperand(Idx);
922   }
923 
924   const MachineOperand *findRegisterUseOperand(
925     unsigned Reg, bool isKill = false,
926     const TargetRegisterInfo *TRI = nullptr) const {
927     return const_cast<MachineInstr *>(this)->
928       findRegisterUseOperand(Reg, isKill, TRI);
929   }
930 
931   /// Returns the operand index that is a def of the specified register or
932   /// -1 if it is not found. If isDead is true, defs that are not dead are
933   /// skipped. If Overlap is true, then it also looks for defs that merely
934   /// overlap the specified register. If TargetRegisterInfo is non-null,
935   /// then it also checks if there is a def of a super-register.
936   /// This may also return a register mask operand when Overlap is true.
937   int findRegisterDefOperandIdx(unsigned Reg,
938                                 bool isDead = false, bool Overlap = false,
939                                 const TargetRegisterInfo *TRI = nullptr) const;
940 
941   /// Wrapper for findRegisterDefOperandIdx, it returns
942   /// a pointer to the MachineOperand rather than an index.
943   MachineOperand *findRegisterDefOperand(unsigned Reg, bool isDead = false,
944                                       const TargetRegisterInfo *TRI = nullptr) {
945     int Idx = findRegisterDefOperandIdx(Reg, isDead, false, TRI);
946     return (Idx == -1) ? nullptr : &getOperand(Idx);
947   }
948 
949   /// Find the index of the first operand in the
950   /// operand list that is used to represent the predicate. It returns -1 if
951   /// none is found.
952   int findFirstPredOperandIdx() const;
953 
954   /// Find the index of the flag word operand that
955   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
956   /// getOperand(OpIdx) does not belong to an inline asm operand group.
957   ///
958   /// If GroupNo is not NULL, it will receive the number of the operand group
959   /// containing OpIdx.
960   ///
961   /// The flag operand is an immediate that can be decoded with methods like
962   /// InlineAsm::hasRegClassConstraint().
963   ///
964   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
965 
966   /// Compute the static register class constraint for operand OpIdx.
967   /// For normal instructions, this is derived from the MCInstrDesc.
968   /// For inline assembly it is derived from the flag words.
969   ///
970   /// Returns NULL if the static register class constraint cannot be
971   /// determined.
972   ///
973   const TargetRegisterClass*
974   getRegClassConstraint(unsigned OpIdx,
975                         const TargetInstrInfo *TII,
976                         const TargetRegisterInfo *TRI) const;
977 
978   /// \brief Applies the constraints (def/use) implied by this MI on \p Reg to
979   /// the given \p CurRC.
980   /// If \p ExploreBundle is set and MI is part of a bundle, all the
981   /// instructions inside the bundle will be taken into account. In other words,
982   /// this method accumulates all the constraints of the operand of this MI and
983   /// the related bundle if MI is a bundle or inside a bundle.
984   ///
985   /// Returns the register class that satisfies both \p CurRC and the
986   /// constraints set by MI. Returns NULL if such a register class does not
987   /// exist.
988   ///
989   /// \pre CurRC must not be NULL.
990   const TargetRegisterClass *getRegClassConstraintEffectForVReg(
991       unsigned Reg, const TargetRegisterClass *CurRC,
992       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
993       bool ExploreBundle = false) const;
994 
995   /// \brief Applies the constraints (def/use) implied by the \p OpIdx operand
996   /// to the given \p CurRC.
997   ///
998   /// Returns the register class that satisfies both \p CurRC and the
999   /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1000   /// does not exist.
1001   ///
1002   /// \pre CurRC must not be NULL.
1003   /// \pre The operand at \p OpIdx must be a register.
1004   const TargetRegisterClass *
1005   getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1006                               const TargetInstrInfo *TII,
1007                               const TargetRegisterInfo *TRI) const;
1008 
1009   /// Add a tie between the register operands at DefIdx and UseIdx.
1010   /// The tie will cause the register allocator to ensure that the two
1011   /// operands are assigned the same physical register.
1012   ///
1013   /// Tied operands are managed automatically for explicit operands in the
1014   /// MCInstrDesc. This method is for exceptional cases like inline asm.
1015   void tieOperands(unsigned DefIdx, unsigned UseIdx);
1016 
1017   /// Given the index of a tied register operand, find the
1018   /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1019   /// index of the tied operand which must exist.
1020   unsigned findTiedOperandIdx(unsigned OpIdx) const;
1021 
1022   /// Given the index of a register def operand,
1023   /// check if the register def is tied to a source operand, due to either
1024   /// two-address elimination or inline assembly constraints. Returns the
1025   /// first tied use operand index by reference if UseOpIdx is not null.
1026   bool isRegTiedToUseOperand(unsigned DefOpIdx,
1027                              unsigned *UseOpIdx = nullptr) const {
1028     const MachineOperand &MO = getOperand(DefOpIdx);
1029     if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1030       return false;
1031     if (UseOpIdx)
1032       *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1033     return true;
1034   }
1035 
1036   /// Return true if the use operand of the specified index is tied to a def
1037   /// operand. It also returns the def operand index by reference if DefOpIdx
1038   /// is not null.
1039   bool isRegTiedToDefOperand(unsigned UseOpIdx,
1040                              unsigned *DefOpIdx = nullptr) const {
1041     const MachineOperand &MO = getOperand(UseOpIdx);
1042     if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1043       return false;
1044     if (DefOpIdx)
1045       *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1046     return true;
1047   }
1048 
1049   /// Clears kill flags on all operands.
1050   void clearKillInfo();
1051 
1052   /// Replace all occurrences of FromReg with ToReg:SubIdx,
1053   /// properly composing subreg indices where necessary.
1054   void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
1055                           const TargetRegisterInfo &RegInfo);
1056 
1057   /// We have determined MI kills a register. Look for the
1058   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1059   /// add a implicit operand if it's not found. Returns true if the operand
1060   /// exists / is added.
1061   bool addRegisterKilled(unsigned IncomingReg,
1062                          const TargetRegisterInfo *RegInfo,
1063                          bool AddIfNotFound = false);
1064 
1065   /// Clear all kill flags affecting Reg.  If RegInfo is
1066   /// provided, this includes super-register kills.
1067   void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
1068 
1069   /// We have determined MI defined a register without a use.
1070   /// Look for the operand that defines it and mark it as IsDead. If
1071   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1072   /// true if the operand exists / is added.
1073   bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo,
1074                        bool AddIfNotFound = false);
1075 
1076   /// Clear all dead flags on operands defining register @p Reg.
1077   void clearRegisterDeads(unsigned Reg);
1078 
1079   /// Mark all subregister defs of register @p Reg with the undef flag.
1080   /// This function is used when we determined to have a subregister def in an
1081   /// otherwise undefined super register.
1082   void setRegisterDefReadUndef(unsigned Reg, bool IsUndef = true);
1083 
1084   /// We have determined MI defines a register. Make sure there is an operand
1085   /// defining Reg.
1086   void addRegisterDefined(unsigned Reg,
1087                           const TargetRegisterInfo *RegInfo = nullptr);
1088 
1089   /// Mark every physreg used by this instruction as
1090   /// dead except those in the UsedRegs list.
1091   ///
1092   /// On instructions with register mask operands, also add implicit-def
1093   /// operands for all registers in UsedRegs.
1094   void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1095                              const TargetRegisterInfo &TRI);
1096 
1097   /// Return true if it is safe to move this instruction. If
1098   /// SawStore is set to true, it means that there is a store (or call) between
1099   /// the instruction's location and its intended destination.
1100   bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const;
1101 
1102   /// Return true if this instruction may have an ordered
1103   /// or volatile memory reference, or if the information describing the memory
1104   /// reference is not available. Return false if it is known to have no
1105   /// ordered or volatile memory references.
1106   bool hasOrderedMemoryRef() const;
1107 
1108   /// Return true if this instruction is loading from a
1109   /// location whose value is invariant across the function.  For example,
1110   /// loading a value from the constant pool or from the argument area of
1111   /// a function if it does not change.  This should only return true of *all*
1112   /// loads the instruction does are invariant (if it does multiple loads).
1113   bool isInvariantLoad(AliasAnalysis *AA) const;
1114 
1115   /// If the specified instruction is a PHI that always merges together the
1116   /// same virtual register, return the register, otherwise return 0.
1117   unsigned isConstantValuePHI() const;
1118 
1119   /// Return true if this instruction has side effects that are not modeled
1120   /// by mayLoad / mayStore, etc.
1121   /// For all instructions, the property is encoded in MCInstrDesc::Flags
1122   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1123   /// INLINEASM instruction, in which case the side effect property is encoded
1124   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1125   ///
1126   bool hasUnmodeledSideEffects() const;
1127 
1128   /// Returns true if it is illegal to fold a load across this instruction.
1129   bool isLoadFoldBarrier() const;
1130 
1131   /// Return true if all the defs of this instruction are dead.
1132   bool allDefsAreDead() const;
1133 
1134   /// Copy implicit register operands from specified
1135   /// instruction to this instruction.
1136   void copyImplicitOps(MachineFunction &MF, const MachineInstr *MI);
1137 
1138   //
1139   // Debugging support
1140   //
1141   void print(raw_ostream &OS, bool SkipOpers = false) const;
1142   void print(raw_ostream &OS, ModuleSlotTracker &MST,
1143              bool SkipOpers = false) const;
1144   void dump() const;
1145 
1146   //===--------------------------------------------------------------------===//
1147   // Accessors used to build up machine instructions.
1148 
1149   /// Add the specified operand to the instruction.  If it is an implicit
1150   /// operand, it is added to the end of the operand list.  If it is an
1151   /// explicit operand it is added at the end of the explicit operand list
1152   /// (before the first implicit operand).
1153   ///
1154   /// MF must be the machine function that was used to allocate this
1155   /// instruction.
1156   ///
1157   /// MachineInstrBuilder provides a more convenient interface for creating
1158   /// instructions and adding operands.
1159   void addOperand(MachineFunction &MF, const MachineOperand &Op);
1160 
1161   /// Add an operand without providing an MF reference. This only works for
1162   /// instructions that are inserted in a basic block.
1163   ///
1164   /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1165   /// preferred.
1166   void addOperand(const MachineOperand &Op);
1167 
1168   /// Replace the instruction descriptor (thus opcode) of
1169   /// the current instruction with a new one.
1170   void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1171 
1172   /// Replace current source information with new such.
1173   /// Avoid using this, the constructor argument is preferable.
1174   void setDebugLoc(DebugLoc dl) {
1175     debugLoc = std::move(dl);
1176     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1177   }
1178 
1179   /// Erase an operand  from an instruction, leaving it with one
1180   /// fewer operand than it started with.
1181   void RemoveOperand(unsigned i);
1182 
1183   /// Add a MachineMemOperand to the machine instruction.
1184   /// This function should be used only occasionally. The setMemRefs function
1185   /// is the primary method for setting up a MachineInstr's MemRefs list.
1186   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1187 
1188   /// Assign this MachineInstr's memory reference descriptor list.
1189   /// This does not transfer ownership.
1190   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
1191     setMemRefs(std::make_pair(NewMemRefs, NewMemRefsEnd-NewMemRefs));
1192   }
1193 
1194   /// Assign this MachineInstr's memory reference descriptor list.  First
1195   /// element in the pair is the begin iterator/pointer to the array; the
1196   /// second is the number of MemoryOperands.  This does not transfer ownership
1197   /// of the underlying memory.
1198   void setMemRefs(std::pair<mmo_iterator, unsigned> NewMemRefs) {
1199     MemRefs = NewMemRefs.first;
1200     NumMemRefs = uint8_t(NewMemRefs.second);
1201     assert(NumMemRefs == NewMemRefs.second &&
1202            "Too many memrefs - must drop memory operands");
1203   }
1204 
1205   /// Return a set of memrefs (begin iterator, size) which conservatively
1206   /// describe the memory behavior of both MachineInstrs.  This is appropriate
1207   /// for use when merging two MachineInstrs into one. This routine does not
1208   /// modify the memrefs of the this MachineInstr.
1209   std::pair<mmo_iterator, unsigned> mergeMemRefsWith(const MachineInstr& Other);
1210 
1211   /// Clear this MachineInstr's memory reference descriptor list.  This resets
1212   /// the memrefs to their most conservative state.  This should be used only
1213   /// as a last resort since it greatly pessimizes our knowledge of the memory
1214   /// access performed by the instruction.
1215   void dropMemRefs() {
1216     MemRefs = nullptr;
1217     NumMemRefs = 0;
1218   }
1219 
1220   /// Break any tie involving OpIdx.
1221   void untieRegOperand(unsigned OpIdx) {
1222     MachineOperand &MO = getOperand(OpIdx);
1223     if (MO.isReg() && MO.isTied()) {
1224       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1225       MO.TiedTo = 0;
1226     }
1227   }
1228 
1229   /// Add all implicit def and use operands to this instruction.
1230   void addImplicitDefUseOperands(MachineFunction &MF);
1231 
1232 private:
1233   /// If this instruction is embedded into a MachineFunction, return the
1234   /// MachineRegisterInfo object for the current function, otherwise
1235   /// return null.
1236   MachineRegisterInfo *getRegInfo();
1237 
1238   /// Unlink all of the register operands in this instruction from their
1239   /// respective use lists.  This requires that the operands already be on their
1240   /// use lists.
1241   void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1242 
1243   /// Add all of the register operands in this instruction from their
1244   /// respective use lists.  This requires that the operands not be on their
1245   /// use lists yet.
1246   void AddRegOperandsToUseLists(MachineRegisterInfo&);
1247 
1248   /// Slow path for hasProperty when we're dealing with a bundle.
1249   bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
1250 
1251   /// \brief Implements the logic of getRegClassConstraintEffectForVReg for the
1252   /// this MI and the given operand index \p OpIdx.
1253   /// If the related operand does not constrained Reg, this returns CurRC.
1254   const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1255       unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1256       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1257 };
1258 
1259 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1260 /// instruction rather than by pointer value.
1261 /// The hashing and equality testing functions ignore definitions so this is
1262 /// useful for CSE, etc.
1263 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1264   static inline MachineInstr *getEmptyKey() {
1265     return nullptr;
1266   }
1267 
1268   static inline MachineInstr *getTombstoneKey() {
1269     return reinterpret_cast<MachineInstr*>(-1);
1270   }
1271 
1272   static unsigned getHashValue(const MachineInstr* const &MI);
1273 
1274   static bool isEqual(const MachineInstr* const &LHS,
1275                       const MachineInstr* const &RHS) {
1276     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1277         LHS == getEmptyKey() || LHS == getTombstoneKey())
1278       return LHS == RHS;
1279     return LHS->isIdenticalTo(RHS, MachineInstr::IgnoreVRegDefs);
1280   }
1281 };
1282 
1283 //===----------------------------------------------------------------------===//
1284 // Debugging Support
1285 
1286 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1287   MI.print(OS);
1288   return OS;
1289 }
1290 
1291 } // End llvm namespace
1292 
1293 #endif
1294