TargetInstrInfo.h revision 7ed47a13356daed2a34cd2209a31f92552e3bdd8
1//===-- llvm/Target/TargetInstrInfo.h - Instruction Info --------*- 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 describes the target machine instructions to the code generator.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TARGET_TARGETINSTRINFO_H
15#define LLVM_TARGET_TARGETINSTRINFO_H
16
17#include "llvm/CodeGen/MachineBasicBlock.h"
18#include "llvm/CodeGen/MachineFunction.h"
19#include "llvm/Support/DataTypes.h"
20#include <vector>
21#include <cassert>
22
23namespace llvm {
24
25class MachineInstr;
26class TargetMachine;
27class TargetRegisterClass;
28class LiveVariables;
29
30//---------------------------------------------------------------------------
31// Data types used to define information about a single machine instruction
32//---------------------------------------------------------------------------
33
34typedef short MachineOpCode;
35typedef unsigned InstrSchedClass;
36
37//---------------------------------------------------------------------------
38// struct TargetInstrDescriptor:
39//  Predefined information about each machine instruction.
40//  Designed to initialized statically.
41//
42
43const unsigned M_BRANCH_FLAG           = 1 << 0;
44const unsigned M_CALL_FLAG             = 1 << 1;
45const unsigned M_RET_FLAG              = 1 << 2;
46const unsigned M_BARRIER_FLAG          = 1 << 3;
47const unsigned M_DELAY_SLOT_FLAG       = 1 << 4;
48const unsigned M_LOAD_FLAG             = 1 << 5;
49const unsigned M_STORE_FLAG            = 1 << 6;
50const unsigned M_INDIRECT_FLAG         = 1 << 7;
51const unsigned M_IMPLICIT_DEF_FLAG     = 1 << 8;
52
53// M_CONVERTIBLE_TO_3_ADDR - This is a 2-address instruction which can be
54// changed into a 3-address instruction if the first two operands cannot be
55// assigned to the same register.  The target must implement the
56// TargetInstrInfo::convertToThreeAddress method for this instruction.
57const unsigned M_CONVERTIBLE_TO_3_ADDR = 1 << 9;
58
59// This M_COMMUTABLE - is a 2- or 3-address instruction (of the form X = op Y,
60// Z), which produces the same result if Y and Z are exchanged.
61const unsigned M_COMMUTABLE            = 1 << 10;
62
63// M_TERMINATOR_FLAG - Is this instruction part of the terminator for a basic
64// block?  Typically this is things like return and branch instructions.
65// Various passes use this to insert code into the bottom of a basic block, but
66// before control flow occurs.
67const unsigned M_TERMINATOR_FLAG       = 1 << 11;
68
69// M_USES_CUSTOM_DAG_SCHED_INSERTION - Set if this instruction requires custom
70// insertion support when the DAG scheduler is inserting it into a machine basic
71// block.
72const unsigned M_USES_CUSTOM_DAG_SCHED_INSERTION = 1 << 12;
73
74// M_VARIABLE_OPS - Set if this instruction can have a variable number of extra
75// operands in addition to the minimum number operands specified.
76const unsigned M_VARIABLE_OPS          = 1 << 13;
77
78// M_PREDICABLE - Set if this instruction has a predicate operand that
79// controls execution. It may be set to 'always'.
80const unsigned M_PREDICABLE            = 1 << 14;
81
82// M_REMATERIALIZIBLE - Set if this instruction can be trivally re-materialized
83// at any time, e.g. constant generation, load from constant pool.
84const unsigned M_REMATERIALIZIBLE      = 1 << 15;
85
86// M_NOT_DUPLICABLE - Set if this instruction cannot be safely duplicated.
87// (e.g. instructions with unique labels attached).
88const unsigned M_NOT_DUPLICABLE        = 1 << 16;
89
90// M_HAS_OPTIONAL_DEF - Set if this instruction has an optional definition, e.g.
91// ARM instructions which can set condition code if 's' bit is set.
92const unsigned M_HAS_OPTIONAL_DEF      = 1 << 17;
93
94// M_NEVER_HAS_SIDE_EFFECTS - Set if this instruction has no side effects that
95// are not captured by any operands of the instruction or other flags, and when
96// *all* instances of the instruction of that opcode have no side effects.
97//
98// Note: This and M_MAY_HAVE_SIDE_EFFECTS are mutually exclusive. You can't set
99// both! If neither flag is set, then the instruction *always* has side effects.
100const unsigned M_NEVER_HAS_SIDE_EFFECTS = 1 << 18;
101
102// M_MAY_HAVE_SIDE_EFFECTS - Set if some instances of this instruction can have
103// side effects. The virtual method "isReallySideEffectFree" is called to
104// determine this. Load instructions are an example of where this is useful. In
105// general, loads always have side effects. However, loads from constant pools
106// don't. We let the specific back end make this determination.
107//
108// Note: This and M_NEVER_HAS_SIDE_EFFECTS are mutually exclusive. You can't set
109// both! If neither flag is set, then the instruction *always* has side effects.
110const unsigned M_MAY_HAVE_SIDE_EFFECTS = 1 << 19;
111
112// Machine operand flags
113// M_LOOK_UP_PTR_REG_CLASS - Set if this operand is a pointer value and it
114// requires a callback to look up its register class.
115const unsigned M_LOOK_UP_PTR_REG_CLASS = 1 << 0;
116
117/// M_PREDICATE_OPERAND - Set if this is one of the operands that made up of the
118/// predicate operand that controls an M_PREDICATED instruction.
119const unsigned M_PREDICATE_OPERAND = 1 << 1;
120
121/// M_OPTIONAL_DEF_OPERAND - Set if this operand is a optional def.
122///
123const unsigned M_OPTIONAL_DEF_OPERAND = 1 << 2;
124
125namespace TOI {
126  // Operand constraints: only "tied_to" for now.
127  enum OperandConstraint {
128    TIED_TO = 0  // Must be allocated the same register as.
129  };
130}
131
132/// TargetOperandInfo - This holds information about one operand of a machine
133/// instruction, indicating the register class for register operands, etc.
134///
135class TargetOperandInfo {
136public:
137  /// RegClass - This specifies the register class enumeration of the operand
138  /// if the operand is a register.  If not, this contains 0.
139  unsigned short RegClass;
140  unsigned short Flags;
141  /// Lower 16 bits are used to specify which constraints are set. The higher 16
142  /// bits are used to specify the value of constraints (4 bits each).
143  unsigned int Constraints;
144  /// Currently no other information.
145};
146
147
148class TargetInstrDescriptor {
149public:
150  MachineOpCode   Opcode;        // The opcode.
151  unsigned short  numOperands;   // Num of args (may be more if variable_ops).
152  unsigned short  numDefs;       // Num of args that are definitions.
153  const char *    Name;          // Assembly language mnemonic for the opcode.
154  InstrSchedClass schedClass;    // enum  identifying instr sched class
155  unsigned        Flags;         // flags identifying machine instr class
156  unsigned        TSFlags;       // Target Specific Flag values
157  const unsigned *ImplicitUses;  // Registers implicitly read by this instr
158  const unsigned *ImplicitDefs;  // Registers implicitly defined by this instr
159  const TargetOperandInfo *OpInfo; // 'numOperands' entries about operands.
160
161  /// getOperandConstraint - Returns the value of the specific constraint if
162  /// it is set. Returns -1 if it is not set.
163  int getOperandConstraint(unsigned OpNum,
164                           TOI::OperandConstraint Constraint) const {
165    assert((OpNum < numOperands || (Flags & M_VARIABLE_OPS)) &&
166           "Invalid operand # of TargetInstrInfo");
167    if (OpNum < numOperands &&
168        (OpInfo[OpNum].Constraints & (1 << Constraint))) {
169      unsigned Pos = 16 + Constraint * 4;
170      return (int)(OpInfo[OpNum].Constraints >> Pos) & 0xf;
171    }
172    return -1;
173  }
174
175  /// findTiedToSrcOperand - Returns the operand that is tied to the specified
176  /// dest operand. Returns -1 if there isn't one.
177  int findTiedToSrcOperand(unsigned OpNum) const;
178};
179
180
181//---------------------------------------------------------------------------
182///
183/// TargetInstrInfo - Interface to description of machine instructions
184///
185class TargetInstrInfo {
186  const TargetInstrDescriptor* desc;    // raw array to allow static init'n
187  unsigned NumOpcodes;                  // number of entries in the desc array
188  unsigned numRealOpCodes;              // number of non-dummy op codes
189
190  TargetInstrInfo(const TargetInstrInfo &);  // DO NOT IMPLEMENT
191  void operator=(const TargetInstrInfo &);   // DO NOT IMPLEMENT
192public:
193  TargetInstrInfo(const TargetInstrDescriptor *desc, unsigned NumOpcodes);
194  virtual ~TargetInstrInfo();
195
196  // Invariant opcodes: All instruction sets have these as their low opcodes.
197  enum {
198    PHI = 0,
199    INLINEASM = 1,
200    LABEL = 2,
201    EXTRACT_SUBREG = 3,
202    INSERT_SUBREG = 4
203  };
204
205  unsigned getNumOpcodes() const { return NumOpcodes; }
206
207  /// get - Return the machine instruction descriptor that corresponds to the
208  /// specified instruction opcode.
209  ///
210  const TargetInstrDescriptor& get(MachineOpCode Opcode) const {
211    assert((unsigned)Opcode < NumOpcodes);
212    return desc[Opcode];
213  }
214
215  const char *getName(MachineOpCode Opcode) const {
216    return get(Opcode).Name;
217  }
218
219  int getNumOperands(MachineOpCode Opcode) const {
220    return get(Opcode).numOperands;
221  }
222
223  int getNumDefs(MachineOpCode Opcode) const {
224    return get(Opcode).numDefs;
225  }
226
227  InstrSchedClass getSchedClass(MachineOpCode Opcode) const {
228    return get(Opcode).schedClass;
229  }
230
231  const unsigned *getImplicitUses(MachineOpCode Opcode) const {
232    return get(Opcode).ImplicitUses;
233  }
234
235  const unsigned *getImplicitDefs(MachineOpCode Opcode) const {
236    return get(Opcode).ImplicitDefs;
237  }
238
239
240  //
241  // Query instruction class flags according to the machine-independent
242  // flags listed above.
243  //
244  bool isReturn(MachineOpCode Opcode) const {
245    return get(Opcode).Flags & M_RET_FLAG;
246  }
247
248  bool isCommutableInstr(MachineOpCode Opcode) const {
249    return get(Opcode).Flags & M_COMMUTABLE;
250  }
251  bool isTerminatorInstr(MachineOpCode Opcode) const {
252    return get(Opcode).Flags & M_TERMINATOR_FLAG;
253  }
254
255  bool isBranch(MachineOpCode Opcode) const {
256    return get(Opcode).Flags & M_BRANCH_FLAG;
257  }
258
259  bool isIndirectBranch(MachineOpCode Opcode) const {
260    return get(Opcode).Flags & M_INDIRECT_FLAG;
261  }
262
263  /// isBarrier - Returns true if the specified instruction stops control flow
264  /// from executing the instruction immediately following it.  Examples include
265  /// unconditional branches and return instructions.
266  bool isBarrier(MachineOpCode Opcode) const {
267    return get(Opcode).Flags & M_BARRIER_FLAG;
268  }
269
270  bool isCall(MachineOpCode Opcode) const {
271    return get(Opcode).Flags & M_CALL_FLAG;
272  }
273  bool isLoad(MachineOpCode Opcode) const {
274    return get(Opcode).Flags & M_LOAD_FLAG;
275  }
276  bool isStore(MachineOpCode Opcode) const {
277    return get(Opcode).Flags & M_STORE_FLAG;
278  }
279
280  /// hasDelaySlot - Returns true if the specified instruction has a delay slot
281  /// which must be filled by the code generator.
282  bool hasDelaySlot(MachineOpCode Opcode) const {
283    return get(Opcode).Flags & M_DELAY_SLOT_FLAG;
284  }
285
286  /// usesCustomDAGSchedInsertionHook - Return true if this instruction requires
287  /// custom insertion support when the DAG scheduler is inserting it into a
288  /// machine basic block.
289  bool usesCustomDAGSchedInsertionHook(MachineOpCode Opcode) const {
290    return get(Opcode).Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION;
291  }
292
293  bool hasVariableOperands(MachineOpCode Opcode) const {
294    return get(Opcode).Flags & M_VARIABLE_OPS;
295  }
296
297  bool isPredicable(MachineOpCode Opcode) const {
298    return get(Opcode).Flags & M_PREDICABLE;
299  }
300
301  bool isNotDuplicable(MachineOpCode Opcode) const {
302    return get(Opcode).Flags & M_NOT_DUPLICABLE;
303  }
304
305  bool hasOptionalDef(MachineOpCode Opcode) const {
306    return get(Opcode).Flags & M_HAS_OPTIONAL_DEF;
307  }
308
309  /// isTriviallyReMaterializable - Return true if the instruction is trivially
310  /// rematerializable, meaning it has no side effects and requires no operands
311  /// that aren't always available.
312  bool isTriviallyReMaterializable(MachineInstr *MI) const {
313    return (MI->getInstrDescriptor()->Flags & M_REMATERIALIZIBLE) &&
314           isReallyTriviallyReMaterializable(MI);
315  }
316
317  /// hasUnmodelledSideEffects - Returns true if the instruction has side
318  /// effects that are not captured by any operands of the instruction or other
319  /// flags.
320  bool hasUnmodelledSideEffects(MachineInstr *MI) const {
321    const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
322    if (!(TID->Flags & M_NEVER_HAS_SIDE_EFFECTS ||
323          TID->Flags & M_MAY_HAVE_SIDE_EFFECTS)) return true;
324    if (TID->Flags & M_NEVER_HAS_SIDE_EFFECTS) return false;
325    return !isReallySideEffectFree(MI); // May have side effects
326  }
327protected:
328  /// isReallyTriviallyReMaterializable - For instructions with opcodes for
329  /// which the M_REMATERIALIZABLE flag is set, this function tests whether the
330  /// instruction itself is actually trivially rematerializable, considering
331  /// its operands.  This is used for targets that have instructions that are
332  /// only trivially rematerializable for specific uses.  This predicate must
333  /// return false if the instruction has any side effects other than
334  /// producing a value, or if it requres any address registers that are not
335  /// always available.
336  virtual bool isReallyTriviallyReMaterializable(MachineInstr *MI) const {
337    return true;
338  }
339
340  /// isReallySideEffectFree - If the M_MAY_HAVE_SIDE_EFFECTS flag is set, this
341  /// method is called to determine if the specific instance of this
342  /// instruction has side effects. This is useful in cases of instructions,
343  /// like loads, which generally always have side effects. A load from a
344  /// constant pool doesn't have side effects, though. So we need to
345  /// differentiate it from the general case.
346  virtual bool isReallySideEffectFree(MachineInstr *MI) const {
347    return false;
348  }
349public:
350  /// getOperandConstraint - Returns the value of the specific constraint if
351  /// it is set. Returns -1 if it is not set.
352  int getOperandConstraint(MachineOpCode Opcode, unsigned OpNum,
353                           TOI::OperandConstraint Constraint) const {
354    return get(Opcode).getOperandConstraint(OpNum, Constraint);
355  }
356
357  /// Return true if the instruction is a register to register move
358  /// and leave the source and dest operands in the passed parameters.
359  virtual bool isMoveInstr(const MachineInstr& MI,
360                           unsigned& sourceReg,
361                           unsigned& destReg) const {
362    return false;
363  }
364
365  /// isLoadFromStackSlot - If the specified machine instruction is a direct
366  /// load from a stack slot, return the virtual or physical register number of
367  /// the destination along with the FrameIndex of the loaded stack slot.  If
368  /// not, return 0.  This predicate must return 0 if the instruction has
369  /// any side effects other than loading from the stack slot.
370  virtual unsigned isLoadFromStackSlot(MachineInstr *MI, int &FrameIndex) const{
371    return 0;
372  }
373
374  /// isStoreToStackSlot - If the specified machine instruction is a direct
375  /// store to a stack slot, return the virtual or physical register number of
376  /// the source reg along with the FrameIndex of the loaded stack slot.  If
377  /// not, return 0.  This predicate must return 0 if the instruction has
378  /// any side effects other than storing to the stack slot.
379  virtual unsigned isStoreToStackSlot(MachineInstr *MI, int &FrameIndex) const {
380    return 0;
381  }
382
383  /// convertToThreeAddress - This method must be implemented by targets that
384  /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
385  /// may be able to convert a two-address instruction into one or more true
386  /// three-address instructions on demand.  This allows the X86 target (for
387  /// example) to convert ADD and SHL instructions into LEA instructions if they
388  /// would require register copies due to two-addressness.
389  ///
390  /// This method returns a null pointer if the transformation cannot be
391  /// performed, otherwise it returns the last new instruction.
392  ///
393  virtual MachineInstr *
394  convertToThreeAddress(MachineFunction::iterator &MFI,
395                   MachineBasicBlock::iterator &MBBI, LiveVariables &LV) const {
396    return 0;
397  }
398
399  /// commuteInstruction - If a target has any instructions that are commutable,
400  /// but require converting to a different instruction or making non-trivial
401  /// changes to commute them, this method can overloaded to do this.  The
402  /// default implementation of this method simply swaps the first two operands
403  /// of MI and returns it.
404  ///
405  /// If a target wants to make more aggressive changes, they can construct and
406  /// return a new machine instruction.  If an instruction cannot commute, it
407  /// can also return null.
408  ///
409  virtual MachineInstr *commuteInstruction(MachineInstr *MI) const;
410
411  /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
412  /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
413  /// implemented for a target).  Upon success, this returns false and returns
414  /// with the following information in various cases:
415  ///
416  /// 1. If this block ends with no branches (it just falls through to its succ)
417  ///    just return false, leaving TBB/FBB null.
418  /// 2. If this block ends with only an unconditional branch, it sets TBB to be
419  ///    the destination block.
420  /// 3. If this block ends with an conditional branch and it falls through to
421  ///    an successor block, it sets TBB to be the branch destination block and a
422  ///    list of operands that evaluate the condition. These
423  ///    operands can be passed to other TargetInstrInfo methods to create new
424  ///    branches.
425  /// 4. If this block ends with an conditional branch and an unconditional
426  ///    block, it returns the 'true' destination in TBB, the 'false' destination
427  ///    in FBB, and a list of operands that evaluate the condition. These
428  ///    operands can be passed to other TargetInstrInfo methods to create new
429  ///    branches.
430  ///
431  /// Note that RemoveBranch and InsertBranch must be implemented to support
432  /// cases where this method returns success.
433  ///
434  virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
435                             MachineBasicBlock *&FBB,
436                             std::vector<MachineOperand> &Cond) const {
437    return true;
438  }
439
440  /// RemoveBranch - Remove the branching code at the end of the specific MBB.
441  /// this is only invoked in cases where AnalyzeBranch returns success. It
442  /// returns the number of instructions that were removed.
443  virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
444    assert(0 && "Target didn't implement TargetInstrInfo::RemoveBranch!");
445    return 0;
446  }
447
448  /// InsertBranch - Insert a branch into the end of the specified
449  /// MachineBasicBlock.  This operands to this method are the same as those
450  /// returned by AnalyzeBranch.  This is invoked in cases where AnalyzeBranch
451  /// returns success and when an unconditional branch (TBB is non-null, FBB is
452  /// null, Cond is empty) needs to be inserted. It returns the number of
453  /// instructions inserted.
454  virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
455                            MachineBasicBlock *FBB,
456                            const std::vector<MachineOperand> &Cond) const {
457    assert(0 && "Target didn't implement TargetInstrInfo::InsertBranch!");
458    return 0;
459  }
460
461  /// BlockHasNoFallThrough - Return true if the specified block does not
462  /// fall-through into its successor block.  This is primarily used when a
463  /// branch is unanalyzable.  It is useful for things like unconditional
464  /// indirect branches (jump tables).
465  virtual bool BlockHasNoFallThrough(MachineBasicBlock &MBB) const {
466    return false;
467  }
468
469  /// ReverseBranchCondition - Reverses the branch condition of the specified
470  /// condition list, returning false on success and true if it cannot be
471  /// reversed.
472  virtual bool ReverseBranchCondition(std::vector<MachineOperand> &Cond) const {
473    return true;
474  }
475
476  /// insertNoop - Insert a noop into the instruction stream at the specified
477  /// point.
478  virtual void insertNoop(MachineBasicBlock &MBB,
479                          MachineBasicBlock::iterator MI) const {
480    assert(0 && "Target didn't implement insertNoop!");
481    abort();
482  }
483
484  /// isPredicated - Returns true if the instruction is already predicated.
485  ///
486  virtual bool isPredicated(const MachineInstr *MI) const {
487    return false;
488  }
489
490  /// isUnpredicatedTerminator - Returns true if the instruction is a
491  /// terminator instruction that has not been predicated.
492  virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
493
494  /// PredicateInstruction - Convert the instruction into a predicated
495  /// instruction. It returns true if the operation was successful.
496  virtual
497  bool PredicateInstruction(MachineInstr *MI,
498                            const std::vector<MachineOperand> &Pred) const;
499
500  /// SubsumesPredicate - Returns true if the first specified predicate
501  /// subsumes the second, e.g. GE subsumes GT.
502  virtual
503  bool SubsumesPredicate(const std::vector<MachineOperand> &Pred1,
504                         const std::vector<MachineOperand> &Pred2) const {
505    return false;
506  }
507
508  /// DefinesPredicate - If the specified instruction defines any predicate
509  /// or condition code register(s) used for predication, returns true as well
510  /// as the definition predicate(s) by reference.
511  virtual bool DefinesPredicate(MachineInstr *MI,
512                                std::vector<MachineOperand> &Pred) const {
513    return false;
514  }
515
516  /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
517  /// values.
518  virtual const TargetRegisterClass *getPointerRegClass() const {
519    assert(0 && "Target didn't implement getPointerRegClass!");
520    abort();
521    return 0; // Must return a value in order to compile with VS 2005
522  }
523};
524
525} // End llvm namespace
526
527#endif
528