• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/MC/MCInstrInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 
20 namespace llvm {
21 
22 class InstrItineraryData;
23 class LiveVariables;
24 class MCAsmInfo;
25 class MachineMemOperand;
26 class MachineRegisterInfo;
27 class MDNode;
28 class MCInst;
29 class SDNode;
30 class ScheduleHazardRecognizer;
31 class SelectionDAG;
32 class ScheduleDAG;
33 class TargetRegisterClass;
34 class TargetRegisterInfo;
35 class BranchProbability;
36 
37 template<class T> class SmallVectorImpl;
38 
39 
40 //---------------------------------------------------------------------------
41 ///
42 /// TargetInstrInfo - Interface to description of machine instruction set
43 ///
44 class TargetInstrInfo : public MCInstrInfo {
45   TargetInstrInfo(const TargetInstrInfo &);  // DO NOT IMPLEMENT
46   void operator=(const TargetInstrInfo &);   // DO NOT IMPLEMENT
47 public:
48   TargetInstrInfo(int CFSetupOpcode = -1, int CFDestroyOpcode = -1)
CallFrameSetupOpcode(CFSetupOpcode)49     : CallFrameSetupOpcode(CFSetupOpcode),
50       CallFrameDestroyOpcode(CFDestroyOpcode) {
51   }
52 
53   virtual ~TargetInstrInfo();
54 
55   /// getRegClass - Givem a machine instruction descriptor, returns the register
56   /// class constraint for OpNum, or NULL.
57   const TargetRegisterClass *getRegClass(const MCInstrDesc &TID,
58                                          unsigned OpNum,
59                                          const TargetRegisterInfo *TRI) const;
60 
61   /// isTriviallyReMaterializable - Return true if the instruction is trivially
62   /// rematerializable, meaning it has no side effects and requires no operands
63   /// that aren't always available.
64   bool isTriviallyReMaterializable(const MachineInstr *MI,
65                                    AliasAnalysis *AA = 0) const {
66     return MI->getOpcode() == TargetOpcode::IMPLICIT_DEF ||
67            (MI->getDesc().isRematerializable() &&
68             (isReallyTriviallyReMaterializable(MI, AA) ||
69              isReallyTriviallyReMaterializableGeneric(MI, AA)));
70   }
71 
72 protected:
73   /// isReallyTriviallyReMaterializable - For instructions with opcodes for
74   /// which the M_REMATERIALIZABLE flag is set, this hook lets the target
75   /// specify whether the instruction is actually trivially rematerializable,
76   /// taking into consideration its operands. This predicate must return false
77   /// if the instruction has any side effects other than producing a value, or
78   /// if it requres any address registers that are not always available.
isReallyTriviallyReMaterializable(const MachineInstr * MI,AliasAnalysis * AA)79   virtual bool isReallyTriviallyReMaterializable(const MachineInstr *MI,
80                                                  AliasAnalysis *AA) const {
81     return false;
82   }
83 
84 private:
85   /// isReallyTriviallyReMaterializableGeneric - For instructions with opcodes
86   /// for which the M_REMATERIALIZABLE flag is set and the target hook
87   /// isReallyTriviallyReMaterializable returns false, this function does
88   /// target-independent tests to determine if the instruction is really
89   /// trivially rematerializable.
90   bool isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
91                                                 AliasAnalysis *AA) const;
92 
93 public:
94   /// getCallFrameSetup/DestroyOpcode - These methods return the opcode of the
95   /// frame setup/destroy instructions if they exist (-1 otherwise).  Some
96   /// targets use pseudo instructions in order to abstract away the difference
97   /// between operating with a frame pointer and operating without, through the
98   /// use of these two instructions.
99   ///
getCallFrameSetupOpcode()100   int getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
getCallFrameDestroyOpcode()101   int getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
102 
103   /// isCoalescableExtInstr - Return true if the instruction is a "coalescable"
104   /// extension instruction. That is, it's like a copy where it's legal for the
105   /// source to overlap the destination. e.g. X86::MOVSX64rr32. If this returns
106   /// true, then it's expected the pre-extension value is available as a subreg
107   /// of the result register. This also returns the sub-register index in
108   /// SubIdx.
isCoalescableExtInstr(const MachineInstr & MI,unsigned & SrcReg,unsigned & DstReg,unsigned & SubIdx)109   virtual bool isCoalescableExtInstr(const MachineInstr &MI,
110                                      unsigned &SrcReg, unsigned &DstReg,
111                                      unsigned &SubIdx) const {
112     return false;
113   }
114 
115   /// isLoadFromStackSlot - If the specified machine instruction is a direct
116   /// load from a stack slot, return the virtual or physical register number of
117   /// the destination along with the FrameIndex of the loaded stack slot.  If
118   /// not, return 0.  This predicate must return 0 if the instruction has
119   /// any side effects other than loading from the stack slot.
isLoadFromStackSlot(const MachineInstr * MI,int & FrameIndex)120   virtual unsigned isLoadFromStackSlot(const MachineInstr *MI,
121                                        int &FrameIndex) const {
122     return 0;
123   }
124 
125   /// isLoadFromStackSlotPostFE - Check for post-frame ptr elimination
126   /// stack locations as well.  This uses a heuristic so it isn't
127   /// reliable for correctness.
isLoadFromStackSlotPostFE(const MachineInstr * MI,int & FrameIndex)128   virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr *MI,
129                                              int &FrameIndex) const {
130     return 0;
131   }
132 
133   /// hasLoadFromStackSlot - If the specified machine instruction has
134   /// a load from a stack slot, return true along with the FrameIndex
135   /// of the loaded stack slot and the machine mem operand containing
136   /// the reference.  If not, return false.  Unlike
137   /// isLoadFromStackSlot, this returns true for any instructions that
138   /// loads from the stack.  This is just a hint, as some cases may be
139   /// missed.
hasLoadFromStackSlot(const MachineInstr * MI,const MachineMemOperand * & MMO,int & FrameIndex)140   virtual bool hasLoadFromStackSlot(const MachineInstr *MI,
141                                     const MachineMemOperand *&MMO,
142                                     int &FrameIndex) const {
143     return 0;
144   }
145 
146   /// isStoreToStackSlot - If the specified machine instruction is a direct
147   /// store to a stack slot, return the virtual or physical register number of
148   /// the source reg along with the FrameIndex of the loaded stack slot.  If
149   /// not, return 0.  This predicate must return 0 if the instruction has
150   /// any side effects other than storing to the stack slot.
isStoreToStackSlot(const MachineInstr * MI,int & FrameIndex)151   virtual unsigned isStoreToStackSlot(const MachineInstr *MI,
152                                       int &FrameIndex) const {
153     return 0;
154   }
155 
156   /// isStoreToStackSlotPostFE - Check for post-frame ptr elimination
157   /// stack locations as well.  This uses a heuristic so it isn't
158   /// reliable for correctness.
isStoreToStackSlotPostFE(const MachineInstr * MI,int & FrameIndex)159   virtual unsigned isStoreToStackSlotPostFE(const MachineInstr *MI,
160                                             int &FrameIndex) const {
161     return 0;
162   }
163 
164   /// hasStoreToStackSlot - If the specified machine instruction has a
165   /// store to a stack slot, return true along with the FrameIndex of
166   /// the loaded stack slot and the machine mem operand containing the
167   /// reference.  If not, return false.  Unlike isStoreToStackSlot,
168   /// this returns true for any instructions that stores to the
169   /// stack.  This is just a hint, as some cases may be missed.
hasStoreToStackSlot(const MachineInstr * MI,const MachineMemOperand * & MMO,int & FrameIndex)170   virtual bool hasStoreToStackSlot(const MachineInstr *MI,
171                                    const MachineMemOperand *&MMO,
172                                    int &FrameIndex) const {
173     return 0;
174   }
175 
176   /// reMaterialize - Re-issue the specified 'original' instruction at the
177   /// specific location targeting a new destination register.
178   /// The register in Orig->getOperand(0).getReg() will be substituted by
179   /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
180   /// SubIdx.
181   virtual void reMaterialize(MachineBasicBlock &MBB,
182                              MachineBasicBlock::iterator MI,
183                              unsigned DestReg, unsigned SubIdx,
184                              const MachineInstr *Orig,
185                              const TargetRegisterInfo &TRI) const = 0;
186 
187   /// scheduleTwoAddrSource - Schedule the copy / re-mat of the source of the
188   /// two-addrss instruction inserted by two-address pass.
scheduleTwoAddrSource(MachineInstr * SrcMI,MachineInstr * UseMI,const TargetRegisterInfo & TRI)189   virtual void scheduleTwoAddrSource(MachineInstr *SrcMI,
190                                      MachineInstr *UseMI,
191                                      const TargetRegisterInfo &TRI) const {
192     // Do nothing.
193   }
194 
195   /// duplicate - Create a duplicate of the Orig instruction in MF. This is like
196   /// MachineFunction::CloneMachineInstr(), but the target may update operands
197   /// that are required to be unique.
198   ///
199   /// The instruction must be duplicable as indicated by isNotDuplicable().
200   virtual MachineInstr *duplicate(MachineInstr *Orig,
201                                   MachineFunction &MF) const = 0;
202 
203   /// convertToThreeAddress - This method must be implemented by targets that
204   /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
205   /// may be able to convert a two-address instruction into one or more true
206   /// three-address instructions on demand.  This allows the X86 target (for
207   /// example) to convert ADD and SHL instructions into LEA instructions if they
208   /// would require register copies due to two-addressness.
209   ///
210   /// This method returns a null pointer if the transformation cannot be
211   /// performed, otherwise it returns the last new instruction.
212   ///
213   virtual MachineInstr *
convertToThreeAddress(MachineFunction::iterator & MFI,MachineBasicBlock::iterator & MBBI,LiveVariables * LV)214   convertToThreeAddress(MachineFunction::iterator &MFI,
215                    MachineBasicBlock::iterator &MBBI, LiveVariables *LV) const {
216     return 0;
217   }
218 
219   /// commuteInstruction - If a target has any instructions that are
220   /// commutable but require converting to different instructions or making
221   /// non-trivial changes to commute them, this method can overloaded to do
222   /// that.  The default implementation simply swaps the commutable operands.
223   /// If NewMI is false, MI is modified in place and returned; otherwise, a
224   /// new machine instruction is created and returned.  Do not call this
225   /// method for a non-commutable instruction, but there may be some cases
226   /// where this method fails and returns null.
227   virtual MachineInstr *commuteInstruction(MachineInstr *MI,
228                                            bool NewMI = false) const = 0;
229 
230   /// findCommutedOpIndices - If specified MI is commutable, return the two
231   /// operand indices that would swap value. Return false if the instruction
232   /// is not in a form which this routine understands.
233   virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
234                                      unsigned &SrcOpIdx2) const = 0;
235 
236   /// produceSameValue - Return true if two machine instructions would produce
237   /// identical values. By default, this is only true when the two instructions
238   /// are deemed identical except for defs. If this function is called when the
239   /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
240   /// aggressive checks.
241   virtual bool produceSameValue(const MachineInstr *MI0,
242                                 const MachineInstr *MI1,
243                                 const MachineRegisterInfo *MRI = 0) const = 0;
244 
245   /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
246   /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
247   /// implemented for a target).  Upon success, this returns false and returns
248   /// with the following information in various cases:
249   ///
250   /// 1. If this block ends with no branches (it just falls through to its succ)
251   ///    just return false, leaving TBB/FBB null.
252   /// 2. If this block ends with only an unconditional branch, it sets TBB to be
253   ///    the destination block.
254   /// 3. If this block ends with a conditional branch and it falls through to a
255   ///    successor block, it sets TBB to be the branch destination block and a
256   ///    list of operands that evaluate the condition. These operands can be
257   ///    passed to other TargetInstrInfo methods to create new branches.
258   /// 4. If this block ends with a conditional branch followed by an
259   ///    unconditional branch, it returns the 'true' destination in TBB, the
260   ///    'false' destination in FBB, and a list of operands that evaluate the
261   ///    condition.  These operands can be passed to other TargetInstrInfo
262   ///    methods to create new branches.
263   ///
264   /// Note that RemoveBranch and InsertBranch must be implemented to support
265   /// cases where this method returns success.
266   ///
267   /// If AllowModify is true, then this routine is allowed to modify the basic
268   /// block (e.g. delete instructions after the unconditional branch).
269   ///
270   virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
271                              MachineBasicBlock *&FBB,
272                              SmallVectorImpl<MachineOperand> &Cond,
273                              bool AllowModify = false) const {
274     return true;
275   }
276 
277   /// RemoveBranch - Remove the branching code at the end of the specific MBB.
278   /// This is only invoked in cases where AnalyzeBranch returns success. It
279   /// returns the number of instructions that were removed.
RemoveBranch(MachineBasicBlock & MBB)280   virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
281     assert(0 && "Target didn't implement TargetInstrInfo::RemoveBranch!");
282     return 0;
283   }
284 
285   /// InsertBranch - Insert branch code into the end of the specified
286   /// MachineBasicBlock.  The operands to this method are the same as those
287   /// returned by AnalyzeBranch.  This is only invoked in cases where
288   /// AnalyzeBranch returns success. It returns the number of instructions
289   /// inserted.
290   ///
291   /// It is also invoked by tail merging to add unconditional branches in
292   /// cases where AnalyzeBranch doesn't apply because there was no original
293   /// branch to analyze.  At least this much must be implemented, else tail
294   /// merging needs to be disabled.
InsertBranch(MachineBasicBlock & MBB,MachineBasicBlock * TBB,MachineBasicBlock * FBB,const SmallVectorImpl<MachineOperand> & Cond,DebugLoc DL)295   virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
296                                 MachineBasicBlock *FBB,
297                                 const SmallVectorImpl<MachineOperand> &Cond,
298                                 DebugLoc DL) const {
299     assert(0 && "Target didn't implement TargetInstrInfo::InsertBranch!");
300     return 0;
301   }
302 
303   /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
304   /// after it, replacing it with an unconditional branch to NewDest. This is
305   /// used by the tail merging pass.
306   virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
307                                        MachineBasicBlock *NewDest) const = 0;
308 
309   /// isLegalToSplitMBBAt - Return true if it's legal to split the given basic
310   /// block at the specified instruction (i.e. instruction would be the start
311   /// of a new basic block).
isLegalToSplitMBBAt(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI)312   virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
313                                    MachineBasicBlock::iterator MBBI) const {
314     return true;
315   }
316 
317   /// isProfitableToIfCvt - Return true if it's profitable to predicate
318   /// instructions with accumulated instruction latency of "NumCycles"
319   /// of the specified basic block, where the probability of the instructions
320   /// being executed is given by Probability, and Confidence is a measure
321   /// of our confidence that it will be properly predicted.
322   virtual
isProfitableToIfCvt(MachineBasicBlock & MBB,unsigned NumCyles,unsigned ExtraPredCycles,const BranchProbability & Probability)323   bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCyles,
324                            unsigned ExtraPredCycles,
325                            const BranchProbability &Probability) const {
326     return false;
327   }
328 
329   /// isProfitableToIfCvt - Second variant of isProfitableToIfCvt, this one
330   /// checks for the case where two basic blocks from true and false path
331   /// of a if-then-else (diamond) are predicated on mutally exclusive
332   /// predicates, where the probability of the true path being taken is given
333   /// by Probability, and Confidence is a measure of our confidence that it
334   /// will be properly predicted.
335   virtual bool
isProfitableToIfCvt(MachineBasicBlock & TMBB,unsigned NumTCycles,unsigned ExtraTCycles,MachineBasicBlock & FMBB,unsigned NumFCycles,unsigned ExtraFCycles,const BranchProbability & Probability)336   isProfitableToIfCvt(MachineBasicBlock &TMBB,
337                       unsigned NumTCycles, unsigned ExtraTCycles,
338                       MachineBasicBlock &FMBB,
339                       unsigned NumFCycles, unsigned ExtraFCycles,
340                       const BranchProbability &Probability) const {
341     return false;
342   }
343 
344   /// isProfitableToDupForIfCvt - Return true if it's profitable for
345   /// if-converter to duplicate instructions of specified accumulated
346   /// instruction latencies in the specified MBB to enable if-conversion.
347   /// The probability of the instructions being executed is given by
348   /// Probability, and Confidence is a measure of our confidence that it
349   /// will be properly predicted.
350   virtual bool
isProfitableToDupForIfCvt(MachineBasicBlock & MBB,unsigned NumCyles,const BranchProbability & Probability)351   isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCyles,
352                             const BranchProbability &Probability) const {
353     return false;
354   }
355 
356   /// copyPhysReg - Emit instructions to copy a pair of physical registers.
copyPhysReg(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,DebugLoc DL,unsigned DestReg,unsigned SrcReg,bool KillSrc)357   virtual void copyPhysReg(MachineBasicBlock &MBB,
358                            MachineBasicBlock::iterator MI, DebugLoc DL,
359                            unsigned DestReg, unsigned SrcReg,
360                            bool KillSrc) const {
361     assert(0 && "Target didn't implement TargetInstrInfo::copyPhysReg!");
362   }
363 
364   /// storeRegToStackSlot - Store the specified register of the given register
365   /// class to the specified stack frame index. The store instruction is to be
366   /// added to the given machine basic block before the specified machine
367   /// instruction. If isKill is true, the register operand is the last use and
368   /// must be marked kill.
storeRegToStackSlot(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned SrcReg,bool isKill,int FrameIndex,const TargetRegisterClass * RC,const TargetRegisterInfo * TRI)369   virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
370                                    MachineBasicBlock::iterator MI,
371                                    unsigned SrcReg, bool isKill, int FrameIndex,
372                                    const TargetRegisterClass *RC,
373                                    const TargetRegisterInfo *TRI) const {
374   assert(0 && "Target didn't implement TargetInstrInfo::storeRegToStackSlot!");
375   }
376 
377   /// loadRegFromStackSlot - Load the specified register of the given register
378   /// class from the specified stack frame index. The load instruction is to be
379   /// added to the given machine basic block before the specified machine
380   /// instruction.
loadRegFromStackSlot(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned DestReg,int FrameIndex,const TargetRegisterClass * RC,const TargetRegisterInfo * TRI)381   virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
382                                     MachineBasicBlock::iterator MI,
383                                     unsigned DestReg, int FrameIndex,
384                                     const TargetRegisterClass *RC,
385                                     const TargetRegisterInfo *TRI) const {
386   assert(0 && "Target didn't implement TargetInstrInfo::loadRegFromStackSlot!");
387   }
388 
389   /// expandPostRAPseudo - This function is called for all pseudo instructions
390   /// that remain after register allocation. Many pseudo instructions are
391   /// created to help register allocation. This is the place to convert them
392   /// into real instructions. The target can edit MI in place, or it can insert
393   /// new instructions and erase MI. The function should return true if
394   /// anything was changed.
expandPostRAPseudo(MachineBasicBlock::iterator MI)395   virtual bool expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
396     return false;
397   }
398 
399   /// emitFrameIndexDebugValue - Emit a target-dependent form of
400   /// DBG_VALUE encoding the address of a frame index.  Addresses would
401   /// normally be lowered the same way as other addresses on the target,
402   /// e.g. in load instructions.  For targets that do not support this
403   /// the debug info is simply lost.
404   /// If you add this for a target you should handle this DBG_VALUE in the
405   /// target-specific AsmPrinter code as well; you will probably get invalid
406   /// assembly output if you don't.
emitFrameIndexDebugValue(MachineFunction & MF,int FrameIx,uint64_t Offset,const MDNode * MDPtr,DebugLoc dl)407   virtual MachineInstr *emitFrameIndexDebugValue(MachineFunction &MF,
408                                                  int FrameIx,
409                                                  uint64_t Offset,
410                                                  const MDNode *MDPtr,
411                                                  DebugLoc dl) const {
412     return 0;
413   }
414 
415   /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
416   /// slot into the specified machine instruction for the specified operand(s).
417   /// If this is possible, a new instruction is returned with the specified
418   /// operand folded, otherwise NULL is returned.
419   /// The new instruction is inserted before MI, and the client is responsible
420   /// for removing the old instruction.
421   MachineInstr* foldMemoryOperand(MachineBasicBlock::iterator MI,
422                                   const SmallVectorImpl<unsigned> &Ops,
423                                   int FrameIndex) const;
424 
425   /// foldMemoryOperand - Same as the previous version except it allows folding
426   /// of any load and store from / to any address, not just from a specific
427   /// stack slot.
428   MachineInstr* foldMemoryOperand(MachineBasicBlock::iterator MI,
429                                   const SmallVectorImpl<unsigned> &Ops,
430                                   MachineInstr* LoadMI) const;
431 
432 protected:
433   /// foldMemoryOperandImpl - Target-dependent implementation for
434   /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
435   /// take care of adding a MachineMemOperand to the newly created instruction.
foldMemoryOperandImpl(MachineFunction & MF,MachineInstr * MI,const SmallVectorImpl<unsigned> & Ops,int FrameIndex)436   virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
437                                           MachineInstr* MI,
438                                           const SmallVectorImpl<unsigned> &Ops,
439                                           int FrameIndex) const {
440     return 0;
441   }
442 
443   /// foldMemoryOperandImpl - Target-dependent implementation for
444   /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
445   /// take care of adding a MachineMemOperand to the newly created instruction.
foldMemoryOperandImpl(MachineFunction & MF,MachineInstr * MI,const SmallVectorImpl<unsigned> & Ops,MachineInstr * LoadMI)446   virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
447                                               MachineInstr* MI,
448                                           const SmallVectorImpl<unsigned> &Ops,
449                                               MachineInstr* LoadMI) const {
450     return 0;
451   }
452 
453 public:
454   /// canFoldMemoryOperand - Returns true for the specified load / store if
455   /// folding is possible.
456   virtual
457   bool canFoldMemoryOperand(const MachineInstr *MI,
458                             const SmallVectorImpl<unsigned> &Ops) const =0;
459 
460   /// unfoldMemoryOperand - Separate a single instruction which folded a load or
461   /// a store or a load and a store into two or more instruction. If this is
462   /// possible, returns true as well as the new instructions by reference.
unfoldMemoryOperand(MachineFunction & MF,MachineInstr * MI,unsigned Reg,bool UnfoldLoad,bool UnfoldStore,SmallVectorImpl<MachineInstr * > & NewMIs)463   virtual bool unfoldMemoryOperand(MachineFunction &MF, MachineInstr *MI,
464                                 unsigned Reg, bool UnfoldLoad, bool UnfoldStore,
465                                  SmallVectorImpl<MachineInstr*> &NewMIs) const{
466     return false;
467   }
468 
unfoldMemoryOperand(SelectionDAG & DAG,SDNode * N,SmallVectorImpl<SDNode * > & NewNodes)469   virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
470                                    SmallVectorImpl<SDNode*> &NewNodes) const {
471     return false;
472   }
473 
474   /// getOpcodeAfterMemoryUnfold - Returns the opcode of the would be new
475   /// instruction after load / store are unfolded from an instruction of the
476   /// specified opcode. It returns zero if the specified unfolding is not
477   /// possible. If LoadRegIndex is non-null, it is filled in with the operand
478   /// index of the operand which will hold the register holding the loaded
479   /// value.
480   virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc,
481                                       bool UnfoldLoad, bool UnfoldStore,
482                                       unsigned *LoadRegIndex = 0) const {
483     return 0;
484   }
485 
486   /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler
487   /// to determine if two loads are loading from the same base address. It
488   /// should only return true if the base pointers are the same and the
489   /// only differences between the two addresses are the offset. It also returns
490   /// the offsets by reference.
areLoadsFromSameBasePtr(SDNode * Load1,SDNode * Load2,int64_t & Offset1,int64_t & Offset2)491   virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
492                                     int64_t &Offset1, int64_t &Offset2) const {
493     return false;
494   }
495 
496   /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
497   /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
498   /// be scheduled togther. On some targets if two loads are loading from
499   /// addresses in the same cache line, it's better if they are scheduled
500   /// together. This function takes two integers that represent the load offsets
501   /// from the common base address. It returns true if it decides it's desirable
502   /// to schedule the two loads together. "NumLoads" is the number of loads that
503   /// have already been scheduled after Load1.
shouldScheduleLoadsNear(SDNode * Load1,SDNode * Load2,int64_t Offset1,int64_t Offset2,unsigned NumLoads)504   virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
505                                        int64_t Offset1, int64_t Offset2,
506                                        unsigned NumLoads) const {
507     return false;
508   }
509 
510   /// ReverseBranchCondition - Reverses the branch condition of the specified
511   /// condition list, returning false on success and true if it cannot be
512   /// reversed.
513   virtual
ReverseBranchCondition(SmallVectorImpl<MachineOperand> & Cond)514   bool ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
515     return true;
516   }
517 
518   /// insertNoop - Insert a noop into the instruction stream at the specified
519   /// point.
520   virtual void insertNoop(MachineBasicBlock &MBB,
521                           MachineBasicBlock::iterator MI) const;
522 
523 
524   /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
getNoopForMachoTarget(MCInst & NopInst)525   virtual void getNoopForMachoTarget(MCInst &NopInst) const {
526     // Default to just using 'nop' string.
527   }
528 
529 
530   /// isPredicated - Returns true if the instruction is already predicated.
531   ///
isPredicated(const MachineInstr * MI)532   virtual bool isPredicated(const MachineInstr *MI) const {
533     return false;
534   }
535 
536   /// isUnpredicatedTerminator - Returns true if the instruction is a
537   /// terminator instruction that has not been predicated.
538   virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
539 
540   /// PredicateInstruction - Convert the instruction into a predicated
541   /// instruction. It returns true if the operation was successful.
542   virtual
543   bool PredicateInstruction(MachineInstr *MI,
544                         const SmallVectorImpl<MachineOperand> &Pred) const = 0;
545 
546   /// SubsumesPredicate - Returns true if the first specified predicate
547   /// subsumes the second, e.g. GE subsumes GT.
548   virtual
SubsumesPredicate(const SmallVectorImpl<MachineOperand> & Pred1,const SmallVectorImpl<MachineOperand> & Pred2)549   bool SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
550                          const SmallVectorImpl<MachineOperand> &Pred2) const {
551     return false;
552   }
553 
554   /// DefinesPredicate - If the specified instruction defines any predicate
555   /// or condition code register(s) used for predication, returns true as well
556   /// as the definition predicate(s) by reference.
DefinesPredicate(MachineInstr * MI,std::vector<MachineOperand> & Pred)557   virtual bool DefinesPredicate(MachineInstr *MI,
558                                 std::vector<MachineOperand> &Pred) const {
559     return false;
560   }
561 
562   /// isPredicable - Return true if the specified instruction can be predicated.
563   /// By default, this returns true for every instruction with a
564   /// PredicateOperand.
isPredicable(MachineInstr * MI)565   virtual bool isPredicable(MachineInstr *MI) const {
566     return MI->getDesc().isPredicable();
567   }
568 
569   /// isSafeToMoveRegClassDefs - Return true if it's safe to move a machine
570   /// instruction that defines the specified register class.
isSafeToMoveRegClassDefs(const TargetRegisterClass * RC)571   virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
572     return true;
573   }
574 
575   /// isSchedulingBoundary - Test if the given instruction should be
576   /// considered a scheduling boundary. This primarily includes labels and
577   /// terminators.
578   virtual bool isSchedulingBoundary(const MachineInstr *MI,
579                                     const MachineBasicBlock *MBB,
580                                     const MachineFunction &MF) const = 0;
581 
582   /// Measure the specified inline asm to determine an approximation of its
583   /// length.
584   virtual unsigned getInlineAsmLength(const char *Str,
585                                       const MCAsmInfo &MAI) const;
586 
587   /// CreateTargetHazardRecognizer - Allocate and return a hazard recognizer to
588   /// use for this target when scheduling the machine instructions before
589   /// register allocation.
590   virtual ScheduleHazardRecognizer*
591   CreateTargetHazardRecognizer(const TargetMachine *TM,
592                                const ScheduleDAG *DAG) const = 0;
593 
594   /// CreateTargetPostRAHazardRecognizer - Allocate and return a hazard
595   /// recognizer to use for this target when scheduling the machine instructions
596   /// after register allocation.
597   virtual ScheduleHazardRecognizer*
598   CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
599                                      const ScheduleDAG *DAG) const = 0;
600 
601   /// AnalyzeCompare - For a comparison instruction, return the source register
602   /// in SrcReg and the value it compares against in CmpValue. Return true if
603   /// the comparison instruction can be analyzed.
AnalyzeCompare(const MachineInstr * MI,unsigned & SrcReg,int & Mask,int & Value)604   virtual bool AnalyzeCompare(const MachineInstr *MI,
605                               unsigned &SrcReg, int &Mask, int &Value) const {
606     return false;
607   }
608 
609   /// OptimizeCompareInstr - See if the comparison instruction can be converted
610   /// into something more efficient. E.g., on ARM most instructions can set the
611   /// flags register, obviating the need for a separate CMP.
OptimizeCompareInstr(MachineInstr * CmpInstr,unsigned SrcReg,int Mask,int Value,const MachineRegisterInfo * MRI)612   virtual bool OptimizeCompareInstr(MachineInstr *CmpInstr,
613                                     unsigned SrcReg, int Mask, int Value,
614                                     const MachineRegisterInfo *MRI) const {
615     return false;
616   }
617 
618   /// FoldImmediate - 'Reg' is known to be defined by a move immediate
619   /// instruction, try to fold the immediate into the use instruction.
FoldImmediate(MachineInstr * UseMI,MachineInstr * DefMI,unsigned Reg,MachineRegisterInfo * MRI)620   virtual bool FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
621                              unsigned Reg, MachineRegisterInfo *MRI) const {
622     return false;
623   }
624 
625   /// getNumMicroOps - Return the number of u-operations the given machine
626   /// instruction will be decoded to on the target cpu.
627   virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
628                                   const MachineInstr *MI) const;
629 
630   /// isZeroCost - Return true for pseudo instructions that don't consume any
631   /// machine resources in their current form. These are common cases that the
632   /// scheduler should consider free, rather than conservatively handling them
633   /// as instructions with no itinerary.
isZeroCost(unsigned Opcode)634   bool isZeroCost(unsigned Opcode) const {
635     return Opcode <= TargetOpcode::COPY;
636   }
637 
638   /// getOperandLatency - Compute and return the use operand latency of a given
639   /// pair of def and use.
640   /// In most cases, the static scheduling itinerary was enough to determine the
641   /// operand latency. But it may not be possible for instructions with variable
642   /// number of defs / uses.
643   virtual int getOperandLatency(const InstrItineraryData *ItinData,
644                               const MachineInstr *DefMI, unsigned DefIdx,
645                               const MachineInstr *UseMI, unsigned UseIdx) const;
646 
647   virtual int getOperandLatency(const InstrItineraryData *ItinData,
648                                 SDNode *DefNode, unsigned DefIdx,
649                                 SDNode *UseNode, unsigned UseIdx) const;
650 
651   /// getInstrLatency - Compute the instruction latency of a given instruction.
652   /// If the instruction has higher cost when predicated, it's returned via
653   /// PredCost.
654   virtual int getInstrLatency(const InstrItineraryData *ItinData,
655                               const MachineInstr *MI,
656                               unsigned *PredCost = 0) const;
657 
658   virtual int getInstrLatency(const InstrItineraryData *ItinData,
659                               SDNode *Node) const;
660 
661   /// isHighLatencyDef - Return true if this opcode has high latency to its
662   /// result.
isHighLatencyDef(int opc)663   virtual bool isHighLatencyDef(int opc) const { return false; }
664 
665   /// hasHighOperandLatency - Compute operand latency between a def of 'Reg'
666   /// and an use in the current loop, return true if the target considered
667   /// it 'high'. This is used by optimization passes such as machine LICM to
668   /// determine whether it makes sense to hoist an instruction out even in
669   /// high register pressure situation.
670   virtual
hasHighOperandLatency(const InstrItineraryData * ItinData,const MachineRegisterInfo * MRI,const MachineInstr * DefMI,unsigned DefIdx,const MachineInstr * UseMI,unsigned UseIdx)671   bool hasHighOperandLatency(const InstrItineraryData *ItinData,
672                              const MachineRegisterInfo *MRI,
673                              const MachineInstr *DefMI, unsigned DefIdx,
674                              const MachineInstr *UseMI, unsigned UseIdx) const {
675     return false;
676   }
677 
678   /// hasLowDefLatency - Compute operand latency of a def of 'Reg', return true
679   /// if the target considered it 'low'.
680   virtual
681   bool hasLowDefLatency(const InstrItineraryData *ItinData,
682                         const MachineInstr *DefMI, unsigned DefIdx) const;
683 
684   /// verifyInstruction - Perform target specific instruction verification.
685   virtual
verifyInstruction(const MachineInstr * MI,StringRef & ErrInfo)686   bool verifyInstruction(const MachineInstr *MI, StringRef &ErrInfo) const {
687     return true;
688   }
689 
690   /// getExecutionDomain - Return the current execution domain and bit mask of
691   /// possible domains for instruction.
692   ///
693   /// Some micro-architectures have multiple execution domains, and multiple
694   /// opcodes that perform the same operation in different domains.  For
695   /// example, the x86 architecture provides the por, orps, and orpd
696   /// instructions that all do the same thing.  There is a latency penalty if a
697   /// register is written in one domain and read in another.
698   ///
699   /// This function returns a pair (domain, mask) containing the execution
700   /// domain of MI, and a bit mask of possible domains.  The setExecutionDomain
701   /// function can be used to change the opcode to one of the domains in the
702   /// bit mask.  Instructions whose execution domain can't be changed should
703   /// return a 0 mask.
704   ///
705   /// The execution domain numbers don't have any special meaning except domain
706   /// 0 is used for instructions that are not associated with any interesting
707   /// execution domain.
708   ///
709   virtual std::pair<uint16_t, uint16_t>
getExecutionDomain(const MachineInstr * MI)710   getExecutionDomain(const MachineInstr *MI) const {
711     return std::make_pair(0, 0);
712   }
713 
714   /// setExecutionDomain - Change the opcode of MI to execute in Domain.
715   ///
716   /// The bit (1 << Domain) must be set in the mask returned from
717   /// getExecutionDomain(MI).
718   ///
setExecutionDomain(MachineInstr * MI,unsigned Domain)719   virtual void setExecutionDomain(MachineInstr *MI, unsigned Domain) const {}
720 
721 private:
722   int CallFrameSetupOpcode, CallFrameDestroyOpcode;
723 };
724 
725 /// TargetInstrInfoImpl - This is the default implementation of
726 /// TargetInstrInfo, which just provides a couple of default implementations
727 /// for various methods.  This separated out because it is implemented in
728 /// libcodegen, not in libtarget.
729 class TargetInstrInfoImpl : public TargetInstrInfo {
730 protected:
731   TargetInstrInfoImpl(int CallFrameSetupOpcode = -1,
732                       int CallFrameDestroyOpcode = -1)
TargetInstrInfo(CallFrameSetupOpcode,CallFrameDestroyOpcode)733     : TargetInstrInfo(CallFrameSetupOpcode, CallFrameDestroyOpcode) {}
734 public:
735   virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
736                                        MachineBasicBlock *NewDest) const;
737   virtual MachineInstr *commuteInstruction(MachineInstr *MI,
738                                            bool NewMI = false) const;
739   virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
740                                      unsigned &SrcOpIdx2) const;
741   virtual bool canFoldMemoryOperand(const MachineInstr *MI,
742                                     const SmallVectorImpl<unsigned> &Ops) const;
743   virtual bool hasLoadFromStackSlot(const MachineInstr *MI,
744                                     const MachineMemOperand *&MMO,
745                                     int &FrameIndex) const;
746   virtual bool hasStoreToStackSlot(const MachineInstr *MI,
747                                    const MachineMemOperand *&MMO,
748                                    int &FrameIndex) const;
749   virtual bool PredicateInstruction(MachineInstr *MI,
750                             const SmallVectorImpl<MachineOperand> &Pred) const;
751   virtual void reMaterialize(MachineBasicBlock &MBB,
752                              MachineBasicBlock::iterator MI,
753                              unsigned DestReg, unsigned SubReg,
754                              const MachineInstr *Orig,
755                              const TargetRegisterInfo &TRI) const;
756   virtual MachineInstr *duplicate(MachineInstr *Orig,
757                                   MachineFunction &MF) const;
758   virtual bool produceSameValue(const MachineInstr *MI0,
759                                 const MachineInstr *MI1,
760                                 const MachineRegisterInfo *MRI) const;
761   virtual bool isSchedulingBoundary(const MachineInstr *MI,
762                                     const MachineBasicBlock *MBB,
763                                     const MachineFunction &MF) const;
764 
765   bool usePreRAHazardRecognizer() const;
766 
767   virtual ScheduleHazardRecognizer *
768   CreateTargetHazardRecognizer(const TargetMachine*, const ScheduleDAG*) const;
769 
770   virtual ScheduleHazardRecognizer *
771   CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
772                                      const ScheduleDAG*) const;
773 };
774 
775 } // End llvm namespace
776 
777 #endif
778