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