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