LLVM API Documentation

TargetInstrInfo.h
Go to the documentation of this file.
00001 //===-- llvm/Target/TargetInstrInfo.h - Instruction Info --------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file describes the target machine instruction set to the code generator.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_TARGET_TARGETINSTRINFO_H
00015 #define LLVM_TARGET_TARGETINSTRINFO_H
00016 
00017 #include "llvm/ADT/SmallSet.h"
00018 #include "llvm/CodeGen/DFAPacketizer.h"
00019 #include "llvm/CodeGen/MachineFunction.h"
00020 #include "llvm/MC/MCInstrInfo.h"
00021 
00022 namespace llvm {
00023 
00024 class InstrItineraryData;
00025 class LiveVariables;
00026 class MCAsmInfo;
00027 class MachineMemOperand;
00028 class MachineRegisterInfo;
00029 class MDNode;
00030 class MCInst;
00031 class MCSchedModel;
00032 class SDNode;
00033 class ScheduleHazardRecognizer;
00034 class SelectionDAG;
00035 class ScheduleDAG;
00036 class TargetRegisterClass;
00037 class TargetRegisterInfo;
00038 class BranchProbability;
00039 
00040 template<class T> class SmallVectorImpl;
00041 
00042 
00043 //---------------------------------------------------------------------------
00044 ///
00045 /// TargetInstrInfo - Interface to description of machine instruction set
00046 ///
00047 class TargetInstrInfo : public MCInstrInfo {
00048   TargetInstrInfo(const TargetInstrInfo &) LLVM_DELETED_FUNCTION;
00049   void operator=(const TargetInstrInfo &) LLVM_DELETED_FUNCTION;
00050 public:
00051   TargetInstrInfo(int CFSetupOpcode = -1, int CFDestroyOpcode = -1)
00052     : CallFrameSetupOpcode(CFSetupOpcode),
00053       CallFrameDestroyOpcode(CFDestroyOpcode) {
00054   }
00055 
00056   virtual ~TargetInstrInfo();
00057 
00058   /// getRegClass - Givem a machine instruction descriptor, returns the register
00059   /// class constraint for OpNum, or NULL.
00060   const TargetRegisterClass *getRegClass(const MCInstrDesc &TID,
00061                                          unsigned OpNum,
00062                                          const TargetRegisterInfo *TRI,
00063                                          const MachineFunction &MF) const;
00064 
00065   /// isTriviallyReMaterializable - Return true if the instruction is trivially
00066   /// rematerializable, meaning it has no side effects and requires no operands
00067   /// that aren't always available.
00068   bool isTriviallyReMaterializable(const MachineInstr *MI,
00069                                    AliasAnalysis *AA = 0) const {
00070     return MI->getOpcode() == TargetOpcode::IMPLICIT_DEF ||
00071            (MI->getDesc().isRematerializable() &&
00072             (isReallyTriviallyReMaterializable(MI, AA) ||
00073              isReallyTriviallyReMaterializableGeneric(MI, AA)));
00074   }
00075 
00076 protected:
00077   /// isReallyTriviallyReMaterializable - For instructions with opcodes for
00078   /// which the M_REMATERIALIZABLE flag is set, this hook lets the target
00079   /// specify whether the instruction is actually trivially rematerializable,
00080   /// taking into consideration its operands. This predicate must return false
00081   /// if the instruction has any side effects other than producing a value, or
00082   /// if it requres any address registers that are not always available.
00083   virtual bool isReallyTriviallyReMaterializable(const MachineInstr *MI,
00084                                                  AliasAnalysis *AA) const {
00085     return false;
00086   }
00087 
00088 private:
00089   /// isReallyTriviallyReMaterializableGeneric - For instructions with opcodes
00090   /// for which the M_REMATERIALIZABLE flag is set and the target hook
00091   /// isReallyTriviallyReMaterializable returns false, this function does
00092   /// target-independent tests to determine if the instruction is really
00093   /// trivially rematerializable.
00094   bool isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
00095                                                 AliasAnalysis *AA) const;
00096 
00097 public:
00098   /// getCallFrameSetup/DestroyOpcode - These methods return the opcode of the
00099   /// frame setup/destroy instructions if they exist (-1 otherwise).  Some
00100   /// targets use pseudo instructions in order to abstract away the difference
00101   /// between operating with a frame pointer and operating without, through the
00102   /// use of these two instructions.
00103   ///
00104   int getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
00105   int getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
00106 
00107   /// isCoalescableExtInstr - Return true if the instruction is a "coalescable"
00108   /// extension instruction. That is, it's like a copy where it's legal for the
00109   /// source to overlap the destination. e.g. X86::MOVSX64rr32. If this returns
00110   /// true, then it's expected the pre-extension value is available as a subreg
00111   /// of the result register. This also returns the sub-register index in
00112   /// SubIdx.
00113   virtual bool isCoalescableExtInstr(const MachineInstr &MI,
00114                                      unsigned &SrcReg, unsigned &DstReg,
00115                                      unsigned &SubIdx) const {
00116     return false;
00117   }
00118 
00119   /// isLoadFromStackSlot - If the specified machine instruction is a direct
00120   /// load from a stack slot, return the virtual or physical register number of
00121   /// the destination along with the FrameIndex of the loaded stack slot.  If
00122   /// not, return 0.  This predicate must return 0 if the instruction has
00123   /// any side effects other than loading from the stack slot.
00124   virtual unsigned isLoadFromStackSlot(const MachineInstr *MI,
00125                                        int &FrameIndex) const {
00126     return 0;
00127   }
00128 
00129   /// isLoadFromStackSlotPostFE - Check for post-frame ptr elimination
00130   /// stack locations as well.  This uses a heuristic so it isn't
00131   /// reliable for correctness.
00132   virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr *MI,
00133                                              int &FrameIndex) const {
00134     return 0;
00135   }
00136 
00137   /// hasLoadFromStackSlot - If the specified machine instruction has
00138   /// a load from a stack slot, return true along with the FrameIndex
00139   /// of the loaded stack slot and the machine mem operand containing
00140   /// the reference.  If not, return false.  Unlike
00141   /// isLoadFromStackSlot, this returns true for any instructions that
00142   /// loads from the stack.  This is just a hint, as some cases may be
00143   /// missed.
00144   virtual bool hasLoadFromStackSlot(const MachineInstr *MI,
00145                                     const MachineMemOperand *&MMO,
00146                                     int &FrameIndex) const;
00147 
00148   /// isStoreToStackSlot - If the specified machine instruction is a direct
00149   /// store to a stack slot, return the virtual or physical register number of
00150   /// the source reg along with the FrameIndex of the loaded stack slot.  If
00151   /// not, return 0.  This predicate must return 0 if the instruction has
00152   /// any side effects other than storing to the stack slot.
00153   virtual unsigned isStoreToStackSlot(const MachineInstr *MI,
00154                                       int &FrameIndex) const {
00155     return 0;
00156   }
00157 
00158   /// isStoreToStackSlotPostFE - Check for post-frame ptr elimination
00159   /// stack locations as well.  This uses a heuristic so it isn't
00160   /// reliable for correctness.
00161   virtual unsigned isStoreToStackSlotPostFE(const MachineInstr *MI,
00162                                             int &FrameIndex) const {
00163     return 0;
00164   }
00165 
00166   /// hasStoreToStackSlot - If the specified machine instruction has a
00167   /// store to a stack slot, return true along with the FrameIndex of
00168   /// the loaded stack slot and the machine mem operand containing the
00169   /// reference.  If not, return false.  Unlike isStoreToStackSlot,
00170   /// this returns true for any instructions that stores to the
00171   /// stack.  This is just a hint, as some cases may be missed.
00172   virtual bool hasStoreToStackSlot(const MachineInstr *MI,
00173                                    const MachineMemOperand *&MMO,
00174                                    int &FrameIndex) const;
00175 
00176   /// reMaterialize - Re-issue the specified 'original' instruction at the
00177   /// specific location targeting a new destination register.
00178   /// The register in Orig->getOperand(0).getReg() will be substituted by
00179   /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
00180   /// SubIdx.
00181   virtual void reMaterialize(MachineBasicBlock &MBB,
00182                              MachineBasicBlock::iterator MI,
00183                              unsigned DestReg, unsigned SubIdx,
00184                              const MachineInstr *Orig,
00185                              const TargetRegisterInfo &TRI) const;
00186 
00187   /// duplicate - Create a duplicate of the Orig instruction in MF. This is like
00188   /// MachineFunction::CloneMachineInstr(), but the target may update operands
00189   /// that are required to be unique.
00190   ///
00191   /// The instruction must be duplicable as indicated by isNotDuplicable().
00192   virtual MachineInstr *duplicate(MachineInstr *Orig,
00193                                   MachineFunction &MF) const;
00194 
00195   /// convertToThreeAddress - This method must be implemented by targets that
00196   /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
00197   /// may be able to convert a two-address instruction into one or more true
00198   /// three-address instructions on demand.  This allows the X86 target (for
00199   /// example) to convert ADD and SHL instructions into LEA instructions if they
00200   /// would require register copies due to two-addressness.
00201   ///
00202   /// This method returns a null pointer if the transformation cannot be
00203   /// performed, otherwise it returns the last new instruction.
00204   ///
00205   virtual MachineInstr *
00206   convertToThreeAddress(MachineFunction::iterator &MFI,
00207                    MachineBasicBlock::iterator &MBBI, LiveVariables *LV) const {
00208     return 0;
00209   }
00210 
00211   /// commuteInstruction - If a target has any instructions that are
00212   /// commutable but require converting to different instructions or making
00213   /// non-trivial changes to commute them, this method can overloaded to do
00214   /// that.  The default implementation simply swaps the commutable operands.
00215   /// If NewMI is false, MI is modified in place and returned; otherwise, a
00216   /// new machine instruction is created and returned.  Do not call this
00217   /// method for a non-commutable instruction, but there may be some cases
00218   /// where this method fails and returns null.
00219   virtual MachineInstr *commuteInstruction(MachineInstr *MI,
00220                                            bool NewMI = false) const;
00221 
00222   /// findCommutedOpIndices - If specified MI is commutable, return the two
00223   /// operand indices that would swap value. Return false if the instruction
00224   /// is not in a form which this routine understands.
00225   virtual bool findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
00226                                      unsigned &SrcOpIdx2) const;
00227 
00228   /// produceSameValue - Return true if two machine instructions would produce
00229   /// identical values. By default, this is only true when the two instructions
00230   /// are deemed identical except for defs. If this function is called when the
00231   /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
00232   /// aggressive checks.
00233   virtual bool produceSameValue(const MachineInstr *MI0,
00234                                 const MachineInstr *MI1,
00235                                 const MachineRegisterInfo *MRI = 0) const;
00236 
00237   /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
00238   /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
00239   /// implemented for a target).  Upon success, this returns false and returns
00240   /// with the following information in various cases:
00241   ///
00242   /// 1. If this block ends with no branches (it just falls through to its succ)
00243   ///    just return false, leaving TBB/FBB null.
00244   /// 2. If this block ends with only an unconditional branch, it sets TBB to be
00245   ///    the destination block.
00246   /// 3. If this block ends with a conditional branch and it falls through to a
00247   ///    successor block, it sets TBB to be the branch destination block and a
00248   ///    list of operands that evaluate the condition. These operands can be
00249   ///    passed to other TargetInstrInfo methods to create new branches.
00250   /// 4. If this block ends with a conditional branch followed by an
00251   ///    unconditional branch, it returns the 'true' destination in TBB, the
00252   ///    'false' destination in FBB, and a list of operands that evaluate the
00253   ///    condition.  These operands can be passed to other TargetInstrInfo
00254   ///    methods to create new branches.
00255   ///
00256   /// Note that RemoveBranch and InsertBranch must be implemented to support
00257   /// cases where this method returns success.
00258   ///
00259   /// If AllowModify is true, then this routine is allowed to modify the basic
00260   /// block (e.g. delete instructions after the unconditional branch).
00261   ///
00262   virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
00263                              MachineBasicBlock *&FBB,
00264                              SmallVectorImpl<MachineOperand> &Cond,
00265                              bool AllowModify = false) const {
00266     return true;
00267   }
00268 
00269   /// RemoveBranch - Remove the branching code at the end of the specific MBB.
00270   /// This is only invoked in cases where AnalyzeBranch returns success. It
00271   /// returns the number of instructions that were removed.
00272   virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
00273     llvm_unreachable("Target didn't implement TargetInstrInfo::RemoveBranch!");
00274   }
00275 
00276   /// InsertBranch - Insert branch code into the end of the specified
00277   /// MachineBasicBlock.  The operands to this method are the same as those
00278   /// returned by AnalyzeBranch.  This is only invoked in cases where
00279   /// AnalyzeBranch returns success. It returns the number of instructions
00280   /// inserted.
00281   ///
00282   /// It is also invoked by tail merging to add unconditional branches in
00283   /// cases where AnalyzeBranch doesn't apply because there was no original
00284   /// branch to analyze.  At least this much must be implemented, else tail
00285   /// merging needs to be disabled.
00286   virtual unsigned InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
00287                                 MachineBasicBlock *FBB,
00288                                 const SmallVectorImpl<MachineOperand> &Cond,
00289                                 DebugLoc DL) const {
00290     llvm_unreachable("Target didn't implement TargetInstrInfo::InsertBranch!");
00291   }
00292 
00293   /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
00294   /// after it, replacing it with an unconditional branch to NewDest. This is
00295   /// used by the tail merging pass.
00296   virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
00297                                        MachineBasicBlock *NewDest) const;
00298 
00299   /// isLegalToSplitMBBAt - Return true if it's legal to split the given basic
00300   /// block at the specified instruction (i.e. instruction would be the start
00301   /// of a new basic block).
00302   virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
00303                                    MachineBasicBlock::iterator MBBI) const {
00304     return true;
00305   }
00306 
00307   /// isProfitableToIfCvt - Return true if it's profitable to predicate
00308   /// instructions with accumulated instruction latency of "NumCycles"
00309   /// of the specified basic block, where the probability of the instructions
00310   /// being executed is given by Probability, and Confidence is a measure
00311   /// of our confidence that it will be properly predicted.
00312   virtual
00313   bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
00314                            unsigned ExtraPredCycles,
00315                            const BranchProbability &Probability) const {
00316     return false;
00317   }
00318 
00319   /// isProfitableToIfCvt - Second variant of isProfitableToIfCvt, this one
00320   /// checks for the case where two basic blocks from true and false path
00321   /// of a if-then-else (diamond) are predicated on mutally exclusive
00322   /// predicates, where the probability of the true path being taken is given
00323   /// by Probability, and Confidence is a measure of our confidence that it
00324   /// will be properly predicted.
00325   virtual bool
00326   isProfitableToIfCvt(MachineBasicBlock &TMBB,
00327                       unsigned NumTCycles, unsigned ExtraTCycles,
00328                       MachineBasicBlock &FMBB,
00329                       unsigned NumFCycles, unsigned ExtraFCycles,
00330                       const BranchProbability &Probability) const {
00331     return false;
00332   }
00333 
00334   /// isProfitableToDupForIfCvt - Return true if it's profitable for
00335   /// if-converter to duplicate instructions of specified accumulated
00336   /// instruction latencies in the specified MBB to enable if-conversion.
00337   /// The probability of the instructions being executed is given by
00338   /// Probability, and Confidence is a measure of our confidence that it
00339   /// will be properly predicted.
00340   virtual bool
00341   isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
00342                             const BranchProbability &Probability) const {
00343     return false;
00344   }
00345 
00346   /// isProfitableToUnpredicate - Return true if it's profitable to unpredicate
00347   /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
00348   /// exclusive predicates.
00349   /// e.g.
00350   ///   subeq  r0, r1, #1
00351   ///   addne  r0, r1, #1
00352   /// =>
00353   ///   sub    r0, r1, #1
00354   ///   addne  r0, r1, #1
00355   ///
00356   /// This may be profitable is conditional instructions are always executed.
00357   virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
00358                                          MachineBasicBlock &FMBB) const {
00359     return false;
00360   }
00361 
00362   /// canInsertSelect - Return true if it is possible to insert a select
00363   /// instruction that chooses between TrueReg and FalseReg based on the
00364   /// condition code in Cond.
00365   ///
00366   /// When successful, also return the latency in cycles from TrueReg,
00367   /// FalseReg, and Cond to the destination register. In most cases, a select
00368   /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
00369   ///
00370   /// Some x86 implementations have 2-cycle cmov instructions.
00371   ///
00372   /// @param MBB         Block where select instruction would be inserted.
00373   /// @param Cond        Condition returned by AnalyzeBranch.
00374   /// @param TrueReg     Virtual register to select when Cond is true.
00375   /// @param FalseReg    Virtual register to select when Cond is false.
00376   /// @param CondCycles  Latency from Cond+Branch to select output.
00377   /// @param TrueCycles  Latency from TrueReg to select output.
00378   /// @param FalseCycles Latency from FalseReg to select output.
00379   virtual bool canInsertSelect(const MachineBasicBlock &MBB,
00380                                const SmallVectorImpl<MachineOperand> &Cond,
00381                                unsigned TrueReg, unsigned FalseReg,
00382                                int &CondCycles,
00383                                int &TrueCycles, int &FalseCycles) const {
00384     return false;
00385   }
00386 
00387   /// insertSelect - Insert a select instruction into MBB before I that will
00388   /// copy TrueReg to DstReg when Cond is true, and FalseReg to DstReg when
00389   /// Cond is false.
00390   ///
00391   /// This function can only be called after canInsertSelect() returned true.
00392   /// The condition in Cond comes from AnalyzeBranch, and it can be assumed
00393   /// that the same flags or registers required by Cond are available at the
00394   /// insertion point.
00395   ///
00396   /// @param MBB      Block where select instruction should be inserted.
00397   /// @param I        Insertion point.
00398   /// @param DL       Source location for debugging.
00399   /// @param DstReg   Virtual register to be defined by select instruction.
00400   /// @param Cond     Condition as computed by AnalyzeBranch.
00401   /// @param TrueReg  Virtual register to copy when Cond is true.
00402   /// @param FalseReg Virtual register to copy when Cons is false.
00403   virtual void insertSelect(MachineBasicBlock &MBB,
00404                             MachineBasicBlock::iterator I, DebugLoc DL,
00405                             unsigned DstReg,
00406                             const SmallVectorImpl<MachineOperand> &Cond,
00407                             unsigned TrueReg, unsigned FalseReg) const {
00408     llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!");
00409   }
00410 
00411   /// analyzeSelect - Analyze the given select instruction, returning true if
00412   /// it cannot be understood. It is assumed that MI->isSelect() is true.
00413   ///
00414   /// When successful, return the controlling condition and the operands that
00415   /// determine the true and false result values.
00416   ///
00417   ///   Result = SELECT Cond, TrueOp, FalseOp
00418   ///
00419   /// Some targets can optimize select instructions, for example by predicating
00420   /// the instruction defining one of the operands. Such targets should set
00421   /// Optimizable.
00422   ///
00423   /// @param         MI Select instruction to analyze.
00424   /// @param Cond    Condition controlling the select.
00425   /// @param TrueOp  Operand number of the value selected when Cond is true.
00426   /// @param FalseOp Operand number of the value selected when Cond is false.
00427   /// @param Optimizable Returned as true if MI is optimizable.
00428   /// @returns False on success.
00429   virtual bool analyzeSelect(const MachineInstr *MI,
00430                              SmallVectorImpl<MachineOperand> &Cond,
00431                              unsigned &TrueOp, unsigned &FalseOp,
00432                              bool &Optimizable) const {
00433     assert(MI && MI->getDesc().isSelect() && "MI must be a select instruction");
00434     return true;
00435   }
00436 
00437   /// optimizeSelect - Given a select instruction that was understood by
00438   /// analyzeSelect and returned Optimizable = true, attempt to optimize MI by
00439   /// merging it with one of its operands. Returns NULL on failure.
00440   ///
00441   /// When successful, returns the new select instruction. The client is
00442   /// responsible for deleting MI.
00443   ///
00444   /// If both sides of the select can be optimized, PreferFalse is used to pick
00445   /// a side.
00446   ///
00447   /// @param MI          Optimizable select instruction.
00448   /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
00449   /// @returns Optimized instruction or NULL.
00450   virtual MachineInstr *optimizeSelect(MachineInstr *MI,
00451                                        bool PreferFalse = false) const {
00452     // This function must be implemented if Optimizable is ever set.
00453     llvm_unreachable("Target must implement TargetInstrInfo::optimizeSelect!");
00454   }
00455 
00456   /// copyPhysReg - Emit instructions to copy a pair of physical registers.
00457   ///
00458   /// This function should support copies within any legal register class as
00459   /// well as any cross-class copies created during instruction selection.
00460   ///
00461   /// The source and destination registers may overlap, which may require a
00462   /// careful implementation when multiple copy instructions are required for
00463   /// large registers. See for example the ARM target.
00464   virtual void copyPhysReg(MachineBasicBlock &MBB,
00465                            MachineBasicBlock::iterator MI, DebugLoc DL,
00466                            unsigned DestReg, unsigned SrcReg,
00467                            bool KillSrc) const {
00468     llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
00469   }
00470 
00471   /// storeRegToStackSlot - Store the specified register of the given register
00472   /// class to the specified stack frame index. The store instruction is to be
00473   /// added to the given machine basic block before the specified machine
00474   /// instruction. If isKill is true, the register operand is the last use and
00475   /// must be marked kill.
00476   virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
00477                                    MachineBasicBlock::iterator MI,
00478                                    unsigned SrcReg, bool isKill, int FrameIndex,
00479                                    const TargetRegisterClass *RC,
00480                                    const TargetRegisterInfo *TRI) const {
00481     llvm_unreachable("Target didn't implement "
00482                      "TargetInstrInfo::storeRegToStackSlot!");
00483   }
00484 
00485   /// loadRegFromStackSlot - Load the specified register of the given register
00486   /// class from the specified stack frame index. The load instruction is to be
00487   /// added to the given machine basic block before the specified machine
00488   /// instruction.
00489   virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
00490                                     MachineBasicBlock::iterator MI,
00491                                     unsigned DestReg, int FrameIndex,
00492                                     const TargetRegisterClass *RC,
00493                                     const TargetRegisterInfo *TRI) const {
00494     llvm_unreachable("Target didn't implement "
00495                      "TargetInstrInfo::loadRegFromStackSlot!");
00496   }
00497 
00498   /// expandPostRAPseudo - This function is called for all pseudo instructions
00499   /// that remain after register allocation. Many pseudo instructions are
00500   /// created to help register allocation. This is the place to convert them
00501   /// into real instructions. The target can edit MI in place, or it can insert
00502   /// new instructions and erase MI. The function should return true if
00503   /// anything was changed.
00504   virtual bool expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
00505     return false;
00506   }
00507 
00508   /// emitFrameIndexDebugValue - Emit a target-dependent form of
00509   /// DBG_VALUE encoding the address of a frame index.  Addresses would
00510   /// normally be lowered the same way as other addresses on the target,
00511   /// e.g. in load instructions.  For targets that do not support this
00512   /// the debug info is simply lost.
00513   /// If you add this for a target you should handle this DBG_VALUE in the
00514   /// target-specific AsmPrinter code as well; you will probably get invalid
00515   /// assembly output if you don't.
00516   virtual MachineInstr *emitFrameIndexDebugValue(MachineFunction &MF,
00517                                                  int FrameIx,
00518                                                  uint64_t Offset,
00519                                                  const MDNode *MDPtr,
00520                                                  DebugLoc dl) const {
00521     return 0;
00522   }
00523 
00524   /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
00525   /// slot into the specified machine instruction for the specified operand(s).
00526   /// If this is possible, a new instruction is returned with the specified
00527   /// operand folded, otherwise NULL is returned.
00528   /// The new instruction is inserted before MI, and the client is responsible
00529   /// for removing the old instruction.
00530   MachineInstr* foldMemoryOperand(MachineBasicBlock::iterator MI,
00531                                   const SmallVectorImpl<unsigned> &Ops,
00532                                   int FrameIndex) const;
00533 
00534   /// foldMemoryOperand - Same as the previous version except it allows folding
00535   /// of any load and store from / to any address, not just from a specific
00536   /// stack slot.
00537   MachineInstr* foldMemoryOperand(MachineBasicBlock::iterator MI,
00538                                   const SmallVectorImpl<unsigned> &Ops,
00539                                   MachineInstr* LoadMI) const;
00540 
00541 protected:
00542   /// foldMemoryOperandImpl - Target-dependent implementation for
00543   /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
00544   /// take care of adding a MachineMemOperand to the newly created instruction.
00545   virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
00546                                           MachineInstr* MI,
00547                                           const SmallVectorImpl<unsigned> &Ops,
00548                                           int FrameIndex) const {
00549     return 0;
00550   }
00551 
00552   /// foldMemoryOperandImpl - Target-dependent implementation for
00553   /// foldMemoryOperand. Target-independent code in foldMemoryOperand will
00554   /// take care of adding a MachineMemOperand to the newly created instruction.
00555   virtual MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
00556                                               MachineInstr* MI,
00557                                           const SmallVectorImpl<unsigned> &Ops,
00558                                               MachineInstr* LoadMI) const {
00559     return 0;
00560   }
00561 
00562 public:
00563   /// canFoldMemoryOperand - Returns true for the specified load / store if
00564   /// folding is possible.
00565   virtual
00566   bool canFoldMemoryOperand(const MachineInstr *MI,
00567                             const SmallVectorImpl<unsigned> &Ops) const;
00568 
00569   /// unfoldMemoryOperand - Separate a single instruction which folded a load or
00570   /// a store or a load and a store into two or more instruction. If this is
00571   /// possible, returns true as well as the new instructions by reference.
00572   virtual bool unfoldMemoryOperand(MachineFunction &MF, MachineInstr *MI,
00573                                 unsigned Reg, bool UnfoldLoad, bool UnfoldStore,
00574                                  SmallVectorImpl<MachineInstr*> &NewMIs) const{
00575     return false;
00576   }
00577 
00578   virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
00579                                    SmallVectorImpl<SDNode*> &NewNodes) const {
00580     return false;
00581   }
00582 
00583   /// getOpcodeAfterMemoryUnfold - Returns the opcode of the would be new
00584   /// instruction after load / store are unfolded from an instruction of the
00585   /// specified opcode. It returns zero if the specified unfolding is not
00586   /// possible. If LoadRegIndex is non-null, it is filled in with the operand
00587   /// index of the operand which will hold the register holding the loaded
00588   /// value.
00589   virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc,
00590                                       bool UnfoldLoad, bool UnfoldStore,
00591                                       unsigned *LoadRegIndex = 0) const {
00592     return 0;
00593   }
00594 
00595   /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler
00596   /// to determine if two loads are loading from the same base address. It
00597   /// should only return true if the base pointers are the same and the
00598   /// only differences between the two addresses are the offset. It also returns
00599   /// the offsets by reference.
00600   virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
00601                                     int64_t &Offset1, int64_t &Offset2) const {
00602     return false;
00603   }
00604 
00605   /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
00606   /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
00607   /// be scheduled togther. On some targets if two loads are loading from
00608   /// addresses in the same cache line, it's better if they are scheduled
00609   /// together. This function takes two integers that represent the load offsets
00610   /// from the common base address. It returns true if it decides it's desirable
00611   /// to schedule the two loads together. "NumLoads" is the number of loads that
00612   /// have already been scheduled after Load1.
00613   virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
00614                                        int64_t Offset1, int64_t Offset2,
00615                                        unsigned NumLoads) const {
00616     return false;
00617   }
00618 
00619   /// \brief Get the base register and byte offset of a load/store instr.
00620   virtual bool getLdStBaseRegImmOfs(MachineInstr *LdSt,
00621                                     unsigned &BaseReg, unsigned &Offset,
00622                                     const TargetRegisterInfo *TRI) const {
00623     return false;
00624   }
00625 
00626   virtual bool shouldClusterLoads(MachineInstr *FirstLdSt,
00627                                   MachineInstr *SecondLdSt,
00628                                   unsigned NumLoads) const {
00629     return false;
00630   }
00631 
00632   /// \brief Can this target fuse the given instructions if they are scheduled
00633   /// adjacent.
00634   virtual bool shouldScheduleAdjacent(MachineInstr* First,
00635                                       MachineInstr *Second) const {
00636     return false;
00637   }
00638 
00639   /// ReverseBranchCondition - Reverses the branch condition of the specified
00640   /// condition list, returning false on success and true if it cannot be
00641   /// reversed.
00642   virtual
00643   bool ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
00644     return true;
00645   }
00646 
00647   /// insertNoop - Insert a noop into the instruction stream at the specified
00648   /// point.
00649   virtual void insertNoop(MachineBasicBlock &MBB,
00650                           MachineBasicBlock::iterator MI) const;
00651 
00652 
00653   /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
00654   virtual void getNoopForMachoTarget(MCInst &NopInst) const {
00655     // Default to just using 'nop' string.
00656   }
00657 
00658 
00659   /// isPredicated - Returns true if the instruction is already predicated.
00660   ///
00661   virtual bool isPredicated(const MachineInstr *MI) const {
00662     return false;
00663   }
00664 
00665   /// isUnpredicatedTerminator - Returns true if the instruction is a
00666   /// terminator instruction that has not been predicated.
00667   virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
00668 
00669   /// PredicateInstruction - Convert the instruction into a predicated
00670   /// instruction. It returns true if the operation was successful.
00671   virtual
00672   bool PredicateInstruction(MachineInstr *MI,
00673                         const SmallVectorImpl<MachineOperand> &Pred) const;
00674 
00675   /// SubsumesPredicate - Returns true if the first specified predicate
00676   /// subsumes the second, e.g. GE subsumes GT.
00677   virtual
00678   bool SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
00679                          const SmallVectorImpl<MachineOperand> &Pred2) const {
00680     return false;
00681   }
00682 
00683   /// DefinesPredicate - If the specified instruction defines any predicate
00684   /// or condition code register(s) used for predication, returns true as well
00685   /// as the definition predicate(s) by reference.
00686   virtual bool DefinesPredicate(MachineInstr *MI,
00687                                 std::vector<MachineOperand> &Pred) const {
00688     return false;
00689   }
00690 
00691   /// isPredicable - Return true if the specified instruction can be predicated.
00692   /// By default, this returns true for every instruction with a
00693   /// PredicateOperand.
00694   virtual bool isPredicable(MachineInstr *MI) const {
00695     return MI->getDesc().isPredicable();
00696   }
00697 
00698   /// isSafeToMoveRegClassDefs - Return true if it's safe to move a machine
00699   /// instruction that defines the specified register class.
00700   virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
00701     return true;
00702   }
00703 
00704   /// isSchedulingBoundary - Test if the given instruction should be
00705   /// considered a scheduling boundary. This primarily includes labels and
00706   /// terminators.
00707   virtual bool isSchedulingBoundary(const MachineInstr *MI,
00708                                     const MachineBasicBlock *MBB,
00709                                     const MachineFunction &MF) const;
00710 
00711   /// Measure the specified inline asm to determine an approximation of its
00712   /// length.
00713   virtual unsigned getInlineAsmLength(const char *Str,
00714                                       const MCAsmInfo &MAI) const;
00715 
00716   /// CreateTargetHazardRecognizer - Allocate and return a hazard recognizer to
00717   /// use for this target when scheduling the machine instructions before
00718   /// register allocation.
00719   virtual ScheduleHazardRecognizer*
00720   CreateTargetHazardRecognizer(const TargetMachine *TM,
00721                                const ScheduleDAG *DAG) const;
00722 
00723   /// CreateTargetMIHazardRecognizer - Allocate and return a hazard recognizer
00724   /// to use for this target when scheduling the machine instructions before
00725   /// register allocation.
00726   virtual ScheduleHazardRecognizer*
00727   CreateTargetMIHazardRecognizer(const InstrItineraryData*,
00728                                  const ScheduleDAG *DAG) const;
00729 
00730   /// CreateTargetPostRAHazardRecognizer - Allocate and return a hazard
00731   /// recognizer to use for this target when scheduling the machine instructions
00732   /// after register allocation.
00733   virtual ScheduleHazardRecognizer*
00734   CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
00735                                      const ScheduleDAG *DAG) const;
00736 
00737   /// Provide a global flag for disabling the PreRA hazard recognizer that
00738   /// targets may choose to honor.
00739   bool usePreRAHazardRecognizer() const;
00740 
00741   /// analyzeCompare - For a comparison instruction, return the source registers
00742   /// in SrcReg and SrcReg2 if having two register operands, and the value it
00743   /// compares against in CmpValue. Return true if the comparison instruction
00744   /// can be analyzed.
00745   virtual bool analyzeCompare(const MachineInstr *MI,
00746                               unsigned &SrcReg, unsigned &SrcReg2,
00747                               int &Mask, int &Value) const {
00748     return false;
00749   }
00750 
00751   /// optimizeCompareInstr - See if the comparison instruction can be converted
00752   /// into something more efficient. E.g., on ARM most instructions can set the
00753   /// flags register, obviating the need for a separate CMP.
00754   virtual bool optimizeCompareInstr(MachineInstr *CmpInstr,
00755                                     unsigned SrcReg, unsigned SrcReg2,
00756                                     int Mask, int Value,
00757                                     const MachineRegisterInfo *MRI) const {
00758     return false;
00759   }
00760 
00761   /// optimizeLoadInstr - Try to remove the load by folding it to a register
00762   /// operand at the use. We fold the load instructions if and only if the
00763   /// def and use are in the same BB. We only look at one load and see
00764   /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
00765   /// defined by the load we are trying to fold. DefMI returns the machine
00766   /// instruction that defines FoldAsLoadDefReg, and the function returns
00767   /// the machine instruction generated due to folding.
00768   virtual MachineInstr* optimizeLoadInstr(MachineInstr *MI,
00769                         const MachineRegisterInfo *MRI,
00770                         unsigned &FoldAsLoadDefReg,
00771                         MachineInstr *&DefMI) const {
00772     return 0;
00773   }
00774 
00775   /// FoldImmediate - 'Reg' is known to be defined by a move immediate
00776   /// instruction, try to fold the immediate into the use instruction.
00777   /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
00778   /// then the caller may assume that DefMI has been erased from its parent
00779   /// block. The caller may assume that it will not be erased by this
00780   /// function otherwise.
00781   virtual bool FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
00782                              unsigned Reg, MachineRegisterInfo *MRI) const {
00783     return false;
00784   }
00785 
00786   /// getNumMicroOps - Return the number of u-operations the given machine
00787   /// instruction will be decoded to on the target cpu. The itinerary's
00788   /// IssueWidth is the number of microops that can be dispatched each
00789   /// cycle. An instruction with zero microops takes no dispatch resources.
00790   virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
00791                                   const MachineInstr *MI) const;
00792 
00793   /// isZeroCost - Return true for pseudo instructions that don't consume any
00794   /// machine resources in their current form. These are common cases that the
00795   /// scheduler should consider free, rather than conservatively handling them
00796   /// as instructions with no itinerary.
00797   bool isZeroCost(unsigned Opcode) const {
00798     return Opcode <= TargetOpcode::COPY;
00799   }
00800 
00801   virtual int getOperandLatency(const InstrItineraryData *ItinData,
00802                                 SDNode *DefNode, unsigned DefIdx,
00803                                 SDNode *UseNode, unsigned UseIdx) const;
00804 
00805   /// getOperandLatency - Compute and return the use operand latency of a given
00806   /// pair of def and use.
00807   /// In most cases, the static scheduling itinerary was enough to determine the
00808   /// operand latency. But it may not be possible for instructions with variable
00809   /// number of defs / uses.
00810   ///
00811   /// This is a raw interface to the itinerary that may be directly overriden by
00812   /// a target. Use computeOperandLatency to get the best estimate of latency.
00813   virtual int getOperandLatency(const InstrItineraryData *ItinData,
00814                                 const MachineInstr *DefMI, unsigned DefIdx,
00815                                 const MachineInstr *UseMI,
00816                                 unsigned UseIdx) const;
00817 
00818   /// computeOperandLatency - Compute and return the latency of the given data
00819   /// dependent def and use when the operand indices are already known.
00820   ///
00821   /// FindMin may be set to get the minimum vs. expected latency.
00822   unsigned computeOperandLatency(const InstrItineraryData *ItinData,
00823                                  const MachineInstr *DefMI, unsigned DefIdx,
00824                                  const MachineInstr *UseMI, unsigned UseIdx,
00825                                  bool FindMin = false) const;
00826 
00827   /// getInstrLatency - Compute the instruction latency of a given instruction.
00828   /// If the instruction has higher cost when predicated, it's returned via
00829   /// PredCost.
00830   virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
00831                                    const MachineInstr *MI,
00832                                    unsigned *PredCost = 0) const;
00833 
00834   virtual int getInstrLatency(const InstrItineraryData *ItinData,
00835                               SDNode *Node) const;
00836 
00837   /// Return the default expected latency for a def based on it's opcode.
00838   unsigned defaultDefLatency(const MCSchedModel *SchedModel,
00839                              const MachineInstr *DefMI) const;
00840 
00841   int computeDefOperandLatency(const InstrItineraryData *ItinData,
00842                                const MachineInstr *DefMI, bool FindMin) const;
00843 
00844   /// isHighLatencyDef - Return true if this opcode has high latency to its
00845   /// result.
00846   virtual bool isHighLatencyDef(int opc) const { return false; }
00847 
00848   /// hasHighOperandLatency - Compute operand latency between a def of 'Reg'
00849   /// and an use in the current loop, return true if the target considered
00850   /// it 'high'. This is used by optimization passes such as machine LICM to
00851   /// determine whether it makes sense to hoist an instruction out even in
00852   /// high register pressure situation.
00853   virtual
00854   bool hasHighOperandLatency(const InstrItineraryData *ItinData,
00855                              const MachineRegisterInfo *MRI,
00856                              const MachineInstr *DefMI, unsigned DefIdx,
00857                              const MachineInstr *UseMI, unsigned UseIdx) const {
00858     return false;
00859   }
00860 
00861   /// hasLowDefLatency - Compute operand latency of a def of 'Reg', return true
00862   /// if the target considered it 'low'.
00863   virtual
00864   bool hasLowDefLatency(const InstrItineraryData *ItinData,
00865                         const MachineInstr *DefMI, unsigned DefIdx) const;
00866 
00867   /// verifyInstruction - Perform target specific instruction verification.
00868   virtual
00869   bool verifyInstruction(const MachineInstr *MI, StringRef &ErrInfo) const {
00870     return true;
00871   }
00872 
00873   /// getExecutionDomain - Return the current execution domain and bit mask of
00874   /// possible domains for instruction.
00875   ///
00876   /// Some micro-architectures have multiple execution domains, and multiple
00877   /// opcodes that perform the same operation in different domains.  For
00878   /// example, the x86 architecture provides the por, orps, and orpd
00879   /// instructions that all do the same thing.  There is a latency penalty if a
00880   /// register is written in one domain and read in another.
00881   ///
00882   /// This function returns a pair (domain, mask) containing the execution
00883   /// domain of MI, and a bit mask of possible domains.  The setExecutionDomain
00884   /// function can be used to change the opcode to one of the domains in the
00885   /// bit mask.  Instructions whose execution domain can't be changed should
00886   /// return a 0 mask.
00887   ///
00888   /// The execution domain numbers don't have any special meaning except domain
00889   /// 0 is used for instructions that are not associated with any interesting
00890   /// execution domain.
00891   ///
00892   virtual std::pair<uint16_t, uint16_t>
00893   getExecutionDomain(const MachineInstr *MI) const {
00894     return std::make_pair(0, 0);
00895   }
00896 
00897   /// setExecutionDomain - Change the opcode of MI to execute in Domain.
00898   ///
00899   /// The bit (1 << Domain) must be set in the mask returned from
00900   /// getExecutionDomain(MI).
00901   ///
00902   virtual void setExecutionDomain(MachineInstr *MI, unsigned Domain) const {}
00903 
00904 
00905   /// getPartialRegUpdateClearance - Returns the preferred minimum clearance
00906   /// before an instruction with an unwanted partial register update.
00907   ///
00908   /// Some instructions only write part of a register, and implicitly need to
00909   /// read the other parts of the register.  This may cause unwanted stalls
00910   /// preventing otherwise unrelated instructions from executing in parallel in
00911   /// an out-of-order CPU.
00912   ///
00913   /// For example, the x86 instruction cvtsi2ss writes its result to bits
00914   /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
00915   /// the instruction needs to wait for the old value of the register to become
00916   /// available:
00917   ///
00918   ///   addps %xmm1, %xmm0
00919   ///   movaps %xmm0, (%rax)
00920   ///   cvtsi2ss %rbx, %xmm0
00921   ///
00922   /// In the code above, the cvtsi2ss instruction needs to wait for the addps
00923   /// instruction before it can issue, even though the high bits of %xmm0
00924   /// probably aren't needed.
00925   ///
00926   /// This hook returns the preferred clearance before MI, measured in
00927   /// instructions.  Other defs of MI's operand OpNum are avoided in the last N
00928   /// instructions before MI.  It should only return a positive value for
00929   /// unwanted dependencies.  If the old bits of the defined register have
00930   /// useful values, or if MI is determined to otherwise read the dependency,
00931   /// the hook should return 0.
00932   ///
00933   /// The unwanted dependency may be handled by:
00934   ///
00935   /// 1. Allocating the same register for an MI def and use.  That makes the
00936   ///    unwanted dependency identical to a required dependency.
00937   ///
00938   /// 2. Allocating a register for the def that has no defs in the previous N
00939   ///    instructions.
00940   ///
00941   /// 3. Calling breakPartialRegDependency() with the same arguments.  This
00942   ///    allows the target to insert a dependency breaking instruction.
00943   ///
00944   virtual unsigned
00945   getPartialRegUpdateClearance(const MachineInstr *MI, unsigned OpNum,
00946                                const TargetRegisterInfo *TRI) const {
00947     // The default implementation returns 0 for no partial register dependency.
00948     return 0;
00949   }
00950 
00951   /// breakPartialRegDependency - Insert a dependency-breaking instruction
00952   /// before MI to eliminate an unwanted dependency on OpNum.
00953   ///
00954   /// If it wasn't possible to avoid a def in the last N instructions before MI
00955   /// (see getPartialRegUpdateClearance), this hook will be called to break the
00956   /// unwanted dependency.
00957   ///
00958   /// On x86, an xorps instruction can be used as a dependency breaker:
00959   ///
00960   ///   addps %xmm1, %xmm0
00961   ///   movaps %xmm0, (%rax)
00962   ///   xorps %xmm0, %xmm0
00963   ///   cvtsi2ss %rbx, %xmm0
00964   ///
00965   /// An <imp-kill> operand should be added to MI if an instruction was
00966   /// inserted.  This ties the instructions together in the post-ra scheduler.
00967   ///
00968   virtual void
00969   breakPartialRegDependency(MachineBasicBlock::iterator MI, unsigned OpNum,
00970                             const TargetRegisterInfo *TRI) const {}
00971 
00972   /// Create machine specific model for scheduling.
00973   virtual DFAPacketizer*
00974     CreateTargetScheduleState(const TargetMachine*, const ScheduleDAG*) const {
00975     return NULL;
00976   }
00977 
00978 private:
00979   int CallFrameSetupOpcode, CallFrameDestroyOpcode;
00980 };
00981 
00982 } // End llvm namespace
00983 
00984 #endif