TargetInstrInfo.h revision 3a6b9eb868f579b945aa8ec8fadf65e4dd913555
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 instruction set to the code generator.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TARGET_TARGETINSTRINFO_H
15#define LLVM_TARGET_TARGETINSTRINFO_H
16
17#include "llvm/Target/TargetInstrDesc.h"
18#include "llvm/CodeGen/MachineFunction.h"
19
20namespace llvm {
21
22class MCAsmInfo;
23class TargetRegisterClass;
24class TargetRegisterInfo;
25class LiveVariables;
26class CalleeSavedInfo;
27class SDNode;
28class SelectionDAG;
29
30template<class T> class SmallVectorImpl;
31
32
33//---------------------------------------------------------------------------
34///
35/// TargetInstrInfo - Interface to description of machine instruction set
36///
37class TargetInstrInfo {
38  const TargetInstrDesc *Descriptors; // Raw array to allow static init'n
39  unsigned NumOpcodes;                // Number of entries in the desc array
40
41  TargetInstrInfo(const TargetInstrInfo &);  // DO NOT IMPLEMENT
42  void operator=(const TargetInstrInfo &);   // DO NOT IMPLEMENT
43public:
44  TargetInstrInfo(const TargetInstrDesc *desc, unsigned NumOpcodes);
45  virtual ~TargetInstrInfo();
46
47  // Invariant opcodes: All instruction sets have these as their low opcodes.
48  enum {
49    PHI = 0,
50    INLINEASM = 1,
51    DBG_LABEL = 2,
52    EH_LABEL = 3,
53    GC_LABEL = 4,
54
55    /// KILL - This instruction is a noop that is used only to adjust the liveness
56    /// of registers. This can be useful when dealing with sub-registers.
57    KILL = 5,
58
59    /// EXTRACT_SUBREG - This instruction takes two operands: a register
60    /// that has subregisters, and a subregister index. It returns the
61    /// extracted subregister value. This is commonly used to implement
62    /// truncation operations on target architectures which support it.
63    EXTRACT_SUBREG = 6,
64
65    /// INSERT_SUBREG - This instruction takes three operands: a register
66    /// that has subregisters, a register providing an insert value, and a
67    /// subregister index. It returns the value of the first register with
68    /// the value of the second register inserted. The first register is
69    /// often defined by an IMPLICIT_DEF, as is commonly used to implement
70    /// anyext operations on target architectures which support it.
71    INSERT_SUBREG = 7,
72
73    /// IMPLICIT_DEF - This is the MachineInstr-level equivalent of undef.
74    IMPLICIT_DEF = 8,
75
76    /// SUBREG_TO_REG - This instruction is similar to INSERT_SUBREG except
77    /// that the first operand is an immediate integer constant. This constant
78    /// is often zero, as is commonly used to implement zext operations on
79    /// target architectures which support it, such as with x86-64 (with
80    /// zext from i32 to i64 via implicit zero-extension).
81    SUBREG_TO_REG = 9,
82
83    /// COPY_TO_REGCLASS - This instruction is a placeholder for a plain
84    /// register-to-register copy into a specific register class. This is only
85    /// used between instruction selection and MachineInstr creation, before
86    /// virtual registers have been created for all the instructions, and it's
87    /// only needed in cases where the register classes implied by the
88    /// instructions are insufficient. The actual MachineInstrs to perform
89    /// the copy are emitted with the TargetInstrInfo::copyRegToReg hook.
90    COPY_TO_REGCLASS = 10
91  };
92
93  unsigned getNumOpcodes() const { return NumOpcodes; }
94
95  /// get - Return the machine instruction descriptor that corresponds to the
96  /// specified instruction opcode.
97  ///
98  const TargetInstrDesc &get(unsigned Opcode) const {
99    assert(Opcode < NumOpcodes && "Invalid opcode!");
100    return Descriptors[Opcode];
101  }
102
103  /// isTriviallyReMaterializable - Return true if the instruction is trivially
104  /// rematerializable, meaning it has no side effects and requires no operands
105  /// that aren't always available.
106  bool isTriviallyReMaterializable(const MachineInstr *MI,
107                                   AliasAnalysis *AA = 0) const {
108    return MI->getOpcode() == IMPLICIT_DEF ||
109           (MI->getDesc().isRematerializable() &&
110            (isReallyTriviallyReMaterializable(MI, AA) ||
111             isReallyTriviallyReMaterializableGeneric(MI, AA)));
112  }
113
114protected:
115  /// isReallyTriviallyReMaterializable - For instructions with opcodes for
116  /// which the M_REMATERIALIZABLE flag is set, this hook lets the target
117  /// specify whether the instruction is actually trivially rematerializable,
118  /// taking into consideration its operands. This predicate must return false
119  /// if the instruction has any side effects other than producing a value, or
120  /// if it requres any address registers that are not always available.
121  virtual bool isReallyTriviallyReMaterializable(const MachineInstr *MI,
122                                                 AliasAnalysis *AA) const {
123    return false;
124  }
125
126private:
127  /// isReallyTriviallyReMaterializableGeneric - For instructions with opcodes
128  /// for which the M_REMATERIALIZABLE flag is set and the target hook
129  /// isReallyTriviallyReMaterializable returns false, this function does
130  /// target-independent tests to determine if the instruction is really
131  /// trivially rematerializable.
132  bool isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
133                                                AliasAnalysis *AA) const;
134
135public:
136  /// Return true if the instruction is a register to register move and return
137  /// the source and dest operands and their sub-register indices by reference.
138  virtual bool isMoveInstr(const MachineInstr& MI,
139                           unsigned& SrcReg, unsigned& DstReg,
140                           unsigned& SrcSubIdx, unsigned& DstSubIdx) const {
141    return false;
142  }
143
144  /// isLoadFromStackSlot - If the specified machine instruction is a direct
145  /// load from a stack slot, return the virtual or physical register number of
146  /// the destination along with the FrameIndex of the loaded stack slot.  If
147  /// not, return 0.  This predicate must return 0 if the instruction has
148  /// any side effects other than loading from the stack slot.
149  virtual unsigned isLoadFromStackSlot(const MachineInstr *MI,
150                                       int &FrameIndex) const {
151    return 0;
152  }
153
154  /// isStoreToStackSlot - If the specified machine instruction is a direct
155  /// store to a stack slot, return the virtual or physical register number of
156  /// the source reg along with the FrameIndex of the loaded stack slot.  If
157  /// not, return 0.  This predicate must return 0 if the instruction has
158  /// any side effects other than storing to the stack slot.
159  virtual unsigned isStoreToStackSlot(const MachineInstr *MI,
160                                      int &FrameIndex) const {
161    return 0;
162  }
163
164  /// reMaterialize - Re-issue the specified 'original' instruction at the
165  /// specific location targeting a new destination register.
166  virtual void reMaterialize(MachineBasicBlock &MBB,
167                             MachineBasicBlock::iterator MI,
168                             unsigned DestReg, unsigned SubIdx,
169                             const MachineInstr *Orig) const = 0;
170
171  /// convertToThreeAddress - This method must be implemented by targets that
172  /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
173  /// may be able to convert a two-address instruction into one or more true
174  /// three-address instructions on demand.  This allows the X86 target (for
175  /// example) to convert ADD and SHL instructions into LEA instructions if they
176  /// would require register copies due to two-addressness.
177  ///
178  /// This method returns a null pointer if the transformation cannot be
179  /// performed, otherwise it returns the last new instruction.
180  ///
181  virtual MachineInstr *
182  convertToThreeAddress(MachineFunction::iterator &MFI,
183                   MachineBasicBlock::iterator &MBBI, LiveVariables *LV) const {
184    return 0;
185  }
186
187  /// commuteInstruction - If a target has any instructions that are commutable,
188  /// but require converting to a different instruction or making non-trivial
189  /// changes to commute them, this method can overloaded to do this.  The
190  /// default implementation of this method simply swaps the first two operands
191  /// of MI and returns it.
192  ///
193  /// If a target wants to make more aggressive changes, they can construct and
194  /// return a new machine instruction.  If an instruction cannot commute, it
195  /// can also return null.
196  ///
197  /// If NewMI is true, then a new machine instruction must be created.
198  ///
199  virtual MachineInstr *commuteInstruction(MachineInstr *MI,
200                                           bool NewMI = false) const = 0;
201
202  /// findCommutedOpIndices - If specified MI is commutable, return the two
203  /// operand indices that would swap value. Return true if the instruction
204  /// is not in a form which this routine understands.
205  virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
206                                     unsigned &SrcOpIdx2) const = 0;
207
208  /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
209  /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
210  /// implemented for a target).  Upon success, this returns false and returns
211  /// with the following information in various cases:
212  ///
213  /// 1. If this block ends with no branches (it just falls through to its succ)
214  ///    just return false, leaving TBB/FBB null.
215  /// 2. If this block ends with only an unconditional branch, it sets TBB to be
216  ///    the destination block.
217  /// 3. If this block ends with an conditional branch and it falls through to
218  ///    a successor block, it sets TBB to be the branch destination block and
219  ///    a list of operands that evaluate the condition. These
220  ///    operands can be passed to other TargetInstrInfo methods to create new
221  ///    branches.
222  /// 4. If this block ends with a conditional branch followed by an
223  ///    unconditional branch, it returns the 'true' destination in TBB, the
224  ///    'false' destination in FBB, and a list of operands that evaluate the
225  ///    condition.  These operands can be passed to other TargetInstrInfo
226  ///    methods to create new branches.
227  ///
228  /// Note that RemoveBranch and InsertBranch must be implemented to support
229  /// cases where this method returns success.
230  ///
231  /// If AllowModify is true, then this routine is allowed to modify the basic
232  /// block (e.g. delete instructions after the unconditional branch).
233  ///
234  virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
235                             MachineBasicBlock *&FBB,
236                             SmallVectorImpl<MachineOperand> &Cond,
237                             bool AllowModify = false) const {
238    return true;
239  }
240
241  /// RemoveBranch - Remove the branching code at the end of the specific MBB.
242  /// This is only invoked in cases where AnalyzeBranch returns success. It
243  /// returns the number of instructions that were removed.
244  virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
245    assert(0 && "Target didn't implement TargetInstrInfo::RemoveBranch!");
246    return 0;
247  }
248
249  /// InsertBranch - Insert branch code into the end of the specified
250  /// MachineBasicBlock.  The operands to this method are the same as those
251  /// returned by AnalyzeBranch.  This is only invoked in cases where
252  /// AnalyzeBranch returns success. It returns the number of instructions
253  /// inserted.
254  ///
255  /// It is also invoked by tail merging to add unconditional branches in
256  /// cases where AnalyzeBranch doesn't apply because there was no original
257  /// branch to analyze.  At least this much must be implemented, else tail
258  /// merging needs to be disabled.
259  virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
260                            MachineBasicBlock *FBB,
261                            const SmallVectorImpl<MachineOperand> &Cond) const {
262    assert(0 && "Target didn't implement TargetInstrInfo::InsertBranch!");
263    return 0;
264  }
265
266  /// copyRegToReg - Emit instructions to copy between a pair of registers. It
267  /// returns false if the target does not how to copy between the specified
268  /// registers.
269  virtual bool copyRegToReg(MachineBasicBlock &MBB,
270                            MachineBasicBlock::iterator MI,
271                            unsigned DestReg, unsigned SrcReg,
272                            const TargetRegisterClass *DestRC,
273                            const TargetRegisterClass *SrcRC) const {
274    assert(0 && "Target didn't implement TargetInstrInfo::copyRegToReg!");
275    return false;
276  }
277
278  /// storeRegToStackSlot - Store the specified register of the given register
279  /// class to the specified stack frame index. The store instruction is to be
280  /// added to the given machine basic block before the specified machine
281  /// instruction. If isKill is true, the register operand is the last use and
282  /// must be marked kill.
283  virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
284                                   MachineBasicBlock::iterator MI,
285                                   unsigned SrcReg, bool isKill, int FrameIndex,
286                                   const TargetRegisterClass *RC) const {
287    assert(0 && "Target didn't implement TargetInstrInfo::storeRegToStackSlot!");
288  }
289
290  /// loadRegFromStackSlot - Load the specified register of the given register
291  /// class from the specified stack frame index. The load instruction is to be
292  /// added to the given machine basic block before the specified machine
293  /// instruction.
294  virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
295                                    MachineBasicBlock::iterator MI,
296                                    unsigned DestReg, int FrameIndex,
297                                    const TargetRegisterClass *RC) const {
298    assert(0 && "Target didn't implement TargetInstrInfo::loadRegFromStackSlot!");
299  }
300
301  /// spillCalleeSavedRegisters - Issues instruction(s) to spill all callee
302  /// saved registers and returns true if it isn't possible / profitable to do
303  /// so by issuing a series of store instructions via
304  /// storeRegToStackSlot(). Returns false otherwise.
305  virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
306                                         MachineBasicBlock::iterator MI,
307                                const std::vector<CalleeSavedInfo> &CSI) const {
308    return false;
309  }
310
311  /// restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee
312  /// saved registers and returns true if it isn't possible / profitable to do
313  /// so by issuing a series of load instructions via loadRegToStackSlot().
314  /// Returns false otherwise.
315  virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
316                                           MachineBasicBlock::iterator MI,
317                                const std::vector<CalleeSavedInfo> &CSI) const {
318    return false;
319  }
320
321  /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
322  /// slot into the specified machine instruction for the specified operand(s).
323  /// If this is possible, a new instruction is returned with the specified
324  /// operand folded, otherwise NULL is returned. The client is responsible for
325  /// removing the old instruction and adding the new one in the instruction
326  /// stream.
327  MachineInstr* foldMemoryOperand(MachineFunction &MF,
328                                  MachineInstr* MI,
329                                  const SmallVectorImpl<unsigned> &Ops,
330                                  int FrameIndex) const;
331
332  /// foldMemoryOperand - Same as the previous version except it allows folding
333  /// of any load and store from / to any address, not just from a specific
334  /// stack slot.
335  MachineInstr* foldMemoryOperand(MachineFunction &MF,
336                                  MachineInstr* MI,
337                                  const SmallVectorImpl<unsigned> &Ops,
338                                  MachineInstr* LoadMI) const;
339
340protected:
341  /// foldMemoryOperandImpl - Target-dependent implementation for
342  /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
343  /// take care of adding a MachineMemOperand to the newly created instruction.
344  virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
345                                          MachineInstr* MI,
346                                          const SmallVectorImpl<unsigned> &Ops,
347                                          int FrameIndex) const {
348    return 0;
349  }
350
351  /// foldMemoryOperandImpl - Target-dependent implementation for
352  /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
353  /// take care of adding a MachineMemOperand to the newly created instruction.
354  virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
355                                              MachineInstr* MI,
356                                              const SmallVectorImpl<unsigned> &Ops,
357                                              MachineInstr* LoadMI) const {
358    return 0;
359  }
360
361public:
362  /// canFoldMemoryOperand - Returns true for the specified load / store if
363  /// folding is possible.
364  virtual
365  bool canFoldMemoryOperand(const MachineInstr *MI,
366                            const SmallVectorImpl<unsigned> &Ops) const {
367    return false;
368  }
369
370  /// unfoldMemoryOperand - Separate a single instruction which folded a load or
371  /// a store or a load and a store into two or more instruction. If this is
372  /// possible, returns true as well as the new instructions by reference.
373  virtual bool unfoldMemoryOperand(MachineFunction &MF, MachineInstr *MI,
374                                unsigned Reg, bool UnfoldLoad, bool UnfoldStore,
375                                 SmallVectorImpl<MachineInstr*> &NewMIs) const{
376    return false;
377  }
378
379  virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
380                                   SmallVectorImpl<SDNode*> &NewNodes) const {
381    return false;
382  }
383
384  /// getOpcodeAfterMemoryUnfold - Returns the opcode of the would be new
385  /// instruction after load / store are unfolded from an instruction of the
386  /// specified opcode. It returns zero if the specified unfolding is not
387  /// possible.
388  virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc,
389                                      bool UnfoldLoad, bool UnfoldStore) const {
390    return 0;
391  }
392
393  /// BlockHasNoFallThrough - Return true if the specified block does not
394  /// fall-through into its successor block.  This is primarily used when a
395  /// branch is unanalyzable.  It is useful for things like unconditional
396  /// indirect branches (jump tables).
397  virtual bool BlockHasNoFallThrough(const MachineBasicBlock &MBB) const {
398    return false;
399  }
400
401  /// ReverseBranchCondition - Reverses the branch condition of the specified
402  /// condition list, returning false on success and true if it cannot be
403  /// reversed.
404  virtual
405  bool ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
406    return true;
407  }
408
409  /// insertNoop - Insert a noop into the instruction stream at the specified
410  /// point.
411  virtual void insertNoop(MachineBasicBlock &MBB,
412                          MachineBasicBlock::iterator MI) const;
413
414  /// isPredicated - Returns true if the instruction is already predicated.
415  ///
416  virtual bool isPredicated(const MachineInstr *MI) const {
417    return false;
418  }
419
420  /// isUnpredicatedTerminator - Returns true if the instruction is a
421  /// terminator instruction that has not been predicated.
422  virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
423
424  /// PredicateInstruction - Convert the instruction into a predicated
425  /// instruction. It returns true if the operation was successful.
426  virtual
427  bool PredicateInstruction(MachineInstr *MI,
428                        const SmallVectorImpl<MachineOperand> &Pred) const = 0;
429
430  /// SubsumesPredicate - Returns true if the first specified predicate
431  /// subsumes the second, e.g. GE subsumes GT.
432  virtual
433  bool SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
434                         const SmallVectorImpl<MachineOperand> &Pred2) const {
435    return false;
436  }
437
438  /// DefinesPredicate - If the specified instruction defines any predicate
439  /// or condition code register(s) used for predication, returns true as well
440  /// as the definition predicate(s) by reference.
441  virtual bool DefinesPredicate(MachineInstr *MI,
442                                std::vector<MachineOperand> &Pred) const {
443    return false;
444  }
445
446  /// isSafeToMoveRegClassDefs - Return true if it's safe to move a machine
447  /// instruction that defines the specified register class.
448  virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
449    return true;
450  }
451
452  /// GetInstSize - Returns the size of the specified Instruction.
453  ///
454  virtual unsigned GetInstSizeInBytes(const MachineInstr *MI) const {
455    assert(0 && "Target didn't implement TargetInstrInfo::GetInstSize!");
456    return 0;
457  }
458
459  /// GetFunctionSizeInBytes - Returns the size of the specified
460  /// MachineFunction.
461  ///
462  virtual unsigned GetFunctionSizeInBytes(const MachineFunction &MF) const = 0;
463
464  /// Measure the specified inline asm to determine an approximation of its
465  /// length.
466  virtual unsigned getInlineAsmLength(const char *Str,
467                                      const MCAsmInfo &MAI) const;
468};
469
470/// TargetInstrInfoImpl - This is the default implementation of
471/// TargetInstrInfo, which just provides a couple of default implementations
472/// for various methods.  This separated out because it is implemented in
473/// libcodegen, not in libtarget.
474class TargetInstrInfoImpl : public TargetInstrInfo {
475protected:
476  TargetInstrInfoImpl(const TargetInstrDesc *desc, unsigned NumOpcodes)
477  : TargetInstrInfo(desc, NumOpcodes) {}
478public:
479  virtual MachineInstr *commuteInstruction(MachineInstr *MI,
480                                           bool NewMI = false) const;
481  virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
482                                     unsigned &SrcOpIdx2) const;
483  virtual bool PredicateInstruction(MachineInstr *MI,
484                            const SmallVectorImpl<MachineOperand> &Pred) const;
485  virtual void reMaterialize(MachineBasicBlock &MBB,
486                             MachineBasicBlock::iterator MI,
487                             unsigned DestReg, unsigned SubReg,
488                             const MachineInstr *Orig) const;
489  virtual unsigned GetFunctionSizeInBytes(const MachineFunction &MF) const;
490};
491
492} // End llvm namespace
493
494#endif
495