Move use list management into MachineRegisterInfo.
[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/CodeGen/MachineOperand.h"
20 #include "llvm/MC/MCInstrDesc.h"
21 #include "llvm/Target/TargetOpcodes.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/ilist_node.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/DenseMapInfo.h"
28 #include "llvm/Support/DebugLoc.h"
29 #include <vector>
30
31 namespace llvm {
32
33 template <typename T> class SmallVectorImpl;
34 class AliasAnalysis;
35 class TargetInstrInfo;
36 class TargetRegisterClass;
37 class TargetRegisterInfo;
38 class MachineFunction;
39 class MachineMemOperand;
40
41 //===----------------------------------------------------------------------===//
42 /// MachineInstr - Representation of each machine instruction.
43 ///
44 class MachineInstr : public ilist_node<MachineInstr> {
45 public:
46   typedef MachineMemOperand **mmo_iterator;
47
48   /// Flags to specify different kinds of comments to output in
49   /// assembly code.  These flags carry semantic information not
50   /// otherwise easily derivable from the IR text.
51   ///
52   enum CommentFlag {
53     ReloadReuse = 0x1
54   };
55
56   enum MIFlag {
57     NoFlags      = 0,
58     FrameSetup   = 1 << 0,              // Instruction is used as a part of
59                                         // function frame setup code.
60     InsideBundle = 1 << 1               // Instruction is inside a bundle (not
61                                         // the first MI in a bundle)
62   };
63 private:
64   const MCInstrDesc *MCID;              // Instruction descriptor.
65
66   uint8_t Flags;                        // Various bits of additional
67                                         // information about machine
68                                         // instruction.
69
70   uint8_t AsmPrinterFlags;              // Various bits of information used by
71                                         // the AsmPrinter to emit helpful
72                                         // comments.  This is *not* semantic
73                                         // information.  Do not use this for
74                                         // anything other than to convey comment
75                                         // information to AsmPrinter.
76
77   uint16_t NumMemRefs;                  // information on memory references
78   mmo_iterator MemRefs;
79
80   std::vector<MachineOperand> Operands; // the operands
81   MachineBasicBlock *Parent;            // Pointer to the owning basic block.
82   DebugLoc debugLoc;                    // Source line information.
83
84   MachineInstr(const MachineInstr&);   // DO NOT IMPLEMENT
85   void operator=(const MachineInstr&); // DO NOT IMPLEMENT
86
87   // Intrusive list support
88   friend struct ilist_traits<MachineInstr>;
89   friend struct ilist_traits<MachineBasicBlock>;
90   void setParent(MachineBasicBlock *P) { Parent = P; }
91
92   /// MachineInstr ctor - This constructor creates a copy of the given
93   /// MachineInstr in the given MachineFunction.
94   MachineInstr(MachineFunction &, const MachineInstr &);
95
96   /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
97   /// MCID NULL and no operands.
98   MachineInstr();
99
100   // The next two constructors have DebugLoc and non-DebugLoc versions;
101   // over time, the non-DebugLoc versions should be phased out and eventually
102   // removed.
103
104   /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
105   /// implicit operands.  It reserves space for the number of operands specified
106   /// by the MCInstrDesc.  The version with a DebugLoc should be preferred.
107   explicit MachineInstr(const MCInstrDesc &MCID, bool NoImp = false);
108
109   /// MachineInstr ctor - Work exactly the same as the ctor above, except that
110   /// the MachineInstr is created and added to the end of the specified basic
111   /// block.  The version with a DebugLoc should be preferred.
112   MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &MCID);
113
114   /// MachineInstr ctor - This constructor create a MachineInstr and add the
115   /// implicit operands.  It reserves space for number of operands specified by
116   /// MCInstrDesc.  An explicit DebugLoc is supplied.
117   explicit MachineInstr(const MCInstrDesc &MCID, const DebugLoc dl,
118                         bool NoImp = false);
119
120   /// MachineInstr ctor - Work exactly the same as the ctor above, except that
121   /// the MachineInstr is created and added to the end of the specified basic
122   /// block.
123   MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
124                const MCInstrDesc &MCID);
125
126   ~MachineInstr();
127
128   // MachineInstrs are pool-allocated and owned by MachineFunction.
129   friend class MachineFunction;
130
131 public:
132   const MachineBasicBlock* getParent() const { return Parent; }
133   MachineBasicBlock* getParent() { return Parent; }
134
135   /// getAsmPrinterFlags - Return the asm printer flags bitvector.
136   ///
137   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
138
139   /// clearAsmPrinterFlags - clear the AsmPrinter bitvector
140   ///
141   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
142
143   /// getAsmPrinterFlag - Return whether an AsmPrinter flag is set.
144   ///
145   bool getAsmPrinterFlag(CommentFlag Flag) const {
146     return AsmPrinterFlags & Flag;
147   }
148
149   /// setAsmPrinterFlag - Set a flag for the AsmPrinter.
150   ///
151   void setAsmPrinterFlag(CommentFlag Flag) {
152     AsmPrinterFlags |= (uint8_t)Flag;
153   }
154
155   /// clearAsmPrinterFlag - clear specific AsmPrinter flags
156   ///
157   void clearAsmPrinterFlag(CommentFlag Flag) {
158     AsmPrinterFlags &= ~Flag;
159   }
160
161   /// getFlags - Return the MI flags bitvector.
162   uint8_t getFlags() const {
163     return Flags;
164   }
165
166   /// getFlag - Return whether an MI flag is set.
167   bool getFlag(MIFlag Flag) const {
168     return Flags & Flag;
169   }
170
171   /// setFlag - Set a MI flag.
172   void setFlag(MIFlag Flag) {
173     Flags |= (uint8_t)Flag;
174   }
175
176   void setFlags(unsigned flags) {
177     Flags = flags;
178   }
179
180   /// clearFlag - Clear a MI flag.
181   void clearFlag(MIFlag Flag) {
182     Flags &= ~((uint8_t)Flag);
183   }
184
185   /// isInsideBundle - Return true if MI is in a bundle (but not the first MI
186   /// in a bundle).
187   ///
188   /// A bundle looks like this before it's finalized:
189   ///   ----------------
190   ///   |      MI      |
191   ///   ----------------
192   ///          |
193   ///   ----------------
194   ///   |      MI    * |
195   ///   ----------------
196   ///          |
197   ///   ----------------
198   ///   |      MI    * |
199   ///   ----------------
200   /// In this case, the first MI starts a bundle but is not inside a bundle, the
201   /// next 2 MIs are considered "inside" the bundle.
202   ///
203   /// After a bundle is finalized, it looks like this:
204   ///   ----------------
205   ///   |    Bundle    |
206   ///   ----------------
207   ///          |
208   ///   ----------------
209   ///   |      MI    * |
210   ///   ----------------
211   ///          |
212   ///   ----------------
213   ///   |      MI    * |
214   ///   ----------------
215   ///          |
216   ///   ----------------
217   ///   |      MI    * |
218   ///   ----------------
219   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
220   /// a bundle, but the next three MIs are.
221   bool isInsideBundle() const {
222     return getFlag(InsideBundle);
223   }
224
225   /// setIsInsideBundle - Set InsideBundle bit.
226   ///
227   void setIsInsideBundle(bool Val = true) {
228     if (Val)
229       setFlag(InsideBundle);
230     else
231       clearFlag(InsideBundle);
232   }
233
234   /// isBundled - Return true if this instruction part of a bundle. This is true
235   /// if either itself or its following instruction is marked "InsideBundle".
236   bool isBundled() const;
237
238   /// getDebugLoc - Returns the debug location id of this MachineInstr.
239   ///
240   DebugLoc getDebugLoc() const { return debugLoc; }
241
242   /// emitError - Emit an error referring to the source location of this
243   /// instruction. This should only be used for inline assembly that is somehow
244   /// impossible to compile. Other errors should have been handled much
245   /// earlier.
246   ///
247   /// If this method returns, the caller should try to recover from the error.
248   ///
249   void emitError(StringRef Msg) const;
250
251   /// getDesc - Returns the target instruction descriptor of this
252   /// MachineInstr.
253   const MCInstrDesc &getDesc() const { return *MCID; }
254
255   /// getOpcode - Returns the opcode of this MachineInstr.
256   ///
257   int getOpcode() const { return MCID->Opcode; }
258
259   /// Access to explicit operands of the instruction.
260   ///
261   unsigned getNumOperands() const { return (unsigned)Operands.size(); }
262
263   const MachineOperand& getOperand(unsigned i) const {
264     assert(i < getNumOperands() && "getOperand() out of range!");
265     return Operands[i];
266   }
267   MachineOperand& getOperand(unsigned i) {
268     assert(i < getNumOperands() && "getOperand() out of range!");
269     return Operands[i];
270   }
271
272   /// getNumExplicitOperands - Returns the number of non-implicit operands.
273   ///
274   unsigned getNumExplicitOperands() const;
275
276   /// iterator/begin/end - Iterate over all operands of a machine instruction.
277   typedef std::vector<MachineOperand>::iterator mop_iterator;
278   typedef std::vector<MachineOperand>::const_iterator const_mop_iterator;
279
280   mop_iterator operands_begin() { return Operands.begin(); }
281   mop_iterator operands_end() { return Operands.end(); }
282
283   const_mop_iterator operands_begin() const { return Operands.begin(); }
284   const_mop_iterator operands_end() const { return Operands.end(); }
285
286   /// Access to memory operands of the instruction
287   mmo_iterator memoperands_begin() const { return MemRefs; }
288   mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
289   bool memoperands_empty() const { return NumMemRefs == 0; }
290
291   /// hasOneMemOperand - Return true if this instruction has exactly one
292   /// MachineMemOperand.
293   bool hasOneMemOperand() const {
294     return NumMemRefs == 1;
295   }
296
297   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
298   /// queries but they are bundle aware.
299
300   enum QueryType {
301     IgnoreBundle,    // Ignore bundles
302     AnyInBundle,     // Return true if any instruction in bundle has property
303     AllInBundle      // Return true if all instructions in bundle have property
304   };
305
306   /// hasProperty - Return true if the instruction (or in the case of a bundle,
307   /// the instructions inside the bundle) has the specified property.
308   /// The first argument is the property being queried.
309   /// The second argument indicates whether the query should look inside
310   /// instruction bundles.
311   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
312     // Inline the fast path.
313     if (Type == IgnoreBundle || !isBundle())
314       return getDesc().getFlags() & (1 << MCFlag);
315
316     // If we have a bundle, take the slow path.
317     return hasPropertyInBundle(1 << MCFlag, Type);
318   }
319
320   /// isVariadic - Return true if this instruction can have a variable number of
321   /// operands.  In this case, the variable operands will be after the normal
322   /// operands but before the implicit definitions and uses (if any are
323   /// present).
324   bool isVariadic(QueryType Type = IgnoreBundle) const {
325     return hasProperty(MCID::Variadic, Type);
326   }
327
328   /// hasOptionalDef - Set if this instruction has an optional definition, e.g.
329   /// ARM instructions which can set condition code if 's' bit is set.
330   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
331     return hasProperty(MCID::HasOptionalDef, Type);
332   }
333
334   /// isPseudo - Return true if this is a pseudo instruction that doesn't
335   /// correspond to a real machine instruction.
336   ///
337   bool isPseudo(QueryType Type = IgnoreBundle) const {
338     return hasProperty(MCID::Pseudo, Type);
339   }
340
341   bool isReturn(QueryType Type = AnyInBundle) const {
342     return hasProperty(MCID::Return, Type);
343   }
344
345   bool isCall(QueryType Type = AnyInBundle) const {
346     return hasProperty(MCID::Call, Type);
347   }
348
349   /// isBarrier - Returns true if the specified instruction stops control flow
350   /// from executing the instruction immediately following it.  Examples include
351   /// unconditional branches and return instructions.
352   bool isBarrier(QueryType Type = AnyInBundle) const {
353     return hasProperty(MCID::Barrier, Type);
354   }
355
356   /// isTerminator - Returns true if this instruction part of the terminator for
357   /// a basic block.  Typically this is things like return and branch
358   /// instructions.
359   ///
360   /// Various passes use this to insert code into the bottom of a basic block,
361   /// but before control flow occurs.
362   bool isTerminator(QueryType Type = AnyInBundle) const {
363     return hasProperty(MCID::Terminator, Type);
364   }
365
366   /// isBranch - Returns true if this is a conditional, unconditional, or
367   /// indirect branch.  Predicates below can be used to discriminate between
368   /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
369   /// get more information.
370   bool isBranch(QueryType Type = AnyInBundle) const {
371     return hasProperty(MCID::Branch, Type);
372   }
373
374   /// isIndirectBranch - Return true if this is an indirect branch, such as a
375   /// branch through a register.
376   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
377     return hasProperty(MCID::IndirectBranch, Type);
378   }
379
380   /// isConditionalBranch - Return true if this is a branch which may fall
381   /// through to the next instruction or may transfer control flow to some other
382   /// block.  The TargetInstrInfo::AnalyzeBranch method can be used to get more
383   /// information about this branch.
384   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
385     return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
386   }
387
388   /// isUnconditionalBranch - Return true if this is a branch which always
389   /// transfers control flow to some other block.  The
390   /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
391   /// about this branch.
392   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
393     return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
394   }
395
396   // isPredicable - Return true if this instruction has a predicate operand that
397   // controls execution.  It may be set to 'always', or may be set to other
398   /// values.   There are various methods in TargetInstrInfo that can be used to
399   /// control and modify the predicate in this instruction.
400   bool isPredicable(QueryType Type = AllInBundle) const {
401     // If it's a bundle than all bundled instructions must be predicable for this
402     // to return true.
403     return hasProperty(MCID::Predicable, Type);
404   }
405
406   /// isCompare - Return true if this instruction is a comparison.
407   bool isCompare(QueryType Type = IgnoreBundle) const {
408     return hasProperty(MCID::Compare, Type);
409   }
410
411   /// isMoveImmediate - Return true if this instruction is a move immediate
412   /// (including conditional moves) instruction.
413   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
414     return hasProperty(MCID::MoveImm, Type);
415   }
416
417   /// isBitcast - Return true if this instruction is a bitcast instruction.
418   ///
419   bool isBitcast(QueryType Type = IgnoreBundle) const {
420     return hasProperty(MCID::Bitcast, Type);
421   }
422
423   /// isNotDuplicable - Return true if this instruction cannot be safely
424   /// duplicated.  For example, if the instruction has a unique labels attached
425   /// to it, duplicating it would cause multiple definition errors.
426   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
427     return hasProperty(MCID::NotDuplicable, Type);
428   }
429
430   /// hasDelaySlot - Returns true if the specified instruction has a delay slot
431   /// which must be filled by the code generator.
432   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
433     return hasProperty(MCID::DelaySlot, Type);
434   }
435
436   /// canFoldAsLoad - Return true for instructions that can be folded as
437   /// memory operands in other instructions. The most common use for this
438   /// is instructions that are simple loads from memory that don't modify
439   /// the loaded value in any way, but it can also be used for instructions
440   /// that can be expressed as constant-pool loads, such as V_SETALLONES
441   /// on x86, to allow them to be folded when it is beneficial.
442   /// This should only be set on instructions that return a value in their
443   /// only virtual register definition.
444   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
445     return hasProperty(MCID::FoldableAsLoad, Type);
446   }
447
448   //===--------------------------------------------------------------------===//
449   // Side Effect Analysis
450   //===--------------------------------------------------------------------===//
451
452   /// mayLoad - Return true if this instruction could possibly read memory.
453   /// Instructions with this flag set are not necessarily simple load
454   /// instructions, they may load a value and modify it, for example.
455   bool mayLoad(QueryType Type = AnyInBundle) const {
456     return hasProperty(MCID::MayLoad, Type);
457   }
458
459
460   /// mayStore - Return true if this instruction could possibly modify memory.
461   /// Instructions with this flag set are not necessarily simple store
462   /// instructions, they may store a modified value based on their operands, or
463   /// may not actually modify anything, for example.
464   bool mayStore(QueryType Type = AnyInBundle) const {
465     return hasProperty(MCID::MayStore, Type);
466   }
467
468   //===--------------------------------------------------------------------===//
469   // Flags that indicate whether an instruction can be modified by a method.
470   //===--------------------------------------------------------------------===//
471
472   /// isCommutable - Return true if this may be a 2- or 3-address
473   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
474   /// result if Y and Z are exchanged.  If this flag is set, then the
475   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
476   /// instruction.
477   ///
478   /// Note that this flag may be set on instructions that are only commutable
479   /// sometimes.  In these cases, the call to commuteInstruction will fail.
480   /// Also note that some instructions require non-trivial modification to
481   /// commute them.
482   bool isCommutable(QueryType Type = IgnoreBundle) const {
483     return hasProperty(MCID::Commutable, Type);
484   }
485
486   /// isConvertibleTo3Addr - Return true if this is a 2-address instruction
487   /// which can be changed into a 3-address instruction if needed.  Doing this
488   /// transformation can be profitable in the register allocator, because it
489   /// means that the instruction can use a 2-address form if possible, but
490   /// degrade into a less efficient form if the source and dest register cannot
491   /// be assigned to the same register.  For example, this allows the x86
492   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
493   /// is the same speed as the shift but has bigger code size.
494   ///
495   /// If this returns true, then the target must implement the
496   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
497   /// is allowed to fail if the transformation isn't valid for this specific
498   /// instruction (e.g. shl reg, 4 on x86).
499   ///
500   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
501     return hasProperty(MCID::ConvertibleTo3Addr, Type);
502   }
503
504   /// usesCustomInsertionHook - Return true if this instruction requires
505   /// custom insertion support when the DAG scheduler is inserting it into a
506   /// machine basic block.  If this is true for the instruction, it basically
507   /// means that it is a pseudo instruction used at SelectionDAG time that is
508   /// expanded out into magic code by the target when MachineInstrs are formed.
509   ///
510   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
511   /// is used to insert this into the MachineBasicBlock.
512   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
513     return hasProperty(MCID::UsesCustomInserter, Type);
514   }
515
516   /// hasPostISelHook - Return true if this instruction requires *adjustment*
517   /// after instruction selection by calling a target hook. For example, this
518   /// can be used to fill in ARM 's' optional operand depending on whether
519   /// the conditional flag register is used.
520   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
521     return hasProperty(MCID::HasPostISelHook, Type);
522   }
523
524   /// isRematerializable - Returns true if this instruction is a candidate for
525   /// remat.  This flag is deprecated, please don't use it anymore.  If this
526   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
527   /// verify the instruction is really rematable.
528   bool isRematerializable(QueryType Type = AllInBundle) const {
529     // It's only possible to re-mat a bundle if all bundled instructions are
530     // re-materializable.
531     return hasProperty(MCID::Rematerializable, Type);
532   }
533
534   /// isAsCheapAsAMove - Returns true if this instruction has the same cost (or
535   /// less) than a move instruction. This is useful during certain types of
536   /// optimizations (e.g., remat during two-address conversion or machine licm)
537   /// where we would like to remat or hoist the instruction, but not if it costs
538   /// more than moving the instruction into the appropriate register. Note, we
539   /// are not marking copies from and to the same register class with this flag.
540   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
541     // Only returns true for a bundle if all bundled instructions are cheap.
542     // FIXME: This probably requires a target hook.
543     return hasProperty(MCID::CheapAsAMove, Type);
544   }
545
546   /// hasExtraSrcRegAllocReq - Returns true if this instruction source operands
547   /// have special register allocation requirements that are not captured by the
548   /// operand register classes. e.g. ARM::STRD's two source registers must be an
549   /// even / odd pair, ARM::STM registers have to be in ascending order.
550   /// Post-register allocation passes should not attempt to change allocations
551   /// for sources of instructions with this flag.
552   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
553     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
554   }
555
556   /// hasExtraDefRegAllocReq - Returns true if this instruction def operands
557   /// have special register allocation requirements that are not captured by the
558   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
559   /// even / odd pair, ARM::LDM registers have to be in ascending order.
560   /// Post-register allocation passes should not attempt to change allocations
561   /// for definitions of instructions with this flag.
562   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
563     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
564   }
565
566
567   enum MICheckType {
568     CheckDefs,      // Check all operands for equality
569     CheckKillDead,  // Check all operands including kill / dead markers
570     IgnoreDefs,     // Ignore all definitions
571     IgnoreVRegDefs  // Ignore virtual register definitions
572   };
573
574   /// isIdenticalTo - Return true if this instruction is identical to (same
575   /// opcode and same operands as) the specified instruction.
576   bool isIdenticalTo(const MachineInstr *Other,
577                      MICheckType Check = CheckDefs) const;
578
579   /// removeFromParent - This method unlinks 'this' from the containing basic
580   /// block, and returns it, but does not delete it.
581   MachineInstr *removeFromParent();
582
583   /// eraseFromParent - This method unlinks 'this' from the containing basic
584   /// block and deletes it.
585   void eraseFromParent();
586
587   /// isLabel - Returns true if the MachineInstr represents a label.
588   ///
589   bool isLabel() const {
590     return getOpcode() == TargetOpcode::PROLOG_LABEL ||
591            getOpcode() == TargetOpcode::EH_LABEL ||
592            getOpcode() == TargetOpcode::GC_LABEL;
593   }
594
595   bool isPrologLabel() const {
596     return getOpcode() == TargetOpcode::PROLOG_LABEL;
597   }
598   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
599   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
600   bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
601
602   bool isPHI() const { return getOpcode() == TargetOpcode::PHI; }
603   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
604   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
605   bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
606   bool isStackAligningInlineAsm() const;
607   bool isInsertSubreg() const {
608     return getOpcode() == TargetOpcode::INSERT_SUBREG;
609   }
610   bool isSubregToReg() const {
611     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
612   }
613   bool isRegSequence() const {
614     return getOpcode() == TargetOpcode::REG_SEQUENCE;
615   }
616   bool isBundle() const {
617     return getOpcode() == TargetOpcode::BUNDLE;
618   }
619   bool isCopy() const {
620     return getOpcode() == TargetOpcode::COPY;
621   }
622   bool isFullCopy() const {
623     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
624   }
625
626   /// isCopyLike - Return true if the instruction behaves like a copy.
627   /// This does not include native copy instructions.
628   bool isCopyLike() const {
629     return isCopy() || isSubregToReg();
630   }
631
632   /// isIdentityCopy - Return true is the instruction is an identity copy.
633   bool isIdentityCopy() const {
634     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
635       getOperand(0).getSubReg() == getOperand(1).getSubReg();
636   }
637
638   /// isTransient - Return true if this is a transient instruction that is
639   /// either very likely to be eliminated during register allocation (such as
640   /// copy-like instructions), or if this instruction doesn't have an
641   /// execution-time cost.
642   bool isTransient() const {
643     switch(getOpcode()) {
644     default: return false;
645     // Copy-like instructions are usually eliminated during register allocation.
646     case TargetOpcode::PHI:
647     case TargetOpcode::COPY:
648     case TargetOpcode::INSERT_SUBREG:
649     case TargetOpcode::SUBREG_TO_REG:
650     case TargetOpcode::REG_SEQUENCE:
651     // Pseudo-instructions that don't produce any real output.
652     case TargetOpcode::IMPLICIT_DEF:
653     case TargetOpcode::KILL:
654     case TargetOpcode::PROLOG_LABEL:
655     case TargetOpcode::EH_LABEL:
656     case TargetOpcode::GC_LABEL:
657     case TargetOpcode::DBG_VALUE:
658       return true;
659     }
660   }
661
662   /// getBundleSize - Return the number of instructions inside the MI bundle.
663   unsigned getBundleSize() const;
664
665   /// readsRegister - Return true if the MachineInstr reads the specified
666   /// register. If TargetRegisterInfo is passed, then it also checks if there
667   /// is a read of a super-register.
668   /// This does not count partial redefines of virtual registers as reads:
669   ///   %reg1024:6 = OP.
670   bool readsRegister(unsigned Reg, const TargetRegisterInfo *TRI = NULL) const {
671     return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
672   }
673
674   /// readsVirtualRegister - Return true if the MachineInstr reads the specified
675   /// virtual register. Take into account that a partial define is a
676   /// read-modify-write operation.
677   bool readsVirtualRegister(unsigned Reg) const {
678     return readsWritesVirtualRegister(Reg).first;
679   }
680
681   /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
682   /// indicating if this instruction reads or writes Reg. This also considers
683   /// partial defines.
684   /// If Ops is not null, all operand indices for Reg are added.
685   std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
686                                       SmallVectorImpl<unsigned> *Ops = 0) const;
687
688   /// killsRegister - Return true if the MachineInstr kills the specified
689   /// register. If TargetRegisterInfo is passed, then it also checks if there is
690   /// a kill of a super-register.
691   bool killsRegister(unsigned Reg, const TargetRegisterInfo *TRI = NULL) const {
692     return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
693   }
694
695   /// definesRegister - Return true if the MachineInstr fully defines the
696   /// specified register. If TargetRegisterInfo is passed, then it also checks
697   /// if there is a def of a super-register.
698   /// NOTE: It's ignoring subreg indices on virtual registers.
699   bool definesRegister(unsigned Reg, const TargetRegisterInfo *TRI=NULL) const {
700     return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
701   }
702
703   /// modifiesRegister - Return true if the MachineInstr modifies (fully define
704   /// or partially define) the specified register.
705   /// NOTE: It's ignoring subreg indices on virtual registers.
706   bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
707     return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
708   }
709
710   /// registerDefIsDead - Returns true if the register is dead in this machine
711   /// instruction. If TargetRegisterInfo is passed, then it also checks
712   /// if there is a dead def of a super-register.
713   bool registerDefIsDead(unsigned Reg,
714                          const TargetRegisterInfo *TRI = NULL) const {
715     return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
716   }
717
718   /// findRegisterUseOperandIdx() - Returns the operand index that is a use of
719   /// the specific register or -1 if it is not found. It further tightens
720   /// the search criteria to a use that kills the register if isKill is true.
721   int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
722                                 const TargetRegisterInfo *TRI = NULL) const;
723
724   /// findRegisterUseOperand - Wrapper for findRegisterUseOperandIdx, it returns
725   /// a pointer to the MachineOperand rather than an index.
726   MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
727                                          const TargetRegisterInfo *TRI = NULL) {
728     int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
729     return (Idx == -1) ? NULL : &getOperand(Idx);
730   }
731
732   /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
733   /// the specified register or -1 if it is not found. If isDead is true, defs
734   /// that are not dead are skipped. If Overlap is true, then it also looks for
735   /// defs that merely overlap the specified register. If TargetRegisterInfo is
736   /// non-null, then it also checks if there is a def of a super-register.
737   /// This may also return a register mask operand when Overlap is true.
738   int findRegisterDefOperandIdx(unsigned Reg,
739                                 bool isDead = false, bool Overlap = false,
740                                 const TargetRegisterInfo *TRI = NULL) const;
741
742   /// findRegisterDefOperand - Wrapper for findRegisterDefOperandIdx, it returns
743   /// a pointer to the MachineOperand rather than an index.
744   MachineOperand *findRegisterDefOperand(unsigned Reg, bool isDead = false,
745                                          const TargetRegisterInfo *TRI = NULL) {
746     int Idx = findRegisterDefOperandIdx(Reg, isDead, false, TRI);
747     return (Idx == -1) ? NULL : &getOperand(Idx);
748   }
749
750   /// findFirstPredOperandIdx() - Find the index of the first operand in the
751   /// operand list that is used to represent the predicate. It returns -1 if
752   /// none is found.
753   int findFirstPredOperandIdx() const;
754
755   /// findInlineAsmFlagIdx() - Find the index of the flag word operand that
756   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
757   /// getOperand(OpIdx) does not belong to an inline asm operand group.
758   ///
759   /// If GroupNo is not NULL, it will receive the number of the operand group
760   /// containing OpIdx.
761   ///
762   /// The flag operand is an immediate that can be decoded with methods like
763   /// InlineAsm::hasRegClassConstraint().
764   ///
765   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = 0) const;
766
767   /// getRegClassConstraint - Compute the static register class constraint for
768   /// operand OpIdx.  For normal instructions, this is derived from the
769   /// MCInstrDesc.  For inline assembly it is derived from the flag words.
770   ///
771   /// Returns NULL if the static register classs constraint cannot be
772   /// determined.
773   ///
774   const TargetRegisterClass*
775   getRegClassConstraint(unsigned OpIdx,
776                         const TargetInstrInfo *TII,
777                         const TargetRegisterInfo *TRI) const;
778
779   /// isRegTiedToUseOperand - Given the index of a register def operand,
780   /// check if the register def is tied to a source operand, due to either
781   /// two-address elimination or inline assembly constraints. Returns the
782   /// first tied use operand index by reference if UseOpIdx is not null.
783   bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx = 0) const;
784
785   /// isRegTiedToDefOperand - Return true if the use operand of the specified
786   /// index is tied to an def operand. It also returns the def operand index by
787   /// reference if DefOpIdx is not null.
788   bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx = 0) const;
789
790   /// clearKillInfo - Clears kill flags on all operands.
791   ///
792   void clearKillInfo();
793
794   /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
795   ///
796   void copyKillDeadInfo(const MachineInstr *MI);
797
798   /// copyPredicates - Copies predicate operand(s) from MI.
799   void copyPredicates(const MachineInstr *MI);
800
801   /// substituteRegister - Replace all occurrences of FromReg with ToReg:SubIdx,
802   /// properly composing subreg indices where necessary.
803   void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
804                           const TargetRegisterInfo &RegInfo);
805
806   /// addRegisterKilled - We have determined MI kills a register. Look for the
807   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
808   /// add a implicit operand if it's not found. Returns true if the operand
809   /// exists / is added.
810   bool addRegisterKilled(unsigned IncomingReg,
811                          const TargetRegisterInfo *RegInfo,
812                          bool AddIfNotFound = false);
813
814   /// clearRegisterKills - Clear all kill flags affecting Reg.  If RegInfo is
815   /// provided, this includes super-register kills.
816   void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
817
818   /// addRegisterDead - We have determined MI defined a register without a use.
819   /// Look for the operand that defines it and mark it as IsDead. If
820   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
821   /// true if the operand exists / is added.
822   bool addRegisterDead(unsigned IncomingReg, const TargetRegisterInfo *RegInfo,
823                        bool AddIfNotFound = false);
824
825   /// addRegisterDefined - We have determined MI defines a register. Make sure
826   /// there is an operand defining Reg.
827   void addRegisterDefined(unsigned IncomingReg,
828                           const TargetRegisterInfo *RegInfo = 0);
829
830   /// setPhysRegsDeadExcept - Mark every physreg used by this instruction as
831   /// dead except those in the UsedRegs list.
832   ///
833   /// On instructions with register mask operands, also add implicit-def
834   /// operands for all registers in UsedRegs.
835   void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
836                              const TargetRegisterInfo &TRI);
837
838   /// isSafeToMove - Return true if it is safe to move this instruction. If
839   /// SawStore is set to true, it means that there is a store (or call) between
840   /// the instruction's location and its intended destination.
841   bool isSafeToMove(const TargetInstrInfo *TII, AliasAnalysis *AA,
842                     bool &SawStore) const;
843
844   /// isSafeToReMat - Return true if it's safe to rematerialize the specified
845   /// instruction which defined the specified register instead of copying it.
846   bool isSafeToReMat(const TargetInstrInfo *TII, AliasAnalysis *AA,
847                      unsigned DstReg) const;
848
849   /// hasVolatileMemoryRef - Return true if this instruction may have a
850   /// volatile memory reference, or if the information describing the
851   /// memory reference is not available. Return false if it is known to
852   /// have no volatile memory references.
853   bool hasVolatileMemoryRef() const;
854
855   /// isInvariantLoad - Return true if this instruction is loading from a
856   /// location whose value is invariant across the function.  For example,
857   /// loading a value from the constant pool or from the argument area of
858   /// a function if it does not change.  This should only return true of *all*
859   /// loads the instruction does are invariant (if it does multiple loads).
860   bool isInvariantLoad(AliasAnalysis *AA) const;
861
862   /// isConstantValuePHI - If the specified instruction is a PHI that always
863   /// merges together the same virtual register, return the register, otherwise
864   /// return 0.
865   unsigned isConstantValuePHI() const;
866
867   /// hasUnmodeledSideEffects - Return true if this instruction has side
868   /// effects that are not modeled by mayLoad / mayStore, etc.
869   /// For all instructions, the property is encoded in MCInstrDesc::Flags
870   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
871   /// INLINEASM instruction, in which case the side effect property is encoded
872   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
873   ///
874   bool hasUnmodeledSideEffects() const;
875
876   /// allDefsAreDead - Return true if all the defs of this instruction are dead.
877   ///
878   bool allDefsAreDead() const;
879
880   /// copyImplicitOps - Copy implicit register operands from specified
881   /// instruction to this instruction.
882   void copyImplicitOps(const MachineInstr *MI);
883
884   //
885   // Debugging support
886   //
887   void print(raw_ostream &OS, const TargetMachine *TM = 0) const;
888   void dump() const;
889
890   //===--------------------------------------------------------------------===//
891   // Accessors used to build up machine instructions.
892
893   /// addOperand - Add the specified operand to the instruction.  If it is an
894   /// implicit operand, it is added to the end of the operand list.  If it is
895   /// an explicit operand it is added at the end of the explicit operand list
896   /// (before the first implicit operand).
897   void addOperand(const MachineOperand &Op);
898
899   /// setDesc - Replace the instruction descriptor (thus opcode) of
900   /// the current instruction with a new one.
901   ///
902   void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
903
904   /// setDebugLoc - Replace current source information with new such.
905   /// Avoid using this, the constructor argument is preferable.
906   ///
907   void setDebugLoc(const DebugLoc dl) { debugLoc = dl; }
908
909   /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
910   /// fewer operand than it started with.
911   ///
912   void RemoveOperand(unsigned i);
913
914   /// addMemOperand - Add a MachineMemOperand to the machine instruction.
915   /// This function should be used only occasionally. The setMemRefs function
916   /// is the primary method for setting up a MachineInstr's MemRefs list.
917   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
918
919   /// setMemRefs - Assign this MachineInstr's memory reference descriptor
920   /// list. This does not transfer ownership.
921   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
922     MemRefs = NewMemRefs;
923     NumMemRefs = NewMemRefsEnd - NewMemRefs;
924   }
925
926 private:
927   /// getRegInfo - If this instruction is embedded into a MachineFunction,
928   /// return the MachineRegisterInfo object for the current function, otherwise
929   /// return null.
930   MachineRegisterInfo *getRegInfo();
931
932   /// addImplicitDefUseOperands - Add all implicit def and use operands to
933   /// this instruction.
934   void addImplicitDefUseOperands();
935
936   /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
937   /// this instruction from their respective use lists.  This requires that the
938   /// operands already be on their use lists.
939   void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
940
941   /// AddRegOperandsToUseLists - Add all of the register operands in
942   /// this instruction from their respective use lists.  This requires that the
943   /// operands not be on their use lists yet.
944   void AddRegOperandsToUseLists(MachineRegisterInfo&);
945
946   /// hasPropertyInBundle - Slow path for hasProperty when we're dealing with a
947   /// bundle.
948   bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
949 };
950
951 /// MachineInstrExpressionTrait - Special DenseMapInfo traits to compare
952 /// MachineInstr* by *value* of the instruction rather than by pointer value.
953 /// The hashing and equality testing functions ignore definitions so this is
954 /// useful for CSE, etc.
955 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
956   static inline MachineInstr *getEmptyKey() {
957     return 0;
958   }
959
960   static inline MachineInstr *getTombstoneKey() {
961     return reinterpret_cast<MachineInstr*>(-1);
962   }
963
964   static unsigned getHashValue(const MachineInstr* const &MI);
965
966   static bool isEqual(const MachineInstr* const &LHS,
967                       const MachineInstr* const &RHS) {
968     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
969         LHS == getEmptyKey() || LHS == getTombstoneKey())
970       return LHS == RHS;
971     return LHS->isIdenticalTo(RHS, MachineInstr::IgnoreVRegDefs);
972   }
973 };
974
975 //===----------------------------------------------------------------------===//
976 // Debugging Support
977
978 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
979   MI.print(OS);
980   return OS;
981 }
982
983 } // End llvm namespace
984
985 #endif