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