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