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