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