Minor cleanup of defaultDefLatency API
[oota-llvm.git] / include / llvm / Target / TargetInstrInfo.h
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/ADT/SmallSet.h"
18 #include "llvm/MC/MCInstrInfo.h"
19 #include "llvm/CodeGen/DFAPacketizer.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21
22 namespace llvm {
23
24 class InstrItineraryData;
25 class LiveVariables;
26 class MCAsmInfo;
27 class MachineMemOperand;
28 class MachineRegisterInfo;
29 class MDNode;
30 class MCInst;
31 class MCSchedModel;
32 class SDNode;
33 class ScheduleHazardRecognizer;
34 class SelectionDAG;
35 class ScheduleDAG;
36 class TargetRegisterClass;
37 class TargetRegisterInfo;
38 class BranchProbability;
39
40 template<class T> class SmallVectorImpl;
41
42
43 //---------------------------------------------------------------------------
44 ///
45 /// TargetInstrInfo - Interface to description of machine instruction set
46 ///
47 class TargetInstrInfo : public MCInstrInfo {
48   TargetInstrInfo(const TargetInstrInfo &);  // DO NOT IMPLEMENT
49   void operator=(const TargetInstrInfo &);   // DO NOT IMPLEMENT
50 public:
51   TargetInstrInfo(int CFSetupOpcode = -1, int CFDestroyOpcode = -1)
52     : CallFrameSetupOpcode(CFSetupOpcode),
53       CallFrameDestroyOpcode(CFDestroyOpcode) {
54   }
55
56   virtual ~TargetInstrInfo();
57
58   /// getRegClass - Givem a machine instruction descriptor, returns the register
59   /// class constraint for OpNum, or NULL.
60   const TargetRegisterClass *getRegClass(const MCInstrDesc &TID,
61                                          unsigned OpNum,
62                                          const TargetRegisterInfo *TRI,
63                                          const MachineFunction &MF) const;
64
65   /// isTriviallyReMaterializable - Return true if the instruction is trivially
66   /// rematerializable, meaning it has no side effects and requires no operands
67   /// that aren't always available.
68   bool isTriviallyReMaterializable(const MachineInstr *MI,
69                                    AliasAnalysis *AA = 0) const {
70     return MI->getOpcode() == TargetOpcode::IMPLICIT_DEF ||
71            (MI->getDesc().isRematerializable() &&
72             (isReallyTriviallyReMaterializable(MI, AA) ||
73              isReallyTriviallyReMaterializableGeneric(MI, AA)));
74   }
75
76 protected:
77   /// isReallyTriviallyReMaterializable - For instructions with opcodes for
78   /// which the M_REMATERIALIZABLE flag is set, this hook lets the target
79   /// specify whether the instruction is actually trivially rematerializable,
80   /// taking into consideration its operands. This predicate must return false
81   /// if the instruction has any side effects other than producing a value, or
82   /// if it requres any address registers that are not always available.
83   virtual bool isReallyTriviallyReMaterializable(const MachineInstr *MI,
84                                                  AliasAnalysis *AA) const {
85     return false;
86   }
87
88 private:
89   /// isReallyTriviallyReMaterializableGeneric - For instructions with opcodes
90   /// for which the M_REMATERIALIZABLE flag is set and the target hook
91   /// isReallyTriviallyReMaterializable returns false, this function does
92   /// target-independent tests to determine if the instruction is really
93   /// trivially rematerializable.
94   bool isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
95                                                 AliasAnalysis *AA) const;
96
97 public:
98   /// getCallFrameSetup/DestroyOpcode - These methods return the opcode of the
99   /// frame setup/destroy instructions if they exist (-1 otherwise).  Some
100   /// targets use pseudo instructions in order to abstract away the difference
101   /// between operating with a frame pointer and operating without, through the
102   /// use of these two instructions.
103   ///
104   int getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
105   int getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
106
107   /// isCoalescableExtInstr - Return true if the instruction is a "coalescable"
108   /// extension instruction. That is, it's like a copy where it's legal for the
109   /// source to overlap the destination. e.g. X86::MOVSX64rr32. If this returns
110   /// true, then it's expected the pre-extension value is available as a subreg
111   /// of the result register. This also returns the sub-register index in
112   /// SubIdx.
113   virtual bool isCoalescableExtInstr(const MachineInstr &MI,
114                                      unsigned &SrcReg, unsigned &DstReg,
115                                      unsigned &SubIdx) const {
116     return false;
117   }
118
119   /// isLoadFromStackSlot - If the specified machine instruction is a direct
120   /// load from a stack slot, return the virtual or physical register number of
121   /// the destination along with the FrameIndex of the loaded stack slot.  If
122   /// not, return 0.  This predicate must return 0 if the instruction has
123   /// any side effects other than loading from the stack slot.
124   virtual unsigned isLoadFromStackSlot(const MachineInstr *MI,
125                                        int &FrameIndex) const {
126     return 0;
127   }
128
129   /// isLoadFromStackSlotPostFE - Check for post-frame ptr elimination
130   /// stack locations as well.  This uses a heuristic so it isn't
131   /// reliable for correctness.
132   virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr *MI,
133                                              int &FrameIndex) const {
134     return 0;
135   }
136
137   /// hasLoadFromStackSlot - If the specified machine instruction has
138   /// a load from a stack slot, return true along with the FrameIndex
139   /// of the loaded stack slot and the machine mem operand containing
140   /// the reference.  If not, return false.  Unlike
141   /// isLoadFromStackSlot, this returns true for any instructions that
142   /// loads from the stack.  This is just a hint, as some cases may be
143   /// missed.
144   virtual bool hasLoadFromStackSlot(const MachineInstr *MI,
145                                     const MachineMemOperand *&MMO,
146                                     int &FrameIndex) const {
147     return 0;
148   }
149
150   /// isStoreToStackSlot - If the specified machine instruction is a direct
151   /// store to a stack slot, return the virtual or physical register number of
152   /// the source reg along with the FrameIndex of the loaded stack slot.  If
153   /// not, return 0.  This predicate must return 0 if the instruction has
154   /// any side effects other than storing to the stack slot.
155   virtual unsigned isStoreToStackSlot(const MachineInstr *MI,
156                                       int &FrameIndex) const {
157     return 0;
158   }
159
160   /// isStoreToStackSlotPostFE - Check for post-frame ptr elimination
161   /// stack locations as well.  This uses a heuristic so it isn't
162   /// reliable for correctness.
163   virtual unsigned isStoreToStackSlotPostFE(const MachineInstr *MI,
164                                             int &FrameIndex) const {
165     return 0;
166   }
167
168   /// hasStoreToStackSlot - If the specified machine instruction has a
169   /// store to a stack slot, return true along with the FrameIndex of
170   /// the loaded stack slot and the machine mem operand containing the
171   /// reference.  If not, return false.  Unlike isStoreToStackSlot,
172   /// this returns true for any instructions that stores to the
173   /// stack.  This is just a hint, as some cases may be missed.
174   virtual bool hasStoreToStackSlot(const MachineInstr *MI,
175                                    const MachineMemOperand *&MMO,
176                                    int &FrameIndex) const {
177     return 0;
178   }
179
180   /// reMaterialize - Re-issue the specified 'original' instruction at the
181   /// specific location targeting a new destination register.
182   /// The register in Orig->getOperand(0).getReg() will be substituted by
183   /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
184   /// SubIdx.
185   virtual void reMaterialize(MachineBasicBlock &MBB,
186                              MachineBasicBlock::iterator MI,
187                              unsigned DestReg, unsigned SubIdx,
188                              const MachineInstr *Orig,
189                              const TargetRegisterInfo &TRI) const = 0;
190
191   /// scheduleTwoAddrSource - Schedule the copy / re-mat of the source of the
192   /// two-addrss instruction inserted by two-address pass.
193   virtual void scheduleTwoAddrSource(MachineInstr *SrcMI,
194                                      MachineInstr *UseMI,
195                                      const TargetRegisterInfo &TRI) const {
196     // Do nothing.
197   }
198
199   /// duplicate - Create a duplicate of the Orig instruction in MF. This is like
200   /// MachineFunction::CloneMachineInstr(), but the target may update operands
201   /// that are required to be unique.
202   ///
203   /// The instruction must be duplicable as indicated by isNotDuplicable().
204   virtual MachineInstr *duplicate(MachineInstr *Orig,
205                                   MachineFunction &MF) const = 0;
206
207   /// convertToThreeAddress - This method must be implemented by targets that
208   /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
209   /// may be able to convert a two-address instruction into one or more true
210   /// three-address instructions on demand.  This allows the X86 target (for
211   /// example) to convert ADD and SHL instructions into LEA instructions if they
212   /// would require register copies due to two-addressness.
213   ///
214   /// This method returns a null pointer if the transformation cannot be
215   /// performed, otherwise it returns the last new instruction.
216   ///
217   virtual MachineInstr *
218   convertToThreeAddress(MachineFunction::iterator &MFI,
219                    MachineBasicBlock::iterator &MBBI, LiveVariables *LV) const {
220     return 0;
221   }
222
223   /// commuteInstruction - If a target has any instructions that are
224   /// commutable but require converting to different instructions or making
225   /// non-trivial changes to commute them, this method can overloaded to do
226   /// that.  The default implementation simply swaps the commutable operands.
227   /// If NewMI is false, MI is modified in place and returned; otherwise, a
228   /// new machine instruction is created and returned.  Do not call this
229   /// method for a non-commutable instruction, but there may be some cases
230   /// where this method fails and returns null.
231   virtual MachineInstr *commuteInstruction(MachineInstr *MI,
232                                            bool NewMI = false) const = 0;
233
234   /// findCommutedOpIndices - If specified MI is commutable, return the two
235   /// operand indices that would swap value. Return false if the instruction
236   /// is not in a form which this routine understands.
237   virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
238                                      unsigned &SrcOpIdx2) const = 0;
239
240   /// produceSameValue - Return true if two machine instructions would produce
241   /// identical values. By default, this is only true when the two instructions
242   /// are deemed identical except for defs. If this function is called when the
243   /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
244   /// aggressive checks.
245   virtual bool produceSameValue(const MachineInstr *MI0,
246                                 const MachineInstr *MI1,
247                                 const MachineRegisterInfo *MRI = 0) const = 0;
248
249   /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
250   /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
251   /// implemented for a target).  Upon success, this returns false and returns
252   /// with the following information in various cases:
253   ///
254   /// 1. If this block ends with no branches (it just falls through to its succ)
255   ///    just return false, leaving TBB/FBB null.
256   /// 2. If this block ends with only an unconditional branch, it sets TBB to be
257   ///    the destination block.
258   /// 3. If this block ends with a conditional branch and it falls through to a
259   ///    successor block, it sets TBB to be the branch destination block and a
260   ///    list of operands that evaluate the condition. These operands can be
261   ///    passed to other TargetInstrInfo methods to create new branches.
262   /// 4. If this block ends with a conditional branch followed by an
263   ///    unconditional branch, it returns the 'true' destination in TBB, the
264   ///    'false' destination in FBB, and a list of operands that evaluate the
265   ///    condition.  These operands can be passed to other TargetInstrInfo
266   ///    methods to create new branches.
267   ///
268   /// Note that RemoveBranch and InsertBranch must be implemented to support
269   /// cases where this method returns success.
270   ///
271   /// If AllowModify is true, then this routine is allowed to modify the basic
272   /// block (e.g. delete instructions after the unconditional branch).
273   ///
274   virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
275                              MachineBasicBlock *&FBB,
276                              SmallVectorImpl<MachineOperand> &Cond,
277                              bool AllowModify = false) const {
278     return true;
279   }
280
281   /// RemoveBranch - Remove the branching code at the end of the specific MBB.
282   /// This is only invoked in cases where AnalyzeBranch returns success. It
283   /// returns the number of instructions that were removed.
284   virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
285     llvm_unreachable("Target didn't implement TargetInstrInfo::RemoveBranch!");
286   }
287
288   /// InsertBranch - Insert branch code into the end of the specified
289   /// MachineBasicBlock.  The operands to this method are the same as those
290   /// returned by AnalyzeBranch.  This is only invoked in cases where
291   /// AnalyzeBranch returns success. It returns the number of instructions
292   /// inserted.
293   ///
294   /// It is also invoked by tail merging to add unconditional branches in
295   /// cases where AnalyzeBranch doesn't apply because there was no original
296   /// branch to analyze.  At least this much must be implemented, else tail
297   /// merging needs to be disabled.
298   virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
299                                 MachineBasicBlock *FBB,
300                                 const SmallVectorImpl<MachineOperand> &Cond,
301                                 DebugLoc DL) const {
302     llvm_unreachable("Target didn't implement TargetInstrInfo::InsertBranch!");
303   }
304
305   /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
306   /// after it, replacing it with an unconditional branch to NewDest. This is
307   /// used by the tail merging pass.
308   virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
309                                        MachineBasicBlock *NewDest) const = 0;
310
311   /// isLegalToSplitMBBAt - Return true if it's legal to split the given basic
312   /// block at the specified instruction (i.e. instruction would be the start
313   /// of a new basic block).
314   virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
315                                    MachineBasicBlock::iterator MBBI) const {
316     return true;
317   }
318
319   /// isProfitableToIfCvt - Return true if it's profitable to predicate
320   /// instructions with accumulated instruction latency of "NumCycles"
321   /// of the specified basic block, where the probability of the instructions
322   /// being executed is given by Probability, and Confidence is a measure
323   /// of our confidence that it will be properly predicted.
324   virtual
325   bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
326                            unsigned ExtraPredCycles,
327                            const BranchProbability &Probability) const {
328     return false;
329   }
330
331   /// isProfitableToIfCvt - Second variant of isProfitableToIfCvt, this one
332   /// checks for the case where two basic blocks from true and false path
333   /// of a if-then-else (diamond) are predicated on mutally exclusive
334   /// predicates, where the probability of the true path being taken is given
335   /// by Probability, and Confidence is a measure of our confidence that it
336   /// will be properly predicted.
337   virtual bool
338   isProfitableToIfCvt(MachineBasicBlock &TMBB,
339                       unsigned NumTCycles, unsigned ExtraTCycles,
340                       MachineBasicBlock &FMBB,
341                       unsigned NumFCycles, unsigned ExtraFCycles,
342                       const BranchProbability &Probability) const {
343     return false;
344   }
345
346   /// isProfitableToDupForIfCvt - Return true if it's profitable for
347   /// if-converter to duplicate instructions of specified accumulated
348   /// instruction latencies in the specified MBB to enable if-conversion.
349   /// The probability of the instructions being executed is given by
350   /// Probability, and Confidence is a measure of our confidence that it
351   /// will be properly predicted.
352   virtual bool
353   isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
354                             const BranchProbability &Probability) const {
355     return false;
356   }
357
358   /// isProfitableToUnpredicate - Return true if it's profitable to unpredicate
359   /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
360   /// exclusive predicates.
361   /// e.g.
362   ///   subeq  r0, r1, #1
363   ///   addne  r0, r1, #1
364   /// =>
365   ///   sub    r0, r1, #1
366   ///   addne  r0, r1, #1
367   ///
368   /// This may be profitable is conditional instructions are always executed.
369   virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
370                                          MachineBasicBlock &FMBB) const {
371     return false;
372   }
373
374   /// canInsertSelect - Return true if it is possible to insert a select
375   /// instruction that chooses between TrueReg and FalseReg based on the
376   /// condition code in Cond.
377   ///
378   /// When successful, also return the latency in cycles from TrueReg,
379   /// FalseReg, and Cond to the destination register. The Cond latency should
380   /// compensate for a conditional branch being removed. For example, if a
381   /// conditional branch has a 3 cycle latency from the condition code read,
382   /// and a cmov instruction has a 2 cycle latency from the condition code
383   /// read, CondCycles should be returned as -1.
384   ///
385   /// @param MBB         Block where select instruction would be inserted.
386   /// @param Cond        Condition returned by AnalyzeBranch.
387   /// @param TrueReg     Virtual register to select when Cond is true.
388   /// @param FalseReg    Virtual register to select when Cond is false.
389   /// @param CondCycles  Latency from Cond+Branch to select output.
390   /// @param TrueCycles  Latency from TrueReg to select output.
391   /// @param FalseCycles Latency from FalseReg to select output.
392   virtual bool canInsertSelect(const MachineBasicBlock &MBB,
393                                const SmallVectorImpl<MachineOperand> &Cond,
394                                unsigned TrueReg, unsigned FalseReg,
395                                int &CondCycles,
396                                int &TrueCycles, int &FalseCycles) const {
397     return false;
398   }
399
400   /// insertSelect - Insert a select instruction into MBB before I that will
401   /// copy TrueReg to DstReg when Cond is true, and FalseReg to DstReg when
402   /// Cond is false.
403   ///
404   /// This function can only be called after canInsertSelect() returned true.
405   /// The condition in Cond comes from AnalyzeBranch, and it can be assumed
406   /// that the same flags or registers required by Cond are available at the
407   /// insertion point.
408   ///
409   /// @param MBB      Block where select instruction should be inserted.
410   /// @param I        Insertion point.
411   /// @param DL       Source location for debugging.
412   /// @param DstReg   Virtual register to be defined by select instruction.
413   /// @param Cond     Condition as computed by AnalyzeBranch.
414   /// @param TrueReg  Virtual register to copy when Cond is true.
415   /// @param FalseReg Virtual register to copy when Cons is false.
416   virtual void insertSelect(MachineBasicBlock &MBB,
417                             MachineBasicBlock::iterator I, DebugLoc DL,
418                             unsigned DstReg,
419                             const SmallVectorImpl<MachineOperand> &Cond,
420                             unsigned TrueReg, unsigned FalseReg) const {
421     llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!");
422   }
423
424   /// copyPhysReg - Emit instructions to copy a pair of physical registers.
425   virtual void copyPhysReg(MachineBasicBlock &MBB,
426                            MachineBasicBlock::iterator MI, DebugLoc DL,
427                            unsigned DestReg, unsigned SrcReg,
428                            bool KillSrc) const {
429     llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
430   }
431
432   /// storeRegToStackSlot - Store the specified register of the given register
433   /// class to the specified stack frame index. The store instruction is to be
434   /// added to the given machine basic block before the specified machine
435   /// instruction. If isKill is true, the register operand is the last use and
436   /// must be marked kill.
437   virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
438                                    MachineBasicBlock::iterator MI,
439                                    unsigned SrcReg, bool isKill, int FrameIndex,
440                                    const TargetRegisterClass *RC,
441                                    const TargetRegisterInfo *TRI) const {
442     llvm_unreachable("Target didn't implement "
443                      "TargetInstrInfo::storeRegToStackSlot!");
444   }
445
446   /// loadRegFromStackSlot - Load the specified register of the given register
447   /// class from the specified stack frame index. The load instruction is to be
448   /// added to the given machine basic block before the specified machine
449   /// instruction.
450   virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
451                                     MachineBasicBlock::iterator MI,
452                                     unsigned DestReg, int FrameIndex,
453                                     const TargetRegisterClass *RC,
454                                     const TargetRegisterInfo *TRI) const {
455     llvm_unreachable("Target didn't implement "
456                      "TargetInstrInfo::loadRegFromStackSlot!");
457   }
458
459   /// expandPostRAPseudo - This function is called for all pseudo instructions
460   /// that remain after register allocation. Many pseudo instructions are
461   /// created to help register allocation. This is the place to convert them
462   /// into real instructions. The target can edit MI in place, or it can insert
463   /// new instructions and erase MI. The function should return true if
464   /// anything was changed.
465   virtual bool expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
466     return false;
467   }
468
469   /// emitFrameIndexDebugValue - Emit a target-dependent form of
470   /// DBG_VALUE encoding the address of a frame index.  Addresses would
471   /// normally be lowered the same way as other addresses on the target,
472   /// e.g. in load instructions.  For targets that do not support this
473   /// the debug info is simply lost.
474   /// If you add this for a target you should handle this DBG_VALUE in the
475   /// target-specific AsmPrinter code as well; you will probably get invalid
476   /// assembly output if you don't.
477   virtual MachineInstr *emitFrameIndexDebugValue(MachineFunction &MF,
478                                                  int FrameIx,
479                                                  uint64_t Offset,
480                                                  const MDNode *MDPtr,
481                                                  DebugLoc dl) const {
482     return 0;
483   }
484
485   /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
486   /// slot into the specified machine instruction for the specified operand(s).
487   /// If this is possible, a new instruction is returned with the specified
488   /// operand folded, otherwise NULL is returned.
489   /// The new instruction is inserted before MI, and the client is responsible
490   /// for removing the old instruction.
491   MachineInstr* foldMemoryOperand(MachineBasicBlock::iterator MI,
492                                   const SmallVectorImpl<unsigned> &Ops,
493                                   int FrameIndex) const;
494
495   /// foldMemoryOperand - Same as the previous version except it allows folding
496   /// of any load and store from / to any address, not just from a specific
497   /// stack slot.
498   MachineInstr* foldMemoryOperand(MachineBasicBlock::iterator MI,
499                                   const SmallVectorImpl<unsigned> &Ops,
500                                   MachineInstr* LoadMI) const;
501
502 protected:
503   /// foldMemoryOperandImpl - Target-dependent implementation for
504   /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
505   /// take care of adding a MachineMemOperand to the newly created instruction.
506   virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
507                                           MachineInstr* MI,
508                                           const SmallVectorImpl<unsigned> &Ops,
509                                           int FrameIndex) const {
510     return 0;
511   }
512
513   /// foldMemoryOperandImpl - Target-dependent implementation for
514   /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
515   /// take care of adding a MachineMemOperand to the newly created instruction.
516   virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
517                                               MachineInstr* MI,
518                                           const SmallVectorImpl<unsigned> &Ops,
519                                               MachineInstr* LoadMI) const {
520     return 0;
521   }
522
523 public:
524   /// canFoldMemoryOperand - Returns true for the specified load / store if
525   /// folding is possible.
526   virtual
527   bool canFoldMemoryOperand(const MachineInstr *MI,
528                             const SmallVectorImpl<unsigned> &Ops) const =0;
529
530   /// unfoldMemoryOperand - Separate a single instruction which folded a load or
531   /// a store or a load and a store into two or more instruction. If this is
532   /// possible, returns true as well as the new instructions by reference.
533   virtual bool unfoldMemoryOperand(MachineFunction &MF, MachineInstr *MI,
534                                 unsigned Reg, bool UnfoldLoad, bool UnfoldStore,
535                                  SmallVectorImpl<MachineInstr*> &NewMIs) const{
536     return false;
537   }
538
539   virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
540                                    SmallVectorImpl<SDNode*> &NewNodes) const {
541     return false;
542   }
543
544   /// getOpcodeAfterMemoryUnfold - Returns the opcode of the would be new
545   /// instruction after load / store are unfolded from an instruction of the
546   /// specified opcode. It returns zero if the specified unfolding is not
547   /// possible. If LoadRegIndex is non-null, it is filled in with the operand
548   /// index of the operand which will hold the register holding the loaded
549   /// value.
550   virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc,
551                                       bool UnfoldLoad, bool UnfoldStore,
552                                       unsigned *LoadRegIndex = 0) const {
553     return 0;
554   }
555
556   /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler
557   /// to determine if two loads are loading from the same base address. It
558   /// should only return true if the base pointers are the same and the
559   /// only differences between the two addresses are the offset. It also returns
560   /// the offsets by reference.
561   virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
562                                     int64_t &Offset1, int64_t &Offset2) const {
563     return false;
564   }
565
566   /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
567   /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
568   /// be scheduled togther. On some targets if two loads are loading from
569   /// addresses in the same cache line, it's better if they are scheduled
570   /// together. This function takes two integers that represent the load offsets
571   /// from the common base address. It returns true if it decides it's desirable
572   /// to schedule the two loads together. "NumLoads" is the number of loads that
573   /// have already been scheduled after Load1.
574   virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
575                                        int64_t Offset1, int64_t Offset2,
576                                        unsigned NumLoads) const {
577     return false;
578   }
579
580   /// ReverseBranchCondition - Reverses the branch condition of the specified
581   /// condition list, returning false on success and true if it cannot be
582   /// reversed.
583   virtual
584   bool ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
585     return true;
586   }
587
588   /// insertNoop - Insert a noop into the instruction stream at the specified
589   /// point.
590   virtual void insertNoop(MachineBasicBlock &MBB,
591                           MachineBasicBlock::iterator MI) const;
592
593
594   /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
595   virtual void getNoopForMachoTarget(MCInst &NopInst) const {
596     // Default to just using 'nop' string.
597   }
598
599
600   /// isPredicated - Returns true if the instruction is already predicated.
601   ///
602   virtual bool isPredicated(const MachineInstr *MI) const {
603     return false;
604   }
605
606   /// isUnpredicatedTerminator - Returns true if the instruction is a
607   /// terminator instruction that has not been predicated.
608   virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const = 0;
609
610   /// PredicateInstruction - Convert the instruction into a predicated
611   /// instruction. It returns true if the operation was successful.
612   virtual
613   bool PredicateInstruction(MachineInstr *MI,
614                         const SmallVectorImpl<MachineOperand> &Pred) const = 0;
615
616   /// SubsumesPredicate - Returns true if the first specified predicate
617   /// subsumes the second, e.g. GE subsumes GT.
618   virtual
619   bool SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
620                          const SmallVectorImpl<MachineOperand> &Pred2) const {
621     return false;
622   }
623
624   /// DefinesPredicate - If the specified instruction defines any predicate
625   /// or condition code register(s) used for predication, returns true as well
626   /// as the definition predicate(s) by reference.
627   virtual bool DefinesPredicate(MachineInstr *MI,
628                                 std::vector<MachineOperand> &Pred) const {
629     return false;
630   }
631
632   /// isPredicable - Return true if the specified instruction can be predicated.
633   /// By default, this returns true for every instruction with a
634   /// PredicateOperand.
635   virtual bool isPredicable(MachineInstr *MI) const {
636     return MI->getDesc().isPredicable();
637   }
638
639   /// isSafeToMoveRegClassDefs - Return true if it's safe to move a machine
640   /// instruction that defines the specified register class.
641   virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
642     return true;
643   }
644
645   /// isSchedulingBoundary - Test if the given instruction should be
646   /// considered a scheduling boundary. This primarily includes labels and
647   /// terminators.
648   virtual bool isSchedulingBoundary(const MachineInstr *MI,
649                                     const MachineBasicBlock *MBB,
650                                     const MachineFunction &MF) const = 0;
651
652   /// Measure the specified inline asm to determine an approximation of its
653   /// length.
654   virtual unsigned getInlineAsmLength(const char *Str,
655                                       const MCAsmInfo &MAI) const;
656
657   /// CreateTargetHazardRecognizer - Allocate and return a hazard recognizer to
658   /// use for this target when scheduling the machine instructions before
659   /// register allocation.
660   virtual ScheduleHazardRecognizer*
661   CreateTargetHazardRecognizer(const TargetMachine *TM,
662                                const ScheduleDAG *DAG) const = 0;
663
664   /// CreateTargetMIHazardRecognizer - Allocate and return a hazard recognizer
665   /// to use for this target when scheduling the machine instructions before
666   /// register allocation.
667   virtual ScheduleHazardRecognizer*
668   CreateTargetMIHazardRecognizer(const InstrItineraryData*,
669                                  const ScheduleDAG *DAG) const = 0;
670
671   /// CreateTargetPostRAHazardRecognizer - Allocate and return a hazard
672   /// recognizer to use for this target when scheduling the machine instructions
673   /// after register allocation.
674   virtual ScheduleHazardRecognizer*
675   CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
676                                      const ScheduleDAG *DAG) const = 0;
677
678   /// analyzeCompare - For a comparison instruction, return the source registers
679   /// in SrcReg and SrcReg2 if having two register operands, and the value it
680   /// compares against in CmpValue. Return true if the comparison instruction
681   /// can be analyzed.
682   virtual bool analyzeCompare(const MachineInstr *MI,
683                               unsigned &SrcReg, unsigned &SrcReg2,
684                               int &Mask, int &Value) const {
685     return false;
686   }
687
688   /// optimizeCompareInstr - See if the comparison instruction can be converted
689   /// into something more efficient. E.g., on ARM most instructions can set the
690   /// flags register, obviating the need for a separate CMP.
691   virtual bool optimizeCompareInstr(MachineInstr *CmpInstr,
692                                     unsigned SrcReg, unsigned SrcReg2,
693                                     int Mask, int Value,
694                                     const MachineRegisterInfo *MRI) const {
695     return false;
696   }
697
698   /// optimizeLoadInstr - Try to remove the load by folding it to a register
699   /// operand at the use. We fold the load instructions if and only if the
700   /// def and use are in the same BB. We only look at one load and see
701   /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
702   /// defined by the load we are trying to fold. DefMI returns the machine
703   /// instruction that defines FoldAsLoadDefReg, and the function returns
704   /// the machine instruction generated due to folding.
705   virtual MachineInstr* optimizeLoadInstr(MachineInstr *MI,
706                         const MachineRegisterInfo *MRI,
707                         unsigned &FoldAsLoadDefReg,
708                         MachineInstr *&DefMI) const {
709     return 0;
710   }
711
712   /// FoldImmediate - 'Reg' is known to be defined by a move immediate
713   /// instruction, try to fold the immediate into the use instruction.
714   virtual bool FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
715                              unsigned Reg, MachineRegisterInfo *MRI) const {
716     return false;
717   }
718
719   /// getNumMicroOps - Return the number of u-operations the given machine
720   /// instruction will be decoded to on the target cpu. The itinerary's
721   /// IssueWidth is the number of microops that can be dispatched each
722   /// cycle. An instruction with zero microops takes no dispatch resources.
723   virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
724                                   const MachineInstr *MI) const = 0;
725
726   /// isZeroCost - Return true for pseudo instructions that don't consume any
727   /// machine resources in their current form. These are common cases that the
728   /// scheduler should consider free, rather than conservatively handling them
729   /// as instructions with no itinerary.
730   bool isZeroCost(unsigned Opcode) const {
731     return Opcode <= TargetOpcode::COPY;
732   }
733
734   virtual int getOperandLatency(const InstrItineraryData *ItinData,
735                                 SDNode *DefNode, unsigned DefIdx,
736                                 SDNode *UseNode, unsigned UseIdx) const = 0;
737
738   /// getOperandLatency - Compute and return the use operand latency of a given
739   /// pair of def and use.
740   /// In most cases, the static scheduling itinerary was enough to determine the
741   /// operand latency. But it may not be possible for instructions with variable
742   /// number of defs / uses.
743   ///
744   /// This is a raw interface to the itinerary that may be directly overriden by
745   /// a target. Use computeOperandLatency to get the best estimate of latency.
746   virtual int getOperandLatency(const InstrItineraryData *ItinData,
747                                 const MachineInstr *DefMI, unsigned DefIdx,
748                                 const MachineInstr *UseMI,
749                                 unsigned UseIdx) const = 0;
750
751   /// computeOperandLatency - Compute and return the latency of the given data
752   /// dependent def and use when the operand indices are already known.
753   ///
754   /// FindMin may be set to get the minimum vs. expected latency.
755   unsigned computeOperandLatency(const InstrItineraryData *ItinData,
756                                  const MachineInstr *DefMI, unsigned DefIdx,
757                                  const MachineInstr *UseMI, unsigned UseIdx,
758                                  bool FindMin = false) const;
759
760   /// computeOperandLatency - Compute and return the latency of the given data
761   /// dependent def and use. DefMI must be a valid def. UseMI may be NULL for
762   /// an unknown use. If the subtarget allows, this may or may not need to call
763   /// getOperandLatency().
764   ///
765   /// FindMin may be set to get the minimum vs. expected latency. Minimum
766   /// latency is used for scheduling groups, while expected latency is for
767   /// instruction cost and critical path.
768   unsigned computeOperandLatency(const InstrItineraryData *ItinData,
769                                  const TargetRegisterInfo *TRI,
770                                  const MachineInstr *DefMI,
771                                  const MachineInstr *UseMI,
772                                  unsigned Reg, bool FindMin) const;
773
774   /// getOutputLatency - Compute and return the output dependency latency of a
775   /// a given pair of defs which both target the same register. This is usually
776   /// one.
777   virtual unsigned getOutputLatency(const InstrItineraryData *ItinData,
778                                     const MachineInstr *DefMI, unsigned DefIdx,
779                                     const MachineInstr *DepMI) const {
780     return 1;
781   }
782
783   /// getInstrLatency - Compute the instruction latency of a given instruction.
784   /// If the instruction has higher cost when predicated, it's returned via
785   /// PredCost.
786   virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
787                                    const MachineInstr *MI,
788                                    unsigned *PredCost = 0) const = 0;
789
790   virtual int getInstrLatency(const InstrItineraryData *ItinData,
791                               SDNode *Node) const = 0;
792
793   /// Return the default expected latency for a def based on it's opcode.
794   unsigned defaultDefLatency(const MCSchedModel *SchedModel,
795                              const MachineInstr *DefMI) const;
796
797   /// isHighLatencyDef - Return true if this opcode has high latency to its
798   /// result.
799   virtual bool isHighLatencyDef(int opc) const { return false; }
800
801   /// hasHighOperandLatency - Compute operand latency between a def of 'Reg'
802   /// and an use in the current loop, return true if the target considered
803   /// it 'high'. This is used by optimization passes such as machine LICM to
804   /// determine whether it makes sense to hoist an instruction out even in
805   /// high register pressure situation.
806   virtual
807   bool hasHighOperandLatency(const InstrItineraryData *ItinData,
808                              const MachineRegisterInfo *MRI,
809                              const MachineInstr *DefMI, unsigned DefIdx,
810                              const MachineInstr *UseMI, unsigned UseIdx) const {
811     return false;
812   }
813
814   /// hasLowDefLatency - Compute operand latency of a def of 'Reg', return true
815   /// if the target considered it 'low'.
816   virtual
817   bool hasLowDefLatency(const InstrItineraryData *ItinData,
818                         const MachineInstr *DefMI, unsigned DefIdx) const = 0;
819
820   /// verifyInstruction - Perform target specific instruction verification.
821   virtual
822   bool verifyInstruction(const MachineInstr *MI, StringRef &ErrInfo) const {
823     return true;
824   }
825
826   /// getExecutionDomain - Return the current execution domain and bit mask of
827   /// possible domains for instruction.
828   ///
829   /// Some micro-architectures have multiple execution domains, and multiple
830   /// opcodes that perform the same operation in different domains.  For
831   /// example, the x86 architecture provides the por, orps, and orpd
832   /// instructions that all do the same thing.  There is a latency penalty if a
833   /// register is written in one domain and read in another.
834   ///
835   /// This function returns a pair (domain, mask) containing the execution
836   /// domain of MI, and a bit mask of possible domains.  The setExecutionDomain
837   /// function can be used to change the opcode to one of the domains in the
838   /// bit mask.  Instructions whose execution domain can't be changed should
839   /// return a 0 mask.
840   ///
841   /// The execution domain numbers don't have any special meaning except domain
842   /// 0 is used for instructions that are not associated with any interesting
843   /// execution domain.
844   ///
845   virtual std::pair<uint16_t, uint16_t>
846   getExecutionDomain(const MachineInstr *MI) const {
847     return std::make_pair(0, 0);
848   }
849
850   /// setExecutionDomain - Change the opcode of MI to execute in Domain.
851   ///
852   /// The bit (1 << Domain) must be set in the mask returned from
853   /// getExecutionDomain(MI).
854   ///
855   virtual void setExecutionDomain(MachineInstr *MI, unsigned Domain) const {}
856
857
858   /// getPartialRegUpdateClearance - Returns the preferred minimum clearance
859   /// before an instruction with an unwanted partial register update.
860   ///
861   /// Some instructions only write part of a register, and implicitly need to
862   /// read the other parts of the register.  This may cause unwanted stalls
863   /// preventing otherwise unrelated instructions from executing in parallel in
864   /// an out-of-order CPU.
865   ///
866   /// For example, the x86 instruction cvtsi2ss writes its result to bits
867   /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
868   /// the instruction needs to wait for the old value of the register to become
869   /// available:
870   ///
871   ///   addps %xmm1, %xmm0
872   ///   movaps %xmm0, (%rax)
873   ///   cvtsi2ss %rbx, %xmm0
874   ///
875   /// In the code above, the cvtsi2ss instruction needs to wait for the addps
876   /// instruction before it can issue, even though the high bits of %xmm0
877   /// probably aren't needed.
878   ///
879   /// This hook returns the preferred clearance before MI, measured in
880   /// instructions.  Other defs of MI's operand OpNum are avoided in the last N
881   /// instructions before MI.  It should only return a positive value for
882   /// unwanted dependencies.  If the old bits of the defined register have
883   /// useful values, or if MI is determined to otherwise read the dependency,
884   /// the hook should return 0.
885   ///
886   /// The unwanted dependency may be handled by:
887   ///
888   /// 1. Allocating the same register for an MI def and use.  That makes the
889   ///    unwanted dependency identical to a required dependency.
890   ///
891   /// 2. Allocating a register for the def that has no defs in the previous N
892   ///    instructions.
893   ///
894   /// 3. Calling breakPartialRegDependency() with the same arguments.  This
895   ///    allows the target to insert a dependency breaking instruction.
896   ///
897   virtual unsigned
898   getPartialRegUpdateClearance(const MachineInstr *MI, unsigned OpNum,
899                                const TargetRegisterInfo *TRI) const {
900     // The default implementation returns 0 for no partial register dependency.
901     return 0;
902   }
903
904   /// breakPartialRegDependency - Insert a dependency-breaking instruction
905   /// before MI to eliminate an unwanted dependency on OpNum.
906   ///
907   /// If it wasn't possible to avoid a def in the last N instructions before MI
908   /// (see getPartialRegUpdateClearance), this hook will be called to break the
909   /// unwanted dependency.
910   ///
911   /// On x86, an xorps instruction can be used as a dependency breaker:
912   ///
913   ///   addps %xmm1, %xmm0
914   ///   movaps %xmm0, (%rax)
915   ///   xorps %xmm0, %xmm0
916   ///   cvtsi2ss %rbx, %xmm0
917   ///
918   /// An <imp-kill> operand should be added to MI if an instruction was
919   /// inserted.  This ties the instructions together in the post-ra scheduler.
920   ///
921   virtual void
922   breakPartialRegDependency(MachineBasicBlock::iterator MI, unsigned OpNum,
923                             const TargetRegisterInfo *TRI) const {}
924
925   /// Create machine specific model for scheduling.
926   virtual DFAPacketizer*
927     CreateTargetScheduleState(const TargetMachine*, const ScheduleDAG*) const {
928     return NULL;
929   }
930
931 private:
932   int CallFrameSetupOpcode, CallFrameDestroyOpcode;
933 };
934
935 /// TargetInstrInfoImpl - This is the default implementation of
936 /// TargetInstrInfo, which just provides a couple of default implementations
937 /// for various methods.  This separated out because it is implemented in
938 /// libcodegen, not in libtarget.
939 class TargetInstrInfoImpl : public TargetInstrInfo {
940 protected:
941   TargetInstrInfoImpl(int CallFrameSetupOpcode = -1,
942                       int CallFrameDestroyOpcode = -1)
943     : TargetInstrInfo(CallFrameSetupOpcode, CallFrameDestroyOpcode) {}
944 public:
945   virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
946                                        MachineBasicBlock *NewDest) const;
947   virtual MachineInstr *commuteInstruction(MachineInstr *MI,
948                                            bool NewMI = false) const;
949   virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
950                                      unsigned &SrcOpIdx2) const;
951   virtual bool canFoldMemoryOperand(const MachineInstr *MI,
952                                     const SmallVectorImpl<unsigned> &Ops) const;
953   virtual bool hasLoadFromStackSlot(const MachineInstr *MI,
954                                     const MachineMemOperand *&MMO,
955                                     int &FrameIndex) const;
956   virtual bool hasStoreToStackSlot(const MachineInstr *MI,
957                                    const MachineMemOperand *&MMO,
958                                    int &FrameIndex) const;
959   virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
960   virtual bool PredicateInstruction(MachineInstr *MI,
961                             const SmallVectorImpl<MachineOperand> &Pred) const;
962   virtual void reMaterialize(MachineBasicBlock &MBB,
963                              MachineBasicBlock::iterator MI,
964                              unsigned DestReg, unsigned SubReg,
965                              const MachineInstr *Orig,
966                              const TargetRegisterInfo &TRI) const;
967   virtual MachineInstr *duplicate(MachineInstr *Orig,
968                                   MachineFunction &MF) const;
969   virtual bool produceSameValue(const MachineInstr *MI0,
970                                 const MachineInstr *MI1,
971                                 const MachineRegisterInfo *MRI) const;
972   virtual bool isSchedulingBoundary(const MachineInstr *MI,
973                                     const MachineBasicBlock *MBB,
974                                     const MachineFunction &MF) const;
975
976   virtual int getOperandLatency(const InstrItineraryData *ItinData,
977                                 SDNode *DefNode, unsigned DefIdx,
978                                 SDNode *UseNode, unsigned UseIdx) const;
979
980   virtual int getInstrLatency(const InstrItineraryData *ItinData,
981                               SDNode *Node) const;
982
983   virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
984                                   const MachineInstr *MI) const;
985
986   virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
987                                    const MachineInstr *MI,
988                                    unsigned *PredCost = 0) const;
989
990   virtual
991   bool hasLowDefLatency(const InstrItineraryData *ItinData,
992                         const MachineInstr *DefMI, unsigned DefIdx) const;
993
994   virtual int getOperandLatency(const InstrItineraryData *ItinData,
995                                 const MachineInstr *DefMI, unsigned DefIdx,
996                                 const MachineInstr *UseMI,
997                                 unsigned UseIdx) const;
998
999   bool usePreRAHazardRecognizer() const;
1000
1001   virtual ScheduleHazardRecognizer *
1002   CreateTargetHazardRecognizer(const TargetMachine*, const ScheduleDAG*) const;
1003
1004   virtual ScheduleHazardRecognizer *
1005   CreateTargetMIHazardRecognizer(const InstrItineraryData*,
1006                                  const ScheduleDAG*) const;
1007
1008   virtual ScheduleHazardRecognizer *
1009   CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
1010                                      const ScheduleDAG*) const;
1011 };
1012
1013 } // End llvm namespace
1014
1015 #endif