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