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