]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/CodeGen/MachineInstr.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / CodeGen / MachineInstr.h
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/IR/DebugLoc.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/Support/ArrayRecycler.h"
30 #include "llvm/Target/TargetOpcodes.h"
31
32 namespace llvm {
33
34 class StringRef;
35 template <typename T> class ArrayRef;
36 template <typename T> class SmallVectorImpl;
37 class DILocalVariable;
38 class DIExpression;
39 class TargetInstrInfo;
40 class TargetRegisterClass;
41 class TargetRegisterInfo;
42 class MachineFunction;
43 class MachineMemOperand;
44
45 //===----------------------------------------------------------------------===//
46 /// Representation of each machine instruction.
47 ///
48 /// This class isn't a POD type, but it must have a trivial destructor. When a
49 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
50 /// without having their destructor called.
51 ///
52 class MachineInstr
53     : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
54                                     ilist_sentinel_tracking<true>> {
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 // higher bits are reserved for target dep comments.
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   MachineInstr(const MachineInstr&) = delete;
108   void operator=(const MachineInstr&) = delete;
109   // Use MachineFunction::DeleteMachineInstr() instead.
110   ~MachineInstr() = delete;
111
112   // Intrusive list support
113   friend struct ilist_traits<MachineInstr>;
114   friend struct ilist_callback_traits<MachineBasicBlock>;
115   void setParent(MachineBasicBlock *P) { Parent = P; }
116
117   /// This constructor creates a copy of the given
118   /// MachineInstr in the given MachineFunction.
119   MachineInstr(MachineFunction &, const MachineInstr &);
120
121   /// This constructor create a MachineInstr and add the implicit operands.
122   /// It reserves space for number of operands specified by
123   /// MCInstrDesc.  An explicit DebugLoc is supplied.
124   MachineInstr(MachineFunction &, const MCInstrDesc &MCID, DebugLoc dl,
125                bool NoImp = false);
126
127   // MachineInstrs are pool-allocated and owned by MachineFunction.
128   friend class MachineFunction;
129
130 public:
131   const MachineBasicBlock* getParent() const { return Parent; }
132   MachineBasicBlock* getParent() { return Parent; }
133
134   /// Return the asm printer flags bitvector.
135   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
136
137   /// Clear the AsmPrinter bitvector.
138   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
139
140   /// Return whether an AsmPrinter flag is set.
141   bool getAsmPrinterFlag(CommentFlag Flag) const {
142     return AsmPrinterFlags & Flag;
143   }
144
145   /// Set a flag for the AsmPrinter.
146   void setAsmPrinterFlag(uint8_t Flag) {
147     AsmPrinterFlags |= Flag;
148   }
149
150   /// Clear specific AsmPrinter flags.
151   void clearAsmPrinterFlag(CommentFlag Flag) {
152     AsmPrinterFlags &= ~Flag;
153   }
154
155   /// Return the MI flags bitvector.
156   uint8_t getFlags() const {
157     return Flags;
158   }
159
160   /// Return whether an MI flag is set.
161   bool getFlag(MIFlag Flag) const {
162     return Flags & Flag;
163   }
164
165   /// Set a MI flag.
166   void setFlag(MIFlag Flag) {
167     Flags |= (uint8_t)Flag;
168   }
169
170   void setFlags(unsigned flags) {
171     // Filter out the automatically maintained flags.
172     unsigned Mask = BundledPred | BundledSucc;
173     Flags = (Flags & Mask) | (flags & ~Mask);
174   }
175
176   /// clearFlag - Clear a MI flag.
177   void clearFlag(MIFlag Flag) {
178     Flags &= ~((uint8_t)Flag);
179   }
180
181
182   /// Return true if MI is in a bundle (but not the first MI in a bundle).
183   ///
184   /// A bundle looks like this before it's finalized:
185   ///   ----------------
186   ///   |      MI      |
187   ///   ----------------
188   ///          |
189   ///   ----------------
190   ///   |      MI    * |
191   ///   ----------------
192   ///          |
193   ///   ----------------
194   ///   |      MI    * |
195   ///   ----------------
196   /// In this case, the first MI starts a bundle but is not inside a bundle, the
197   /// next 2 MIs are considered "inside" the bundle.
198   ///
199   /// After a bundle is finalized, it looks like this:
200   ///   ----------------
201   ///   |    Bundle    |
202   ///   ----------------
203   ///          |
204   ///   ----------------
205   ///   |      MI    * |
206   ///   ----------------
207   ///          |
208   ///   ----------------
209   ///   |      MI    * |
210   ///   ----------------
211   ///          |
212   ///   ----------------
213   ///   |      MI    * |
214   ///   ----------------
215   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
216   /// a bundle, but the next three MIs are.
217   bool isInsideBundle() const {
218     return getFlag(BundledPred);
219   }
220
221   /// Return true if this instruction part of a bundle. This is true
222   /// if either itself or its following instruction is marked "InsideBundle".
223   bool isBundled() const {
224     return isBundledWithPred() || isBundledWithSucc();
225   }
226
227   /// Return true if this instruction is part of a bundle, and it is not the
228   /// first instruction in the bundle.
229   bool isBundledWithPred() const { return getFlag(BundledPred); }
230
231   /// Return true if this instruction is part of a bundle, and it is not the
232   /// last instruction in the bundle.
233   bool isBundledWithSucc() const { return getFlag(BundledSucc); }
234
235   /// Bundle this instruction with its predecessor. This can be an unbundled
236   /// instruction, or it can be the first instruction in a bundle.
237   void bundleWithPred();
238
239   /// Bundle this instruction with its successor. This can be an unbundled
240   /// instruction, or it can be the last instruction in a bundle.
241   void bundleWithSucc();
242
243   /// Break bundle above this instruction.
244   void unbundleFromPred();
245
246   /// Break bundle below this instruction.
247   void unbundleFromSucc();
248
249   /// Returns the debug location id of this MachineInstr.
250   const DebugLoc &getDebugLoc() const { return debugLoc; }
251
252   /// Return the debug variable referenced by
253   /// this DBG_VALUE instruction.
254   const DILocalVariable *getDebugVariable() const;
255
256   /// Return the complex address expression referenced by
257   /// this DBG_VALUE instruction.
258   const DIExpression *getDebugExpression() const;
259
260   /// Emit an error referring to the source location of this instruction.
261   /// This should only be used for inline assembly that is somehow
262   /// impossible to compile. Other errors should have been handled much
263   /// earlier.
264   ///
265   /// If this method returns, the caller should try to recover from the error.
266   ///
267   void emitError(StringRef Msg) const;
268
269   /// Returns the target instruction descriptor of this MachineInstr.
270   const MCInstrDesc &getDesc() const { return *MCID; }
271
272   /// Returns the opcode of this MachineInstr.
273   unsigned getOpcode() const { return MCID->Opcode; }
274
275   /// Access to explicit operands of the instruction.
276   ///
277   unsigned getNumOperands() const { return NumOperands; }
278
279   const MachineOperand& getOperand(unsigned i) const {
280     assert(i < getNumOperands() && "getOperand() out of range!");
281     return Operands[i];
282   }
283   MachineOperand& getOperand(unsigned i) {
284     assert(i < getNumOperands() && "getOperand() out of range!");
285     return Operands[i];
286   }
287
288   /// Returns the number of non-implicit operands.
289   unsigned getNumExplicitOperands() const;
290
291   /// iterator/begin/end - Iterate over all operands of a machine instruction.
292   typedef MachineOperand *mop_iterator;
293   typedef const MachineOperand *const_mop_iterator;
294
295   mop_iterator operands_begin() { return Operands; }
296   mop_iterator operands_end() { return Operands + NumOperands; }
297
298   const_mop_iterator operands_begin() const { return Operands; }
299   const_mop_iterator operands_end() const { return Operands + NumOperands; }
300
301   iterator_range<mop_iterator> operands() {
302     return make_range(operands_begin(), operands_end());
303   }
304   iterator_range<const_mop_iterator> operands() const {
305     return make_range(operands_begin(), operands_end());
306   }
307   iterator_range<mop_iterator> explicit_operands() {
308     return make_range(operands_begin(),
309                       operands_begin() + getNumExplicitOperands());
310   }
311   iterator_range<const_mop_iterator> explicit_operands() const {
312     return make_range(operands_begin(),
313                       operands_begin() + getNumExplicitOperands());
314   }
315   iterator_range<mop_iterator> implicit_operands() {
316     return make_range(explicit_operands().end(), operands_end());
317   }
318   iterator_range<const_mop_iterator> implicit_operands() const {
319     return make_range(explicit_operands().end(), operands_end());
320   }
321   /// Returns a range over all explicit operands that are register definitions.
322   /// Implicit definition are not included!
323   iterator_range<mop_iterator> defs() {
324     return make_range(operands_begin(),
325                       operands_begin() + getDesc().getNumDefs());
326   }
327   /// \copydoc defs()
328   iterator_range<const_mop_iterator> defs() const {
329     return make_range(operands_begin(),
330                       operands_begin() + getDesc().getNumDefs());
331   }
332   /// Returns a range that includes all operands that are register uses.
333   /// This may include unrelated operands which are not register uses.
334   iterator_range<mop_iterator> uses() {
335     return make_range(operands_begin() + getDesc().getNumDefs(),
336                       operands_end());
337   }
338   /// \copydoc uses()
339   iterator_range<const_mop_iterator> uses() const {
340     return make_range(operands_begin() + getDesc().getNumDefs(),
341                       operands_end());
342   }
343   iterator_range<mop_iterator> explicit_uses() {
344     return make_range(operands_begin() + getDesc().getNumDefs(),
345                       operands_begin() + getNumExplicitOperands() );
346   }
347   iterator_range<const_mop_iterator> explicit_uses() const {
348     return make_range(operands_begin() + getDesc().getNumDefs(),
349                       operands_begin() + getNumExplicitOperands() );
350   }
351
352   /// Returns the number of the operand iterator \p I points to.
353   unsigned getOperandNo(const_mop_iterator I) const {
354     return I - operands_begin();
355   }
356
357   /// Access to memory operands of the instruction
358   mmo_iterator memoperands_begin() const { return MemRefs; }
359   mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
360   /// Return true if we don't have any memory operands which described the the
361   /// memory access done by this instruction.  If this is true, calling code
362   /// must be conservative.
363   bool memoperands_empty() const { return NumMemRefs == 0; }
364
365   iterator_range<mmo_iterator>  memoperands() {
366     return make_range(memoperands_begin(), memoperands_end());
367   }
368   iterator_range<mmo_iterator> memoperands() const {
369     return make_range(memoperands_begin(), memoperands_end());
370   }
371
372   /// Return true if this instruction has exactly one MachineMemOperand.
373   bool hasOneMemOperand() const {
374     return NumMemRefs == 1;
375   }
376
377   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
378   /// queries but they are bundle aware.
379
380   enum QueryType {
381     IgnoreBundle,    // Ignore bundles
382     AnyInBundle,     // Return true if any instruction in bundle has property
383     AllInBundle      // Return true if all instructions in bundle have property
384   };
385
386   /// Return true if the instruction (or in the case of a bundle,
387   /// the instructions inside the bundle) has the specified property.
388   /// The first argument is the property being queried.
389   /// The second argument indicates whether the query should look inside
390   /// instruction bundles.
391   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
392     // Inline the fast path for unbundled or bundle-internal instructions.
393     if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
394       return getDesc().getFlags() & (1ULL << MCFlag);
395
396     // If this is the first instruction in a bundle, take the slow path.
397     return hasPropertyInBundle(1ULL << MCFlag, Type);
398   }
399
400   /// Return true if this instruction can have a variable number of operands.
401   /// In this case, the variable operands will be after the normal
402   /// operands but before the implicit definitions and uses (if any are
403   /// present).
404   bool isVariadic(QueryType Type = IgnoreBundle) const {
405     return hasProperty(MCID::Variadic, Type);
406   }
407
408   /// Set if this instruction has an optional definition, e.g.
409   /// ARM instructions which can set condition code if 's' bit is set.
410   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
411     return hasProperty(MCID::HasOptionalDef, Type);
412   }
413
414   /// Return true if this is a pseudo instruction that doesn't
415   /// correspond to a real machine instruction.
416   bool isPseudo(QueryType Type = IgnoreBundle) const {
417     return hasProperty(MCID::Pseudo, Type);
418   }
419
420   bool isReturn(QueryType Type = AnyInBundle) const {
421     return hasProperty(MCID::Return, Type);
422   }
423
424   bool isCall(QueryType Type = AnyInBundle) const {
425     return hasProperty(MCID::Call, Type);
426   }
427
428   /// Returns true if the specified instruction stops control flow
429   /// from executing the instruction immediately following it.  Examples include
430   /// unconditional branches and return instructions.
431   bool isBarrier(QueryType Type = AnyInBundle) const {
432     return hasProperty(MCID::Barrier, Type);
433   }
434
435   /// Returns true if this instruction part of the terminator for a basic block.
436   /// Typically this is things like return and branch instructions.
437   ///
438   /// Various passes use this to insert code into the bottom of a basic block,
439   /// but before control flow occurs.
440   bool isTerminator(QueryType Type = AnyInBundle) const {
441     return hasProperty(MCID::Terminator, Type);
442   }
443
444   /// Returns true if this is a conditional, unconditional, or indirect branch.
445   /// Predicates below can be used to discriminate between
446   /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
447   /// get more information.
448   bool isBranch(QueryType Type = AnyInBundle) const {
449     return hasProperty(MCID::Branch, Type);
450   }
451
452   /// Return true if this is an indirect branch, such as a
453   /// branch through a register.
454   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
455     return hasProperty(MCID::IndirectBranch, Type);
456   }
457
458   /// Return true if this is a branch which may fall
459   /// through to the next instruction or may transfer control flow to some other
460   /// block.  The TargetInstrInfo::AnalyzeBranch method can be used to get more
461   /// information about this branch.
462   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
463     return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
464   }
465
466   /// Return true if this is a branch which always
467   /// transfers control flow to some other block.  The
468   /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
469   /// about this branch.
470   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
471     return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
472   }
473
474   /// Return true if this instruction has a predicate operand that
475   /// controls execution.  It may be set to 'always', or may be set to other
476   /// values.   There are various methods in TargetInstrInfo that can be used to
477   /// control and modify the predicate in this instruction.
478   bool isPredicable(QueryType Type = AllInBundle) const {
479     // If it's a bundle than all bundled instructions must be predicable for this
480     // to return true.
481     return hasProperty(MCID::Predicable, Type);
482   }
483
484   /// Return true if this instruction is a comparison.
485   bool isCompare(QueryType Type = IgnoreBundle) const {
486     return hasProperty(MCID::Compare, Type);
487   }
488
489   /// Return true if this instruction is a move immediate
490   /// (including conditional moves) instruction.
491   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
492     return hasProperty(MCID::MoveImm, Type);
493   }
494
495   /// Return true if this instruction is a bitcast instruction.
496   bool isBitcast(QueryType Type = IgnoreBundle) const {
497     return hasProperty(MCID::Bitcast, Type);
498   }
499
500   /// Return true if this instruction is a select instruction.
501   bool isSelect(QueryType Type = IgnoreBundle) const {
502     return hasProperty(MCID::Select, Type);
503   }
504
505   /// Return true if this instruction cannot be safely duplicated.
506   /// For example, if the instruction has a unique labels attached
507   /// to it, duplicating it would cause multiple definition errors.
508   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
509     return hasProperty(MCID::NotDuplicable, Type);
510   }
511
512   /// Return true if this instruction is convergent.
513   /// Convergent instructions can not be made control-dependent on any
514   /// additional values.
515   bool isConvergent(QueryType Type = AnyInBundle) const {
516     if (isInlineAsm()) {
517       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
518       if (ExtraInfo & InlineAsm::Extra_IsConvergent)
519         return true;
520     }
521     return hasProperty(MCID::Convergent, Type);
522   }
523
524   /// Returns true if the specified instruction has a delay slot
525   /// which must be filled by the code generator.
526   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
527     return hasProperty(MCID::DelaySlot, Type);
528   }
529
530   /// Return true for instructions that can be folded as
531   /// memory operands in other instructions. The most common use for this
532   /// is instructions that are simple loads from memory that don't modify
533   /// the loaded value in any way, but it can also be used for instructions
534   /// that can be expressed as constant-pool loads, such as V_SETALLONES
535   /// on x86, to allow them to be folded when it is beneficial.
536   /// This should only be set on instructions that return a value in their
537   /// only virtual register definition.
538   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
539     return hasProperty(MCID::FoldableAsLoad, Type);
540   }
541
542   /// \brief Return true if this instruction behaves
543   /// the same way as the generic REG_SEQUENCE instructions.
544   /// E.g., on ARM,
545   /// dX VMOVDRR rY, rZ
546   /// is equivalent to
547   /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
548   ///
549   /// Note that for the optimizers to be able to take advantage of
550   /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
551   /// override accordingly.
552   bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
553     return hasProperty(MCID::RegSequence, Type);
554   }
555
556   /// \brief Return true if this instruction behaves
557   /// the same way as the generic EXTRACT_SUBREG instructions.
558   /// E.g., on ARM,
559   /// rX, rY VMOVRRD dZ
560   /// is equivalent to two EXTRACT_SUBREG:
561   /// rX = EXTRACT_SUBREG dZ, ssub_0
562   /// rY = EXTRACT_SUBREG dZ, ssub_1
563   ///
564   /// Note that for the optimizers to be able to take advantage of
565   /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
566   /// override accordingly.
567   bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
568     return hasProperty(MCID::ExtractSubreg, Type);
569   }
570
571   /// \brief Return true if this instruction behaves
572   /// the same way as the generic INSERT_SUBREG instructions.
573   /// E.g., on ARM,
574   /// dX = VSETLNi32 dY, rZ, Imm
575   /// is equivalent to a INSERT_SUBREG:
576   /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
577   ///
578   /// Note that for the optimizers to be able to take advantage of
579   /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
580   /// override accordingly.
581   bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
582     return hasProperty(MCID::InsertSubreg, Type);
583   }
584
585   //===--------------------------------------------------------------------===//
586   // Side Effect Analysis
587   //===--------------------------------------------------------------------===//
588
589   /// Return true if this instruction could possibly read memory.
590   /// Instructions with this flag set are not necessarily simple load
591   /// instructions, they may load a value and modify it, for example.
592   bool mayLoad(QueryType Type = AnyInBundle) const {
593     if (isInlineAsm()) {
594       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
595       if (ExtraInfo & InlineAsm::Extra_MayLoad)
596         return true;
597     }
598     return hasProperty(MCID::MayLoad, Type);
599   }
600
601   /// Return true if this instruction could possibly modify memory.
602   /// Instructions with this flag set are not necessarily simple store
603   /// instructions, they may store a modified value based on their operands, or
604   /// may not actually modify anything, for example.
605   bool mayStore(QueryType Type = AnyInBundle) const {
606     if (isInlineAsm()) {
607       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
608       if (ExtraInfo & InlineAsm::Extra_MayStore)
609         return true;
610     }
611     return hasProperty(MCID::MayStore, Type);
612   }
613
614   /// Return true if this instruction could possibly read or modify memory.
615   bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
616     return mayLoad(Type) || mayStore(Type);
617   }
618
619   //===--------------------------------------------------------------------===//
620   // Flags that indicate whether an instruction can be modified by a method.
621   //===--------------------------------------------------------------------===//
622
623   /// Return true if this may be a 2- or 3-address
624   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
625   /// result if Y and Z are exchanged.  If this flag is set, then the
626   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
627   /// instruction.
628   ///
629   /// Note that this flag may be set on instructions that are only commutable
630   /// sometimes.  In these cases, the call to commuteInstruction will fail.
631   /// Also note that some instructions require non-trivial modification to
632   /// commute them.
633   bool isCommutable(QueryType Type = IgnoreBundle) const {
634     return hasProperty(MCID::Commutable, Type);
635   }
636
637   /// Return true if this is a 2-address instruction
638   /// which can be changed into a 3-address instruction if needed.  Doing this
639   /// transformation can be profitable in the register allocator, because it
640   /// means that the instruction can use a 2-address form if possible, but
641   /// degrade into a less efficient form if the source and dest register cannot
642   /// be assigned to the same register.  For example, this allows the x86
643   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
644   /// is the same speed as the shift but has bigger code size.
645   ///
646   /// If this returns true, then the target must implement the
647   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
648   /// is allowed to fail if the transformation isn't valid for this specific
649   /// instruction (e.g. shl reg, 4 on x86).
650   ///
651   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
652     return hasProperty(MCID::ConvertibleTo3Addr, Type);
653   }
654
655   /// Return true if this instruction requires
656   /// custom insertion support when the DAG scheduler is inserting it into a
657   /// machine basic block.  If this is true for the instruction, it basically
658   /// means that it is a pseudo instruction used at SelectionDAG time that is
659   /// expanded out into magic code by the target when MachineInstrs are formed.
660   ///
661   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
662   /// is used to insert this into the MachineBasicBlock.
663   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
664     return hasProperty(MCID::UsesCustomInserter, Type);
665   }
666
667   /// Return true if this instruction requires *adjustment*
668   /// after instruction selection by calling a target hook. For example, this
669   /// can be used to fill in ARM 's' optional operand depending on whether
670   /// the conditional flag register is used.
671   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
672     return hasProperty(MCID::HasPostISelHook, Type);
673   }
674
675   /// Returns true if this instruction is a candidate for remat.
676   /// This flag is deprecated, please don't use it anymore.  If this
677   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
678   /// verify the instruction is really rematable.
679   bool isRematerializable(QueryType Type = AllInBundle) const {
680     // It's only possible to re-mat a bundle if all bundled instructions are
681     // re-materializable.
682     return hasProperty(MCID::Rematerializable, Type);
683   }
684
685   /// Returns true if this instruction has the same cost (or less) than a move
686   /// instruction. This is useful during certain types of optimizations
687   /// (e.g., remat during two-address conversion or machine licm)
688   /// where we would like to remat or hoist the instruction, but not if it costs
689   /// more than moving the instruction into the appropriate register. Note, we
690   /// are not marking copies from and to the same register class with this flag.
691   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
692     // Only returns true for a bundle if all bundled instructions are cheap.
693     return hasProperty(MCID::CheapAsAMove, Type);
694   }
695
696   /// Returns true if this instruction source operands
697   /// have special register allocation requirements that are not captured by the
698   /// operand register classes. e.g. ARM::STRD's two source registers must be an
699   /// even / odd pair, ARM::STM registers have to be in ascending order.
700   /// Post-register allocation passes should not attempt to change allocations
701   /// for sources of instructions with this flag.
702   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
703     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
704   }
705
706   /// Returns true if this instruction def operands
707   /// have special register allocation requirements that are not captured by the
708   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
709   /// even / odd pair, ARM::LDM registers have to be in ascending order.
710   /// Post-register allocation passes should not attempt to change allocations
711   /// for definitions of instructions with this flag.
712   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
713     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
714   }
715
716
717   enum MICheckType {
718     CheckDefs,      // Check all operands for equality
719     CheckKillDead,  // Check all operands including kill / dead markers
720     IgnoreDefs,     // Ignore all definitions
721     IgnoreVRegDefs  // Ignore virtual register definitions
722   };
723
724   /// Return true if this instruction is identical to \p Other.
725   /// Two instructions are identical if they have the same opcode and all their
726   /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
727   /// Note that this means liveness related flags (dead, undef, kill) do not
728   /// affect the notion of identical.
729   bool isIdenticalTo(const MachineInstr &Other,
730                      MICheckType Check = CheckDefs) const;
731
732   /// Unlink 'this' from the containing basic block, and return it without
733   /// deleting it.
734   ///
735   /// This function can not be used on bundled instructions, use
736   /// removeFromBundle() to remove individual instructions from a bundle.
737   MachineInstr *removeFromParent();
738
739   /// Unlink this instruction from its basic block and return it without
740   /// deleting it.
741   ///
742   /// If the instruction is part of a bundle, the other instructions in the
743   /// bundle remain bundled.
744   MachineInstr *removeFromBundle();
745
746   /// Unlink 'this' from the containing basic block and delete it.
747   ///
748   /// If this instruction is the header of a bundle, the whole bundle is erased.
749   /// This function can not be used for instructions inside a bundle, use
750   /// eraseFromBundle() to erase individual bundled instructions.
751   void eraseFromParent();
752
753   /// Unlink 'this' from the containing basic block and delete it.
754   ///
755   /// For all definitions mark their uses in DBG_VALUE nodes
756   /// as undefined. Otherwise like eraseFromParent().
757   void eraseFromParentAndMarkDBGValuesForRemoval();
758
759   /// Unlink 'this' form its basic block and delete it.
760   ///
761   /// If the instruction is part of a bundle, the other instructions in the
762   /// bundle remain bundled.
763   void eraseFromBundle();
764
765   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
766   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
767
768   /// Returns true if the MachineInstr represents a label.
769   bool isLabel() const { return isEHLabel() || isGCLabel(); }
770   bool isCFIInstruction() const {
771     return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
772   }
773
774   // True if the instruction represents a position in the function.
775   bool isPosition() const { return isLabel() || isCFIInstruction(); }
776
777   bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
778   /// A DBG_VALUE is indirect iff the first operand is a register and
779   /// the second operand is an immediate.
780   bool isIndirectDebugValue() const {
781     return isDebugValue()
782       && getOperand(0).isReg()
783       && getOperand(1).isImm();
784   }
785
786   bool isPHI() const { return getOpcode() == TargetOpcode::PHI; }
787   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
788   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
789   bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
790   bool isMSInlineAsm() const {
791     return getOpcode() == TargetOpcode::INLINEASM && getInlineAsmDialect();
792   }
793   bool isStackAligningInlineAsm() const;
794   InlineAsm::AsmDialect getInlineAsmDialect() const;
795   bool isInsertSubreg() const {
796     return getOpcode() == TargetOpcode::INSERT_SUBREG;
797   }
798   bool isSubregToReg() const {
799     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
800   }
801   bool isRegSequence() const {
802     return getOpcode() == TargetOpcode::REG_SEQUENCE;
803   }
804   bool isBundle() const {
805     return getOpcode() == TargetOpcode::BUNDLE;
806   }
807   bool isCopy() const {
808     return getOpcode() == TargetOpcode::COPY;
809   }
810   bool isFullCopy() const {
811     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
812   }
813   bool isExtractSubreg() const {
814     return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
815   }
816
817   /// Return true if the instruction behaves like a copy.
818   /// This does not include native copy instructions.
819   bool isCopyLike() const {
820     return isCopy() || isSubregToReg();
821   }
822
823   /// Return true is the instruction is an identity copy.
824   bool isIdentityCopy() const {
825     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
826       getOperand(0).getSubReg() == getOperand(1).getSubReg();
827   }
828
829   /// Return true if this instruction doesn't produce any output in the form of
830   /// executable instructions.
831   bool isMetaInstruction() const {
832     switch (getOpcode()) {
833     default:
834       return false;
835     case TargetOpcode::IMPLICIT_DEF:
836     case TargetOpcode::KILL:
837     case TargetOpcode::CFI_INSTRUCTION:
838     case TargetOpcode::EH_LABEL:
839     case TargetOpcode::GC_LABEL:
840     case TargetOpcode::DBG_VALUE:
841       return true;
842     }
843   }
844
845   /// Return true if this is a transient instruction that is either very likely
846   /// to be eliminated during register allocation (such as copy-like
847   /// instructions), or if this instruction doesn't have an execution-time cost.
848   bool isTransient() const {
849     switch (getOpcode()) {
850     default:
851       return isMetaInstruction();
852     // Copy-like instructions are usually eliminated during register allocation.
853     case TargetOpcode::PHI:
854     case TargetOpcode::COPY:
855     case TargetOpcode::INSERT_SUBREG:
856     case TargetOpcode::SUBREG_TO_REG:
857     case TargetOpcode::REG_SEQUENCE:
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   /// Returns true if this instruction's memory access aliases the memory
1121   /// access of Other.
1122   //
1123   /// Assumes any physical registers used to compute addresses
1124   /// have the same value for both instructions.  Returns false if neither
1125   /// instruction writes to memory.
1126   ///
1127   /// @param AA Optional alias analysis, used to compare memory operands.
1128   /// @param Other MachineInstr to check aliasing against.
1129   /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1130   bool mayAlias(AliasAnalysis *AA, MachineInstr &Other, bool UseTBAA);
1131
1132   /// Return true if this instruction may have an ordered
1133   /// or volatile memory reference, or if the information describing the memory
1134   /// reference is not available. Return false if it is known to have no
1135   /// ordered or volatile memory references.
1136   bool hasOrderedMemoryRef() const;
1137
1138   /// Return true if this load instruction never traps and points to a memory
1139   /// location whose value doesn't change during the execution of this function.
1140   ///
1141   /// Examples include loading a value from the constant pool or from the
1142   /// argument area of a function (if it does not change).  If the instruction
1143   /// does multiple loads, this returns true only if all of the loads are
1144   /// dereferenceable and invariant.
1145   bool isDereferenceableInvariantLoad(AliasAnalysis *AA) const;
1146
1147   /// If the specified instruction is a PHI that always merges together the
1148   /// same virtual register, return the register, otherwise return 0.
1149   unsigned isConstantValuePHI() const;
1150
1151   /// Return true if this instruction has side effects that are not modeled
1152   /// by mayLoad / mayStore, etc.
1153   /// For all instructions, the property is encoded in MCInstrDesc::Flags
1154   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1155   /// INLINEASM instruction, in which case the side effect property is encoded
1156   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1157   ///
1158   bool hasUnmodeledSideEffects() const;
1159
1160   /// Returns true if it is illegal to fold a load across this instruction.
1161   bool isLoadFoldBarrier() const;
1162
1163   /// Return true if all the defs of this instruction are dead.
1164   bool allDefsAreDead() const;
1165
1166   /// Copy implicit register operands from specified
1167   /// instruction to this instruction.
1168   void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1169
1170   /// Debugging support
1171   /// @{
1172   /// Print this MI to \p OS.
1173   /// Only print the defs and the opcode if \p SkipOpers is true.
1174   /// Otherwise, also print operands if \p SkipDebugLoc is true.
1175   /// Otherwise, also print the debug loc, with a terminating newline.
1176   /// \p TII is used to print the opcode name.  If it's not present, but the
1177   /// MI is in a function, the opcode will be printed using the function's TII.
1178   void print(raw_ostream &OS, bool SkipOpers = false, bool SkipDebugLoc = false,
1179              const TargetInstrInfo *TII = nullptr) const;
1180   void print(raw_ostream &OS, ModuleSlotTracker &MST, bool SkipOpers = false,
1181              bool SkipDebugLoc = false,
1182              const TargetInstrInfo *TII = nullptr) const;
1183   void dump() const;
1184   /// @}
1185
1186   //===--------------------------------------------------------------------===//
1187   // Accessors used to build up machine instructions.
1188
1189   /// Add the specified operand to the instruction.  If it is an implicit
1190   /// operand, it is added to the end of the operand list.  If it is an
1191   /// explicit operand it is added at the end of the explicit operand list
1192   /// (before the first implicit operand).
1193   ///
1194   /// MF must be the machine function that was used to allocate this
1195   /// instruction.
1196   ///
1197   /// MachineInstrBuilder provides a more convenient interface for creating
1198   /// instructions and adding operands.
1199   void addOperand(MachineFunction &MF, const MachineOperand &Op);
1200
1201   /// Add an operand without providing an MF reference. This only works for
1202   /// instructions that are inserted in a basic block.
1203   ///
1204   /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1205   /// preferred.
1206   void addOperand(const MachineOperand &Op);
1207
1208   /// Replace the instruction descriptor (thus opcode) of
1209   /// the current instruction with a new one.
1210   void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1211
1212   /// Replace current source information with new such.
1213   /// Avoid using this, the constructor argument is preferable.
1214   void setDebugLoc(DebugLoc dl) {
1215     debugLoc = std::move(dl);
1216     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1217   }
1218
1219   /// Erase an operand from an instruction, leaving it with one
1220   /// fewer operand than it started with.
1221   void RemoveOperand(unsigned i);
1222
1223   /// Add a MachineMemOperand to the machine instruction.
1224   /// This function should be used only occasionally. The setMemRefs function
1225   /// is the primary method for setting up a MachineInstr's MemRefs list.
1226   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1227
1228   /// Assign this MachineInstr's memory reference descriptor list.
1229   /// This does not transfer ownership.
1230   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
1231     setMemRefs(std::make_pair(NewMemRefs, NewMemRefsEnd-NewMemRefs));
1232   }
1233
1234   /// Assign this MachineInstr's memory reference descriptor list.  First
1235   /// element in the pair is the begin iterator/pointer to the array; the
1236   /// second is the number of MemoryOperands.  This does not transfer ownership
1237   /// of the underlying memory.
1238   void setMemRefs(std::pair<mmo_iterator, unsigned> NewMemRefs) {
1239     MemRefs = NewMemRefs.first;
1240     NumMemRefs = uint8_t(NewMemRefs.second);
1241     assert(NumMemRefs == NewMemRefs.second &&
1242            "Too many memrefs - must drop memory operands");
1243   }
1244
1245   /// Return a set of memrefs (begin iterator, size) which conservatively
1246   /// describe the memory behavior of both MachineInstrs.  This is appropriate
1247   /// for use when merging two MachineInstrs into one. This routine does not
1248   /// modify the memrefs of the this MachineInstr.
1249   std::pair<mmo_iterator, unsigned> mergeMemRefsWith(const MachineInstr& Other);
1250
1251   /// Clear this MachineInstr's memory reference descriptor list.  This resets
1252   /// the memrefs to their most conservative state.  This should be used only
1253   /// as a last resort since it greatly pessimizes our knowledge of the memory
1254   /// access performed by the instruction.
1255   void dropMemRefs() {
1256     MemRefs = nullptr;
1257     NumMemRefs = 0;
1258   }
1259
1260   /// Break any tie involving OpIdx.
1261   void untieRegOperand(unsigned OpIdx) {
1262     MachineOperand &MO = getOperand(OpIdx);
1263     if (MO.isReg() && MO.isTied()) {
1264       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1265       MO.TiedTo = 0;
1266     }
1267   }
1268
1269   /// Add all implicit def and use operands to this instruction.
1270   void addImplicitDefUseOperands(MachineFunction &MF);
1271
1272 private:
1273   /// If this instruction is embedded into a MachineFunction, return the
1274   /// MachineRegisterInfo object for the current function, otherwise
1275   /// return null.
1276   MachineRegisterInfo *getRegInfo();
1277
1278   /// Unlink all of the register operands in this instruction from their
1279   /// respective use lists.  This requires that the operands already be on their
1280   /// use lists.
1281   void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1282
1283   /// Add all of the register operands in this instruction from their
1284   /// respective use lists.  This requires that the operands not be on their
1285   /// use lists yet.
1286   void AddRegOperandsToUseLists(MachineRegisterInfo&);
1287
1288   /// Slow path for hasProperty when we're dealing with a bundle.
1289   bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
1290
1291   /// \brief Implements the logic of getRegClassConstraintEffectForVReg for the
1292   /// this MI and the given operand index \p OpIdx.
1293   /// If the related operand does not constrained Reg, this returns CurRC.
1294   const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1295       unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1296       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1297 };
1298
1299 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1300 /// instruction rather than by pointer value.
1301 /// The hashing and equality testing functions ignore definitions so this is
1302 /// useful for CSE, etc.
1303 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1304   static inline MachineInstr *getEmptyKey() {
1305     return nullptr;
1306   }
1307
1308   static inline MachineInstr *getTombstoneKey() {
1309     return reinterpret_cast<MachineInstr*>(-1);
1310   }
1311
1312   static unsigned getHashValue(const MachineInstr* const &MI);
1313
1314   static bool isEqual(const MachineInstr* const &LHS,
1315                       const MachineInstr* const &RHS) {
1316     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1317         LHS == getEmptyKey() || LHS == getTombstoneKey())
1318       return LHS == RHS;
1319     return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
1320   }
1321 };
1322
1323 //===----------------------------------------------------------------------===//
1324 // Debugging Support
1325
1326 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1327   MI.print(OS);
1328   return OS;
1329 }
1330
1331 } // End llvm namespace
1332
1333 #endif