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