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