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