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