TargetInstrInfo.h revision 6e141fd04897e5eb4925bb6351297170ebd8a756
1//===-- llvm/Target/TargetInstrInfo.h - Instruction Info --------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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// Machine operand flags
95// M_LOOK_UP_PTR_REG_CLASS - Set if this operand is a pointer value and it
96// requires a callback to look up its register class.
97const unsigned M_LOOK_UP_PTR_REG_CLASS = 1 << 0;
98
99/// M_PREDICATE_OPERAND - Set if this is one of the operands that made up of the
100/// predicate operand that controls an M_PREDICATED instruction.
101const unsigned M_PREDICATE_OPERAND = 1 << 1;
102
103/// M_OPTIONAL_DEF_OPERAND - Set if this operand is a optional def.
104///
105const unsigned M_OPTIONAL_DEF_OPERAND = 1 << 2;
106
107namespace TOI {
108  // Operand constraints: only "tied_to" for now.
109  enum OperandConstraint {
110    TIED_TO = 0  // Must be allocated the same register as.
111  };
112}
113
114/// TargetOperandInfo - This holds information about one operand of a machine
115/// instruction, indicating the register class for register operands, etc.
116///
117class TargetOperandInfo {
118public:
119  /// RegClass - This specifies the register class enumeration of the operand
120  /// if the operand is a register.  If not, this contains 0.
121  unsigned short RegClass;
122  unsigned short Flags;
123  /// Lower 16 bits are used to specify which constraints are set. The higher 16
124  /// bits are used to specify the value of constraints (4 bits each).
125  unsigned int Constraints;
126  /// Currently no other information.
127};
128
129
130class TargetInstrDescriptor {
131public:
132  MachineOpCode   Opcode;        // The opcode.
133  unsigned short  numOperands;   // Num of args (may be more if variable_ops).
134  unsigned short  numDefs;       // Num of args that are definitions.
135  const char *    Name;          // Assembly language mnemonic for the opcode.
136  InstrSchedClass schedClass;    // enum  identifying instr sched class
137  unsigned        Flags;         // flags identifying machine instr class
138  unsigned        TSFlags;       // Target Specific Flag values
139  const unsigned *ImplicitUses;  // Registers implicitly read by this instr
140  const unsigned *ImplicitDefs;  // Registers implicitly defined by this instr
141  const TargetOperandInfo *OpInfo; // 'numOperands' entries about operands.
142
143  /// getOperandConstraint - Returns the value of the specific constraint if
144  /// it is set. Returns -1 if it is not set.
145  int getOperandConstraint(unsigned OpNum,
146                           TOI::OperandConstraint Constraint) const {
147    assert((OpNum < numOperands || (Flags & M_VARIABLE_OPS)) &&
148           "Invalid operand # of TargetInstrInfo");
149    if (OpNum < numOperands &&
150        (OpInfo[OpNum].Constraints & (1 << Constraint))) {
151      unsigned Pos = 16 + Constraint * 4;
152      return (int)(OpInfo[OpNum].Constraints >> Pos) & 0xf;
153    }
154    return -1;
155  }
156
157  /// findTiedToSrcOperand - Returns the operand that is tied to the specified
158  /// dest operand. Returns -1 if there isn't one.
159  int findTiedToSrcOperand(unsigned OpNum) const;
160};
161
162
163//---------------------------------------------------------------------------
164///
165/// TargetInstrInfo - Interface to description of machine instructions
166///
167class TargetInstrInfo {
168  const TargetInstrDescriptor* desc;    // raw array to allow static init'n
169  unsigned NumOpcodes;                  // number of entries in the desc array
170  unsigned numRealOpCodes;              // number of non-dummy op codes
171
172  TargetInstrInfo(const TargetInstrInfo &);  // DO NOT IMPLEMENT
173  void operator=(const TargetInstrInfo &);   // DO NOT IMPLEMENT
174public:
175  TargetInstrInfo(const TargetInstrDescriptor *desc, unsigned NumOpcodes);
176  virtual ~TargetInstrInfo();
177
178  // Invariant opcodes: All instruction sets have these as their low opcodes.
179  enum {
180    PHI = 0,
181    INLINEASM = 1,
182    LABEL = 2,
183    EXTRACT_SUBREG = 3,
184    INSERT_SUBREG = 4
185  };
186
187  unsigned getNumOpcodes() const { return NumOpcodes; }
188
189  /// get - Return the machine instruction descriptor that corresponds to the
190  /// specified instruction opcode.
191  ///
192  const TargetInstrDescriptor& get(MachineOpCode Opcode) const {
193    assert((unsigned)Opcode < NumOpcodes);
194    return desc[Opcode];
195  }
196
197  const char *getName(MachineOpCode Opcode) const {
198    return get(Opcode).Name;
199  }
200
201  int getNumOperands(MachineOpCode Opcode) const {
202    return get(Opcode).numOperands;
203  }
204
205  int getNumDefs(MachineOpCode Opcode) const {
206    return get(Opcode).numDefs;
207  }
208
209  InstrSchedClass getSchedClass(MachineOpCode Opcode) const {
210    return get(Opcode).schedClass;
211  }
212
213  const unsigned *getImplicitUses(MachineOpCode Opcode) const {
214    return get(Opcode).ImplicitUses;
215  }
216
217  const unsigned *getImplicitDefs(MachineOpCode Opcode) const {
218    return get(Opcode).ImplicitDefs;
219  }
220
221
222  //
223  // Query instruction class flags according to the machine-independent
224  // flags listed above.
225  //
226  bool isReturn(MachineOpCode Opcode) const {
227    return get(Opcode).Flags & M_RET_FLAG;
228  }
229
230  bool isCommutableInstr(MachineOpCode Opcode) const {
231    return get(Opcode).Flags & M_COMMUTABLE;
232  }
233  bool isTerminatorInstr(MachineOpCode Opcode) const {
234    return get(Opcode).Flags & M_TERMINATOR_FLAG;
235  }
236
237  bool isBranch(MachineOpCode Opcode) const {
238    return get(Opcode).Flags & M_BRANCH_FLAG;
239  }
240
241  bool isIndirectBranch(MachineOpCode Opcode) const {
242    return get(Opcode).Flags & M_INDIRECT_FLAG;
243  }
244
245  /// isBarrier - Returns true if the specified instruction stops control flow
246  /// from executing the instruction immediately following it.  Examples include
247  /// unconditional branches and return instructions.
248  bool isBarrier(MachineOpCode Opcode) const {
249    return get(Opcode).Flags & M_BARRIER_FLAG;
250  }
251
252  bool isCall(MachineOpCode Opcode) const {
253    return get(Opcode).Flags & M_CALL_FLAG;
254  }
255  bool isLoad(MachineOpCode Opcode) const {
256    return get(Opcode).Flags & M_LOAD_FLAG;
257  }
258  bool isStore(MachineOpCode Opcode) const {
259    return get(Opcode).Flags & M_STORE_FLAG;
260  }
261
262  /// hasDelaySlot - Returns true if the specified instruction has a delay slot
263  /// which must be filled by the code generator.
264  bool hasDelaySlot(MachineOpCode Opcode) const {
265    return get(Opcode).Flags & M_DELAY_SLOT_FLAG;
266  }
267
268  /// usesCustomDAGSchedInsertionHook - Return true if this instruction requires
269  /// custom insertion support when the DAG scheduler is inserting it into a
270  /// machine basic block.
271  bool usesCustomDAGSchedInsertionHook(MachineOpCode Opcode) const {
272    return get(Opcode).Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION;
273  }
274
275  bool hasVariableOperands(MachineOpCode Opcode) const {
276    return get(Opcode).Flags & M_VARIABLE_OPS;
277  }
278
279  bool isPredicable(MachineOpCode Opcode) const {
280    return get(Opcode).Flags & M_PREDICABLE;
281  }
282
283  bool isNotDuplicable(MachineOpCode Opcode) const {
284    return get(Opcode).Flags & M_NOT_DUPLICABLE;
285  }
286
287  bool hasOptionalDef(MachineOpCode Opcode) const {
288    return get(Opcode).Flags & M_HAS_OPTIONAL_DEF;
289  }
290
291  /// isTriviallyReMaterializable - Return true if the instruction is trivially
292  /// rematerializable, meaning it has no side effects and requires no operands
293  /// that aren't always available.
294  bool isTriviallyReMaterializable(MachineInstr *MI) const {
295    return (MI->getInstrDescriptor()->Flags & M_REMATERIALIZIBLE) &&
296           isReallyTriviallyReMaterializable(MI);
297  }
298
299protected:
300  /// isReallyTriviallyReMaterializable - For instructions with opcodes for
301  /// which the M_REMATERIALIZABLE flag is set, this function tests whether the
302  /// instruction itself is actually trivially rematerializable, considering
303  /// its operands.  This is used for targets that have instructions that are
304  /// only trivially rematerializable for specific uses.  This predicate must
305  /// return false if the instruction has any side effects other than
306  /// producing a value, or if it requres any address registers that are not
307  /// always available.
308  virtual bool isReallyTriviallyReMaterializable(MachineInstr *MI) const {
309    return true;
310  }
311
312public:
313  /// getOperandConstraint - Returns the value of the specific constraint if
314  /// it is set. Returns -1 if it is not set.
315  int getOperandConstraint(MachineOpCode Opcode, unsigned OpNum,
316                           TOI::OperandConstraint Constraint) const {
317    return get(Opcode).getOperandConstraint(OpNum, Constraint);
318  }
319
320  /// Return true if the instruction is a register to register move
321  /// and leave the source and dest operands in the passed parameters.
322  virtual bool isMoveInstr(const MachineInstr& MI,
323                           unsigned& sourceReg,
324                           unsigned& destReg) const {
325    return false;
326  }
327
328  /// isLoadFromStackSlot - If the specified machine instruction is a direct
329  /// load from a stack slot, return the virtual or physical register number of
330  /// the destination along with the FrameIndex of the loaded stack slot.  If
331  /// not, return 0.  This predicate must return 0 if the instruction has
332  /// any side effects other than loading from the stack slot.
333  virtual unsigned isLoadFromStackSlot(MachineInstr *MI, int &FrameIndex) const{
334    return 0;
335  }
336
337  /// isStoreToStackSlot - If the specified machine instruction is a direct
338  /// store to a stack slot, return the virtual or physical register number of
339  /// the source reg along with the FrameIndex of the loaded stack slot.  If
340  /// not, return 0.  This predicate must return 0 if the instruction has
341  /// any side effects other than storing to the stack slot.
342  virtual unsigned isStoreToStackSlot(MachineInstr *MI, int &FrameIndex) const {
343    return 0;
344  }
345
346  /// convertToThreeAddress - This method must be implemented by targets that
347  /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
348  /// may be able to convert a two-address instruction into one or more true
349  /// three-address instructions on demand.  This allows the X86 target (for
350  /// example) to convert ADD and SHL instructions into LEA instructions if they
351  /// would require register copies due to two-addressness.
352  ///
353  /// This method returns a null pointer if the transformation cannot be
354  /// performed, otherwise it returns the last new instruction.
355  ///
356  virtual MachineInstr *
357  convertToThreeAddress(MachineFunction::iterator &MFI,
358                   MachineBasicBlock::iterator &MBBI, LiveVariables &LV) const {
359    return 0;
360  }
361
362  /// commuteInstruction - If a target has any instructions that are commutable,
363  /// but require converting to a different instruction or making non-trivial
364  /// changes to commute them, this method can overloaded to do this.  The
365  /// default implementation of this method simply swaps the first two operands
366  /// of MI and returns it.
367  ///
368  /// If a target wants to make more aggressive changes, they can construct and
369  /// return a new machine instruction.  If an instruction cannot commute, it
370  /// can also return null.
371  ///
372  virtual MachineInstr *commuteInstruction(MachineInstr *MI) const;
373
374  /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
375  /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
376  /// implemented for a target).  Upon success, this returns false and returns
377  /// with the following information in various cases:
378  ///
379  /// 1. If this block ends with no branches (it just falls through to its succ)
380  ///    just return false, leaving TBB/FBB null.
381  /// 2. If this block ends with only an unconditional branch, it sets TBB to be
382  ///    the destination block.
383  /// 3. If this block ends with an conditional branch and it falls through to
384  ///    an successor block, it sets TBB to be the branch destination block and a
385  ///    list of operands that evaluate the condition. These
386  ///    operands can be passed to other TargetInstrInfo methods to create new
387  ///    branches.
388  /// 4. If this block ends with an conditional branch and an unconditional
389  ///    block, it returns the 'true' destination in TBB, the 'false' destination
390  ///    in FBB, and a list of operands that evaluate the condition. These
391  ///    operands can be passed to other TargetInstrInfo methods to create new
392  ///    branches.
393  ///
394  /// Note that RemoveBranch and InsertBranch must be implemented to support
395  /// cases where this method returns success.
396  ///
397  virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
398                             MachineBasicBlock *&FBB,
399                             std::vector<MachineOperand> &Cond) const {
400    return true;
401  }
402
403  /// RemoveBranch - Remove the branching code at the end of the specific MBB.
404  /// this is only invoked in cases where AnalyzeBranch returns success. It
405  /// returns the number of instructions that were removed.
406  virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
407    assert(0 && "Target didn't implement TargetInstrInfo::RemoveBranch!");
408    return 0;
409  }
410
411  /// InsertBranch - Insert a branch into the end of the specified
412  /// MachineBasicBlock.  This operands to this method are the same as those
413  /// returned by AnalyzeBranch.  This is invoked in cases where AnalyzeBranch
414  /// returns success and when an unconditional branch (TBB is non-null, FBB is
415  /// null, Cond is empty) needs to be inserted. It returns the number of
416  /// instructions inserted.
417  virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
418                            MachineBasicBlock *FBB,
419                            const std::vector<MachineOperand> &Cond) const {
420    assert(0 && "Target didn't implement TargetInstrInfo::InsertBranch!");
421    return 0;
422  }
423
424  /// BlockHasNoFallThrough - Return true if the specified block does not
425  /// fall-through into its successor block.  This is primarily used when a
426  /// branch is unanalyzable.  It is useful for things like unconditional
427  /// indirect branches (jump tables).
428  virtual bool BlockHasNoFallThrough(MachineBasicBlock &MBB) const {
429    return false;
430  }
431
432  /// ReverseBranchCondition - Reverses the branch condition of the specified
433  /// condition list, returning false on success and true if it cannot be
434  /// reversed.
435  virtual bool ReverseBranchCondition(std::vector<MachineOperand> &Cond) const {
436    return true;
437  }
438
439  /// insertNoop - Insert a noop into the instruction stream at the specified
440  /// point.
441  virtual void insertNoop(MachineBasicBlock &MBB,
442                          MachineBasicBlock::iterator MI) const {
443    assert(0 && "Target didn't implement insertNoop!");
444    abort();
445  }
446
447  /// isPredicated - Returns true if the instruction is already predicated.
448  ///
449  virtual bool isPredicated(const MachineInstr *MI) const {
450    return false;
451  }
452
453  /// isUnpredicatedTerminator - Returns true if the instruction is a
454  /// terminator instruction that has not been predicated.
455  virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
456
457  /// PredicateInstruction - Convert the instruction into a predicated
458  /// instruction. It returns true if the operation was successful.
459  virtual
460  bool PredicateInstruction(MachineInstr *MI,
461                            const std::vector<MachineOperand> &Pred) const;
462
463  /// SubsumesPredicate - Returns true if the first specified predicate
464  /// subsumes the second, e.g. GE subsumes GT.
465  virtual
466  bool SubsumesPredicate(const std::vector<MachineOperand> &Pred1,
467                         const std::vector<MachineOperand> &Pred2) const {
468    return false;
469  }
470
471  /// DefinesPredicate - If the specified instruction defines any predicate
472  /// or condition code register(s) used for predication, returns true as well
473  /// as the definition predicate(s) by reference.
474  virtual bool DefinesPredicate(MachineInstr *MI,
475                                std::vector<MachineOperand> &Pred) const {
476    return false;
477  }
478
479  /// getPointerRegClass - Returns a TargetRegisterClass used for pointer
480  /// values.
481  virtual const TargetRegisterClass *getPointerRegClass() const {
482    assert(0 && "Target didn't implement getPointerRegClass!");
483    abort();
484    return 0; // Must return a value in order to compile with VS 2005
485  }
486};
487
488} // End llvm namespace
489
490#endif
491