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/DenseMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/CodeGen/MachineCombinerPattern.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/Support/BranchProbability.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 class InstrItineraryData;
32 class MachineMemOperand;
33 class MachineRegisterInfo;
37 class MCSymbolRefExpr;
39 class ScheduleHazardRecognizer;
42 class TargetRegisterClass;
43 class TargetRegisterInfo;
44 class TargetSubtargetInfo;
45 class TargetSchedModel;
48 template<class T> class SmallVectorImpl;
50 //---------------------------------------------------------------------------
52 /// TargetInstrInfo - Interface to description of machine instruction set
54 class TargetInstrInfo : public MCInstrInfo {
55 TargetInstrInfo(const TargetInstrInfo &) = delete;
56 void operator=(const TargetInstrInfo &) = delete;
58 TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
59 unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u)
60 : CallFrameSetupOpcode(CFSetupOpcode),
61 CallFrameDestroyOpcode(CFDestroyOpcode),
62 CatchRetOpcode(CatchRetOpcode),
63 ReturnOpcode(ReturnOpcode) {}
65 virtual ~TargetInstrInfo();
67 static bool isGenericOpcode(unsigned Opc) {
68 return Opc <= TargetOpcode::GENERIC_OP_END;
71 /// Given a machine instruction descriptor, returns the register
72 /// class constraint for OpNum, or NULL.
73 const TargetRegisterClass *getRegClass(const MCInstrDesc &TID,
75 const TargetRegisterInfo *TRI,
76 const MachineFunction &MF) const;
78 /// Return true if the instruction is trivially rematerializable, meaning it
79 /// has no side effects and requires no operands that aren't always available.
80 /// This means the only allowed uses are constants and unallocatable physical
81 /// registers so that the instructions result is independent of the place
83 bool isTriviallyReMaterializable(const MachineInstr &MI,
84 AliasAnalysis *AA = nullptr) const {
85 return MI.getOpcode() == TargetOpcode::IMPLICIT_DEF ||
86 (MI.getDesc().isRematerializable() &&
87 (isReallyTriviallyReMaterializable(MI, AA) ||
88 isReallyTriviallyReMaterializableGeneric(MI, AA)));
92 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
93 /// set, this hook lets the target specify whether the instruction is actually
94 /// trivially rematerializable, taking into consideration its operands. This
95 /// predicate must return false if the instruction has any side effects other
96 /// than producing a value, or if it requres any address registers that are
97 /// not always available.
98 /// Requirements must be check as stated in isTriviallyReMaterializable() .
99 virtual bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
100 AliasAnalysis *AA) const {
104 /// This method commutes the operands of the given machine instruction MI.
105 /// The operands to be commuted are specified by their indices OpIdx1 and
108 /// If a target has any instructions that are commutable but require
109 /// converting to different instructions or making non-trivial changes
110 /// to commute them, this method can be overloaded to do that.
111 /// The default implementation simply swaps the commutable operands.
113 /// If NewMI is false, MI is modified in place and returned; otherwise, a
114 /// new machine instruction is created and returned.
116 /// Do not call this method for a non-commutable instruction.
117 /// Even though the instruction is commutable, the method may still
118 /// fail to commute the operands, null pointer is returned in such cases.
119 virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
121 unsigned OpIdx2) const;
123 /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
124 /// operand indices to (ResultIdx1, ResultIdx2).
125 /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
126 /// predefined to some indices or be undefined (designated by the special
127 /// value 'CommuteAnyOperandIndex').
128 /// The predefined result indices cannot be re-defined.
129 /// The function returns true iff after the result pair redefinition
130 /// the fixed result pair is equal to or equivalent to the source pair of
131 /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
132 /// the pairs (x,y) and (y,x) are equivalent.
133 static bool fixCommutedOpIndices(unsigned &ResultIdx1,
134 unsigned &ResultIdx2,
135 unsigned CommutableOpIdx1,
136 unsigned CommutableOpIdx2);
139 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
140 /// set and the target hook isReallyTriviallyReMaterializable returns false,
141 /// this function does target-independent tests to determine if the
142 /// instruction is really trivially rematerializable.
143 bool isReallyTriviallyReMaterializableGeneric(const MachineInstr &MI,
144 AliasAnalysis *AA) const;
147 /// These methods return the opcode of the frame setup/destroy instructions
148 /// if they exist (-1 otherwise). Some targets use pseudo instructions in
149 /// order to abstract away the difference between operating with a frame
150 /// pointer and operating without, through the use of these two instructions.
152 unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
153 unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
155 unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
156 unsigned getReturnOpcode() const { return ReturnOpcode; }
158 /// Returns the actual stack pointer adjustment made by an instruction
159 /// as part of a call sequence. By default, only call frame setup/destroy
160 /// instructions adjust the stack, but targets may want to override this
161 /// to enable more fine-grained adjustment, or adjust by a different value.
162 virtual int getSPAdjust(const MachineInstr &MI) const;
164 /// Return true if the instruction is a "coalescable" extension instruction.
165 /// That is, it's like a copy where it's legal for the source to overlap the
166 /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
167 /// expected the pre-extension value is available as a subreg of the result
168 /// register. This also returns the sub-register index in SubIdx.
169 virtual bool isCoalescableExtInstr(const MachineInstr &MI,
170 unsigned &SrcReg, unsigned &DstReg,
171 unsigned &SubIdx) const {
175 /// If the specified machine instruction is a direct
176 /// load from a stack slot, return the virtual or physical register number of
177 /// the destination along with the FrameIndex of the loaded stack slot. If
178 /// not, return 0. This predicate must return 0 if the instruction has
179 /// any side effects other than loading from the stack slot.
180 virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
181 int &FrameIndex) const {
185 /// Check for post-frame ptr elimination stack locations as well.
186 /// This uses a heuristic so it isn't reliable for correctness.
187 virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
188 int &FrameIndex) const {
192 /// If the specified machine instruction has a load from a stack slot,
193 /// return true along with the FrameIndex of the loaded stack slot and the
194 /// machine mem operand containing the reference.
195 /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
196 /// any instructions that loads from the stack. This is just a hint, as some
197 /// cases may be missed.
198 virtual bool hasLoadFromStackSlot(const MachineInstr &MI,
199 const MachineMemOperand *&MMO,
200 int &FrameIndex) const;
202 /// If the specified machine instruction is a direct
203 /// store to a stack slot, return the virtual or physical register number of
204 /// the source reg along with the FrameIndex of the loaded stack slot. If
205 /// not, return 0. This predicate must return 0 if the instruction has
206 /// any side effects other than storing to the stack slot.
207 virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
208 int &FrameIndex) const {
212 /// Check for post-frame ptr elimination stack locations as well.
213 /// This uses a heuristic, so it isn't reliable for correctness.
214 virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
215 int &FrameIndex) const {
219 /// If the specified machine instruction has a store to a stack slot,
220 /// return true along with the FrameIndex of the loaded stack slot and the
221 /// machine mem operand containing the reference.
222 /// If not, return false. Unlike isStoreToStackSlot,
223 /// this returns true for any instructions that stores to the
224 /// stack. This is just a hint, as some cases may be missed.
225 virtual bool hasStoreToStackSlot(const MachineInstr &MI,
226 const MachineMemOperand *&MMO,
227 int &FrameIndex) const;
229 /// Return true if the specified machine instruction
230 /// is a copy of one stack slot to another and has no other effect.
231 /// Provide the identity of the two frame indices.
232 virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
233 int &SrcFrameIndex) const {
237 /// Compute the size in bytes and offset within a stack slot of a spilled
238 /// register or subregister.
240 /// \param [out] Size in bytes of the spilled value.
241 /// \param [out] Offset in bytes within the stack slot.
242 /// \returns true if both Size and Offset are successfully computed.
244 /// Not all subregisters have computable spill slots. For example,
245 /// subregisters registers may not be byte-sized, and a pair of discontiguous
246 /// subregisters has no single offset.
248 /// Targets with nontrivial bigendian implementations may need to override
249 /// this, particularly to support spilled vector registers.
250 virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
251 unsigned &Size, unsigned &Offset,
252 const MachineFunction &MF) const;
254 /// Returns the size in bytes of the specified MachineInstr, or ~0U
255 /// when this function is not implemented by a target.
256 virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
260 /// Return true if the instruction is as cheap as a move instruction.
262 /// Targets for different archs need to override this, and different
263 /// micro-architectures can also be finely tuned inside.
264 virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
265 return MI.isAsCheapAsAMove();
268 /// Return true if the instruction should be sunk by MachineSink.
270 /// MachineSink determines on its own whether the instruction is safe to sink;
271 /// this gives the target a hook to override the default behavior with regards
272 /// to which instructions should be sunk.
273 virtual bool shouldSink(const MachineInstr &MI) const {
277 /// Re-issue the specified 'original' instruction at the
278 /// specific location targeting a new destination register.
279 /// The register in Orig->getOperand(0).getReg() will be substituted by
280 /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
282 virtual void reMaterialize(MachineBasicBlock &MBB,
283 MachineBasicBlock::iterator MI, unsigned DestReg,
284 unsigned SubIdx, const MachineInstr &Orig,
285 const TargetRegisterInfo &TRI) const;
287 /// Create a duplicate of the Orig instruction in MF. This is like
288 /// MachineFunction::CloneMachineInstr(), but the target may update operands
289 /// that are required to be unique.
291 /// The instruction must be duplicable as indicated by isNotDuplicable().
292 virtual MachineInstr *duplicate(MachineInstr &Orig,
293 MachineFunction &MF) const;
295 /// This method must be implemented by targets that
296 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
297 /// may be able to convert a two-address instruction into one or more true
298 /// three-address instructions on demand. This allows the X86 target (for
299 /// example) to convert ADD and SHL instructions into LEA instructions if they
300 /// would require register copies due to two-addressness.
302 /// This method returns a null pointer if the transformation cannot be
303 /// performed, otherwise it returns the last new instruction.
305 virtual MachineInstr *convertToThreeAddress(MachineFunction::iterator &MFI,
307 LiveVariables *LV) const {
311 // This constant can be used as an input value of operand index passed to
312 // the method findCommutedOpIndices() to tell the method that the
313 // corresponding operand index is not pre-defined and that the method
314 // can pick any commutable operand.
315 static const unsigned CommuteAnyOperandIndex = ~0U;
317 /// This method commutes the operands of the given machine instruction MI.
319 /// The operands to be commuted are specified by their indices OpIdx1 and
320 /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
321 /// 'CommuteAnyOperandIndex', which means that the method is free to choose
322 /// any arbitrarily chosen commutable operand. If both arguments are set to
323 /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
324 /// operands; then commutes them if such operands could be found.
326 /// If NewMI is false, MI is modified in place and returned; otherwise, a
327 /// new machine instruction is created and returned.
329 /// Do not call this method for a non-commutable instruction or
330 /// for non-commuable operands.
331 /// Even though the instruction is commutable, the method may still
332 /// fail to commute the operands, null pointer is returned in such cases.
334 commuteInstruction(MachineInstr &MI, bool NewMI = false,
335 unsigned OpIdx1 = CommuteAnyOperandIndex,
336 unsigned OpIdx2 = CommuteAnyOperandIndex) const;
338 /// Returns true iff the routine could find two commutable operands in the
339 /// given machine instruction.
340 /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
341 /// If any of the INPUT values is set to the special value
342 /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
343 /// operand, then returns its index in the corresponding argument.
344 /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
345 /// looks for 2 commutable operands.
346 /// If INPUT values refer to some operands of MI, then the method simply
347 /// returns true if the corresponding operands are commutable and returns
350 /// For example, calling this method this way:
351 /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
352 /// findCommutedOpIndices(MI, Op1, Op2);
353 /// can be interpreted as a query asking to find an operand that would be
354 /// commutable with the operand#1.
355 virtual bool findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx1,
356 unsigned &SrcOpIdx2) const;
358 /// A pair composed of a register and a sub-register index.
359 /// Used to give some type checking when modeling Reg:SubReg.
360 struct RegSubRegPair {
363 RegSubRegPair(unsigned Reg = 0, unsigned SubReg = 0)
364 : Reg(Reg), SubReg(SubReg) {}
366 /// A pair composed of a pair of a register and a sub-register index,
367 /// and another sub-register index.
368 /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
369 struct RegSubRegPairAndIdx : RegSubRegPair {
371 RegSubRegPairAndIdx(unsigned Reg = 0, unsigned SubReg = 0,
373 : RegSubRegPair(Reg, SubReg), SubIdx(SubIdx) {}
376 /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
378 /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
379 /// the list is modeled as <Reg:SubReg, SubIdx>.
380 /// E.g., REG_SEQUENCE vreg1:sub1, sub0, vreg2, sub1 would produce
382 /// - vreg1:sub1, sub0
383 /// - vreg2<:0>, sub1
385 /// \returns true if it is possible to build such an input sequence
386 /// with the pair \p MI, \p DefIdx. False otherwise.
388 /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
390 /// \note The generic implementation does not provide any support for
391 /// MI.isRegSequenceLike(). In other words, one has to override
392 /// getRegSequenceLikeInputs for target specific instructions.
394 getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
395 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
397 /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
399 /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
400 /// E.g., EXTRACT_SUBREG vreg1:sub1, sub0, sub1 would produce:
401 /// - vreg1:sub1, sub0
403 /// \returns true if it is possible to build such an input sequence
404 /// with the pair \p MI, \p DefIdx. False otherwise.
406 /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
408 /// \note The generic implementation does not provide any support for
409 /// MI.isExtractSubregLike(). In other words, one has to override
410 /// getExtractSubregLikeInputs for target specific instructions.
412 getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
413 RegSubRegPairAndIdx &InputReg) const;
415 /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
417 /// \p [out] BaseReg and \p [out] InsertedReg contain
418 /// the equivalent inputs of INSERT_SUBREG.
419 /// E.g., INSERT_SUBREG vreg0:sub0, vreg1:sub1, sub3 would produce:
420 /// - BaseReg: vreg0:sub0
421 /// - InsertedReg: vreg1:sub1, sub3
423 /// \returns true if it is possible to build such an input sequence
424 /// with the pair \p MI, \p DefIdx. False otherwise.
426 /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
428 /// \note The generic implementation does not provide any support for
429 /// MI.isInsertSubregLike(). In other words, one has to override
430 /// getInsertSubregLikeInputs for target specific instructions.
432 getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
433 RegSubRegPair &BaseReg,
434 RegSubRegPairAndIdx &InsertedReg) const;
437 /// Return true if two machine instructions would produce identical values.
438 /// By default, this is only true when the two instructions
439 /// are deemed identical except for defs. If this function is called when the
440 /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
441 /// aggressive checks.
442 virtual bool produceSameValue(const MachineInstr &MI0,
443 const MachineInstr &MI1,
444 const MachineRegisterInfo *MRI = nullptr) const;
446 /// \returns true if a branch from an instruction with opcode \p BranchOpc
447 /// bytes is capable of jumping to a position \p BrOffset bytes away.
448 virtual bool isBranchOffsetInRange(unsigned BranchOpc,
449 int64_t BrOffset) const {
450 llvm_unreachable("target did not implement");
453 /// \returns The block that branch instruction \p MI jumps to.
454 virtual MachineBasicBlock *getBranchDestBlock(const MachineInstr &MI) const {
455 llvm_unreachable("target did not implement");
458 /// Insert an unconditional indirect branch at the end of \p MBB to \p
459 /// NewDestBB. \p BrOffset indicates the offset of \p NewDestBB relative to
460 /// the offset of the position to insert the new branch.
462 /// \returns The number of bytes added to the block.
463 virtual unsigned insertIndirectBranch(MachineBasicBlock &MBB,
464 MachineBasicBlock &NewDestBB,
466 int64_t BrOffset = 0,
467 RegScavenger *RS = nullptr) const {
468 llvm_unreachable("target did not implement");
471 /// Analyze the branching code at the end of MBB, returning
472 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
473 /// implemented for a target). Upon success, this returns false and returns
474 /// with the following information in various cases:
476 /// 1. If this block ends with no branches (it just falls through to its succ)
477 /// just return false, leaving TBB/FBB null.
478 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
479 /// the destination block.
480 /// 3. If this block ends with a conditional branch and it falls through to a
481 /// successor block, it sets TBB to be the branch destination block and a
482 /// list of operands that evaluate the condition. These operands can be
483 /// passed to other TargetInstrInfo methods to create new branches.
484 /// 4. If this block ends with a conditional branch followed by an
485 /// unconditional branch, it returns the 'true' destination in TBB, the
486 /// 'false' destination in FBB, and a list of operands that evaluate the
487 /// condition. These operands can be passed to other TargetInstrInfo
488 /// methods to create new branches.
490 /// Note that removeBranch and insertBranch must be implemented to support
491 /// cases where this method returns success.
493 /// If AllowModify is true, then this routine is allowed to modify the basic
494 /// block (e.g. delete instructions after the unconditional branch).
496 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
497 /// before calling this function.
498 virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
499 MachineBasicBlock *&FBB,
500 SmallVectorImpl<MachineOperand> &Cond,
501 bool AllowModify = false) const {
505 /// Represents a predicate at the MachineFunction level. The control flow a
506 /// MachineBranchPredicate represents is:
508 /// Reg <def>= LHS `Predicate` RHS == ConditionDef
509 /// if Reg then goto TrueDest else goto FalseDest
511 struct MachineBranchPredicate {
512 enum ComparePredicate {
513 PRED_EQ, // True if two values are equal
514 PRED_NE, // True if two values are not equal
515 PRED_INVALID // Sentinel value
518 ComparePredicate Predicate;
521 MachineBasicBlock *TrueDest;
522 MachineBasicBlock *FalseDest;
523 MachineInstr *ConditionDef;
525 /// SingleUseCondition is true if ConditionDef is dead except for the
526 /// branch(es) at the end of the basic block.
528 bool SingleUseCondition;
530 explicit MachineBranchPredicate()
531 : Predicate(PRED_INVALID), LHS(MachineOperand::CreateImm(0)),
532 RHS(MachineOperand::CreateImm(0)), TrueDest(nullptr),
533 FalseDest(nullptr), ConditionDef(nullptr), SingleUseCondition(false) {
537 /// Analyze the branching code at the end of MBB and parse it into the
538 /// MachineBranchPredicate structure if possible. Returns false on success
539 /// and true on failure.
541 /// If AllowModify is true, then this routine is allowed to modify the basic
542 /// block (e.g. delete instructions after the unconditional branch).
544 virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB,
545 MachineBranchPredicate &MBP,
546 bool AllowModify = false) const {
550 /// Remove the branching code at the end of the specific MBB.
551 /// This is only invoked in cases where AnalyzeBranch returns success. It
552 /// returns the number of instructions that were removed.
553 /// If \p BytesRemoved is non-null, report the change in code size from the
554 /// removed instructions.
555 virtual unsigned removeBranch(MachineBasicBlock &MBB,
556 int *BytesRemoved = nullptr) const {
557 llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!");
560 /// Insert branch code into the end of the specified MachineBasicBlock. The
561 /// operands to this method are the same as those returned by AnalyzeBranch.
562 /// This is only invoked in cases where AnalyzeBranch returns success. It
563 /// returns the number of instructions inserted. If \p BytesAdded is non-null,
564 /// report the change in code size from the added instructions.
566 /// It is also invoked by tail merging to add unconditional branches in
567 /// cases where AnalyzeBranch doesn't apply because there was no original
568 /// branch to analyze. At least this much must be implemented, else tail
569 /// merging needs to be disabled.
571 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
572 /// before calling this function.
573 virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
574 MachineBasicBlock *FBB,
575 ArrayRef<MachineOperand> Cond,
577 int *BytesAdded = nullptr) const {
578 llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!");
581 unsigned insertUnconditionalBranch(MachineBasicBlock &MBB,
582 MachineBasicBlock *DestBB,
584 int *BytesAdded = nullptr) const {
585 return insertBranch(MBB, DestBB, nullptr,
586 ArrayRef<MachineOperand>(), DL, BytesAdded);
589 /// Analyze the loop code, return true if it cannot be understoo. Upon
590 /// success, this function returns false and returns information about the
591 /// induction variable and compare instruction used at the end.
592 virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
593 MachineInstr *&CmpInst) const {
597 /// Generate code to reduce the loop iteration by one and check if the loop is
598 /// finished. Return the value/register of the the new loop count. We need
599 /// this function when peeling off one or more iterations of a loop. This
600 /// function assumes the nth iteration is peeled first.
601 virtual unsigned reduceLoopCount(MachineBasicBlock &MBB,
602 MachineInstr *IndVar, MachineInstr &Cmp,
603 SmallVectorImpl<MachineOperand> &Cond,
604 SmallVectorImpl<MachineInstr *> &PrevInsts,
605 unsigned Iter, unsigned MaxIter) const {
606 llvm_unreachable("Target didn't implement ReduceLoopCount");
609 /// Delete the instruction OldInst and everything after it, replacing it with
610 /// an unconditional branch to NewDest. This is used by the tail merging pass.
611 virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
612 MachineBasicBlock *NewDest) const;
614 /// Return true if it's legal to split the given basic
615 /// block at the specified instruction (i.e. instruction would be the start
616 /// of a new basic block).
617 virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
618 MachineBasicBlock::iterator MBBI) const {
622 /// Return true if it's profitable to predicate
623 /// instructions with accumulated instruction latency of "NumCycles"
624 /// of the specified basic block, where the probability of the instructions
625 /// being executed is given by Probability, and Confidence is a measure
626 /// of our confidence that it will be properly predicted.
628 bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
629 unsigned ExtraPredCycles,
630 BranchProbability Probability) const {
634 /// Second variant of isProfitableToIfCvt. This one
635 /// checks for the case where two basic blocks from true and false path
636 /// of a if-then-else (diamond) are predicated on mutally exclusive
637 /// predicates, where the probability of the true path being taken is given
638 /// by Probability, and Confidence is a measure of our confidence that it
639 /// will be properly predicted.
641 isProfitableToIfCvt(MachineBasicBlock &TMBB,
642 unsigned NumTCycles, unsigned ExtraTCycles,
643 MachineBasicBlock &FMBB,
644 unsigned NumFCycles, unsigned ExtraFCycles,
645 BranchProbability Probability) const {
649 /// Return true if it's profitable for if-converter to duplicate instructions
650 /// of specified accumulated instruction latencies in the specified MBB to
651 /// enable if-conversion.
652 /// The probability of the instructions being executed is given by
653 /// Probability, and Confidence is a measure of our confidence that it
654 /// will be properly predicted.
656 isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
657 BranchProbability Probability) const {
661 /// Return true if it's profitable to unpredicate
662 /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
663 /// exclusive predicates.
671 /// This may be profitable is conditional instructions are always executed.
672 virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
673 MachineBasicBlock &FMBB) const {
677 /// Return true if it is possible to insert a select
678 /// instruction that chooses between TrueReg and FalseReg based on the
679 /// condition code in Cond.
681 /// When successful, also return the latency in cycles from TrueReg,
682 /// FalseReg, and Cond to the destination register. In most cases, a select
683 /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
685 /// Some x86 implementations have 2-cycle cmov instructions.
687 /// @param MBB Block where select instruction would be inserted.
688 /// @param Cond Condition returned by AnalyzeBranch.
689 /// @param TrueReg Virtual register to select when Cond is true.
690 /// @param FalseReg Virtual register to select when Cond is false.
691 /// @param CondCycles Latency from Cond+Branch to select output.
692 /// @param TrueCycles Latency from TrueReg to select output.
693 /// @param FalseCycles Latency from FalseReg to select output.
694 virtual bool canInsertSelect(const MachineBasicBlock &MBB,
695 ArrayRef<MachineOperand> Cond,
696 unsigned TrueReg, unsigned FalseReg,
698 int &TrueCycles, int &FalseCycles) const {
702 /// Insert a select instruction into MBB before I that will copy TrueReg to
703 /// DstReg when Cond is true, and FalseReg to DstReg when Cond is false.
705 /// This function can only be called after canInsertSelect() returned true.
706 /// The condition in Cond comes from AnalyzeBranch, and it can be assumed
707 /// that the same flags or registers required by Cond are available at the
710 /// @param MBB Block where select instruction should be inserted.
711 /// @param I Insertion point.
712 /// @param DL Source location for debugging.
713 /// @param DstReg Virtual register to be defined by select instruction.
714 /// @param Cond Condition as computed by AnalyzeBranch.
715 /// @param TrueReg Virtual register to copy when Cond is true.
716 /// @param FalseReg Virtual register to copy when Cons is false.
717 virtual void insertSelect(MachineBasicBlock &MBB,
718 MachineBasicBlock::iterator I, const DebugLoc &DL,
719 unsigned DstReg, ArrayRef<MachineOperand> Cond,
720 unsigned TrueReg, unsigned FalseReg) const {
721 llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!");
724 /// Analyze the given select instruction, returning true if
725 /// it cannot be understood. It is assumed that MI->isSelect() is true.
727 /// When successful, return the controlling condition and the operands that
728 /// determine the true and false result values.
730 /// Result = SELECT Cond, TrueOp, FalseOp
732 /// Some targets can optimize select instructions, for example by predicating
733 /// the instruction defining one of the operands. Such targets should set
736 /// @param MI Select instruction to analyze.
737 /// @param Cond Condition controlling the select.
738 /// @param TrueOp Operand number of the value selected when Cond is true.
739 /// @param FalseOp Operand number of the value selected when Cond is false.
740 /// @param Optimizable Returned as true if MI is optimizable.
741 /// @returns False on success.
742 virtual bool analyzeSelect(const MachineInstr &MI,
743 SmallVectorImpl<MachineOperand> &Cond,
744 unsigned &TrueOp, unsigned &FalseOp,
745 bool &Optimizable) const {
746 assert(MI.getDesc().isSelect() && "MI must be a select instruction");
750 /// Given a select instruction that was understood by
751 /// analyzeSelect and returned Optimizable = true, attempt to optimize MI by
752 /// merging it with one of its operands. Returns NULL on failure.
754 /// When successful, returns the new select instruction. The client is
755 /// responsible for deleting MI.
757 /// If both sides of the select can be optimized, PreferFalse is used to pick
760 /// @param MI Optimizable select instruction.
761 /// @param NewMIs Set that record all MIs in the basic block up to \p
762 /// MI. Has to be updated with any newly created MI or deleted ones.
763 /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
764 /// @returns Optimized instruction or NULL.
765 virtual MachineInstr *optimizeSelect(MachineInstr &MI,
766 SmallPtrSetImpl<MachineInstr *> &NewMIs,
767 bool PreferFalse = false) const {
768 // This function must be implemented if Optimizable is ever set.
769 llvm_unreachable("Target must implement TargetInstrInfo::optimizeSelect!");
772 /// Emit instructions to copy a pair of physical registers.
774 /// This function should support copies within any legal register class as
775 /// well as any cross-class copies created during instruction selection.
777 /// The source and destination registers may overlap, which may require a
778 /// careful implementation when multiple copy instructions are required for
779 /// large registers. See for example the ARM target.
780 virtual void copyPhysReg(MachineBasicBlock &MBB,
781 MachineBasicBlock::iterator MI, const DebugLoc &DL,
782 unsigned DestReg, unsigned SrcReg,
783 bool KillSrc) const {
784 llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
787 /// Store the specified register of the given register class to the specified
788 /// stack frame index. The store instruction is to be added to the given
789 /// machine basic block before the specified machine instruction. If isKill
790 /// is true, the register operand is the last use and must be marked kill.
791 virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
792 MachineBasicBlock::iterator MI,
793 unsigned SrcReg, bool isKill, int FrameIndex,
794 const TargetRegisterClass *RC,
795 const TargetRegisterInfo *TRI) const {
796 llvm_unreachable("Target didn't implement "
797 "TargetInstrInfo::storeRegToStackSlot!");
800 /// Load the specified register of the given register class from the specified
801 /// stack frame index. The load instruction is to be added to the given
802 /// machine basic block before the specified machine instruction.
803 virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
804 MachineBasicBlock::iterator MI,
805 unsigned DestReg, int FrameIndex,
806 const TargetRegisterClass *RC,
807 const TargetRegisterInfo *TRI) const {
808 llvm_unreachable("Target didn't implement "
809 "TargetInstrInfo::loadRegFromStackSlot!");
812 /// This function is called for all pseudo instructions
813 /// that remain after register allocation. Many pseudo instructions are
814 /// created to help register allocation. This is the place to convert them
815 /// into real instructions. The target can edit MI in place, or it can insert
816 /// new instructions and erase MI. The function should return true if
817 /// anything was changed.
818 virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }
820 /// Check whether the target can fold a load that feeds a subreg operand
821 /// (or a subreg operand that feeds a store).
822 /// For example, X86 may want to return true if it can fold
823 /// movl (%esp), %eax
828 /// Ideally, we'd like the target implementation of foldMemoryOperand() to
829 /// reject subregs - but since this behavior used to be enforced in the
830 /// target-independent code, moving this responsibility to the targets
831 /// has the potential of causing nasty silent breakage in out-of-tree targets.
832 virtual bool isSubregFoldable() const { return false; }
834 /// Attempt to fold a load or store of the specified stack
835 /// slot into the specified machine instruction for the specified operand(s).
836 /// If this is possible, a new instruction is returned with the specified
837 /// operand folded, otherwise NULL is returned.
838 /// The new instruction is inserted before MI, and the client is responsible
839 /// for removing the old instruction.
840 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
842 LiveIntervals *LIS = nullptr) const;
844 /// Same as the previous version except it allows folding of any load and
845 /// store from / to any address, not just from a specific stack slot.
846 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
847 MachineInstr &LoadMI,
848 LiveIntervals *LIS = nullptr) const;
850 /// Return true when there is potentially a faster code sequence
851 /// for an instruction chain ending in \p Root. All potential patterns are
852 /// returned in the \p Pattern vector. Pattern should be sorted in priority
853 /// order since the pattern evaluator stops checking as soon as it finds a
855 /// \param Root - Instruction that could be combined with one of its operands
856 /// \param Patterns - Vector of possible combination patterns
857 virtual bool getMachineCombinerPatterns(
859 SmallVectorImpl<MachineCombinerPattern> &Patterns) const;
861 /// Return true when a code sequence can improve throughput. It
862 /// should be called only for instructions in loops.
863 /// \param Pattern - combiner pattern
864 virtual bool isThroughputPattern(MachineCombinerPattern Pattern) const;
866 /// Return true if the input \P Inst is part of a chain of dependent ops
867 /// that are suitable for reassociation, otherwise return false.
868 /// If the instruction's operands must be commuted to have a previous
869 /// instruction of the same type define the first source operand, \P Commuted
870 /// will be set to true.
871 bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const;
873 /// Return true when \P Inst is both associative and commutative.
874 virtual bool isAssociativeAndCommutative(const MachineInstr &Inst) const {
878 /// Return true when \P Inst has reassociable operands in the same \P MBB.
879 virtual bool hasReassociableOperands(const MachineInstr &Inst,
880 const MachineBasicBlock *MBB) const;
882 /// Return true when \P Inst has reassociable sibling.
883 bool hasReassociableSibling(const MachineInstr &Inst, bool &Commuted) const;
885 /// When getMachineCombinerPatterns() finds patterns, this function generates
886 /// the instructions that could replace the original code sequence. The client
887 /// has to decide whether the actual replacement is beneficial or not.
888 /// \param Root - Instruction that could be combined with one of its operands
889 /// \param Pattern - Combination pattern for Root
890 /// \param InsInstrs - Vector of new instructions that implement P
891 /// \param DelInstrs - Old instructions, including Root, that could be
892 /// replaced by InsInstr
893 /// \param InstrIdxForVirtReg - map of virtual register to instruction in
894 /// InsInstr that defines it
895 virtual void genAlternativeCodeSequence(
896 MachineInstr &Root, MachineCombinerPattern Pattern,
897 SmallVectorImpl<MachineInstr *> &InsInstrs,
898 SmallVectorImpl<MachineInstr *> &DelInstrs,
899 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
901 /// Attempt to reassociate \P Root and \P Prev according to \P Pattern to
902 /// reduce critical path length.
903 void reassociateOps(MachineInstr &Root, MachineInstr &Prev,
904 MachineCombinerPattern Pattern,
905 SmallVectorImpl<MachineInstr *> &InsInstrs,
906 SmallVectorImpl<MachineInstr *> &DelInstrs,
907 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
909 /// This is an architecture-specific helper function of reassociateOps.
910 /// Set special operand attributes for new instructions after reassociation.
911 virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
912 MachineInstr &NewMI1,
913 MachineInstr &NewMI2) const {
916 /// Return true when a target supports MachineCombiner.
917 virtual bool useMachineCombiner() const { return false; }
920 /// Target-dependent implementation for foldMemoryOperand.
921 /// Target-independent code in foldMemoryOperand will
922 /// take care of adding a MachineMemOperand to the newly created instruction.
923 /// The instruction and any auxiliary instructions necessary will be inserted
925 virtual MachineInstr *
926 foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
927 ArrayRef<unsigned> Ops,
928 MachineBasicBlock::iterator InsertPt, int FrameIndex,
929 LiveIntervals *LIS = nullptr) const {
933 /// Target-dependent implementation for foldMemoryOperand.
934 /// Target-independent code in foldMemoryOperand will
935 /// take care of adding a MachineMemOperand to the newly created instruction.
936 /// The instruction and any auxiliary instructions necessary will be inserted
938 virtual MachineInstr *foldMemoryOperandImpl(
939 MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
940 MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
941 LiveIntervals *LIS = nullptr) const {
945 /// \brief Target-dependent implementation of getRegSequenceInputs.
947 /// \returns true if it is possible to build the equivalent
948 /// REG_SEQUENCE inputs with the pair \p MI, \p DefIdx. False otherwise.
950 /// \pre MI.isRegSequenceLike().
952 /// \see TargetInstrInfo::getRegSequenceInputs.
953 virtual bool getRegSequenceLikeInputs(
954 const MachineInstr &MI, unsigned DefIdx,
955 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
959 /// \brief Target-dependent implementation of getExtractSubregInputs.
961 /// \returns true if it is possible to build the equivalent
962 /// EXTRACT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
964 /// \pre MI.isExtractSubregLike().
966 /// \see TargetInstrInfo::getExtractSubregInputs.
967 virtual bool getExtractSubregLikeInputs(
968 const MachineInstr &MI, unsigned DefIdx,
969 RegSubRegPairAndIdx &InputReg) const {
973 /// \brief Target-dependent implementation of getInsertSubregInputs.
975 /// \returns true if it is possible to build the equivalent
976 /// INSERT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
978 /// \pre MI.isInsertSubregLike().
980 /// \see TargetInstrInfo::getInsertSubregInputs.
982 getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
983 RegSubRegPair &BaseReg,
984 RegSubRegPairAndIdx &InsertedReg) const {
989 /// unfoldMemoryOperand - Separate a single instruction which folded a load or
990 /// a store or a load and a store into two or more instruction. If this is
991 /// possible, returns true as well as the new instructions by reference.
993 unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, unsigned Reg,
994 bool UnfoldLoad, bool UnfoldStore,
995 SmallVectorImpl<MachineInstr *> &NewMIs) const {
999 virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
1000 SmallVectorImpl<SDNode*> &NewNodes) const {
1004 /// Returns the opcode of the would be new
1005 /// instruction after load / store are unfolded from an instruction of the
1006 /// specified opcode. It returns zero if the specified unfolding is not
1007 /// possible. If LoadRegIndex is non-null, it is filled in with the operand
1008 /// index of the operand which will hold the register holding the loaded
1010 virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc,
1011 bool UnfoldLoad, bool UnfoldStore,
1012 unsigned *LoadRegIndex = nullptr) const {
1016 /// This is used by the pre-regalloc scheduler to determine if two loads are
1017 /// loading from the same base address. It should only return true if the base
1018 /// pointers are the same and the only differences between the two addresses
1019 /// are the offset. It also returns the offsets by reference.
1020 virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1021 int64_t &Offset1, int64_t &Offset2) const {
1025 /// This is a used by the pre-regalloc scheduler to determine (in conjunction
1026 /// with areLoadsFromSameBasePtr) if two loads should be scheduled together.
1027 /// On some targets if two loads are loading from
1028 /// addresses in the same cache line, it's better if they are scheduled
1029 /// together. This function takes two integers that represent the load offsets
1030 /// from the common base address. It returns true if it decides it's desirable
1031 /// to schedule the two loads together. "NumLoads" is the number of loads that
1032 /// have already been scheduled after Load1.
1033 virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1034 int64_t Offset1, int64_t Offset2,
1035 unsigned NumLoads) const {
1039 /// Get the base register and byte offset of an instruction that reads/writes
1041 virtual bool getMemOpBaseRegImmOfs(MachineInstr &MemOp, unsigned &BaseReg,
1043 const TargetRegisterInfo *TRI) const {
1047 /// Return true if the instruction contains a base register and offset. If
1048 /// true, the function also sets the operand position in the instruction
1049 /// for the base register and offset.
1050 virtual bool getBaseAndOffsetPosition(const MachineInstr &MI,
1052 unsigned &OffsetPos) const {
1056 /// If the instruction is an increment of a constant value, return the amount.
1057 virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const {
1061 /// Returns true if the two given memory operations should be scheduled
1062 /// adjacent. Note that you have to add:
1063 /// DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1065 /// DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
1066 /// to TargetPassConfig::createMachineScheduler() to have an effect.
1067 virtual bool shouldClusterMemOps(MachineInstr &FirstLdSt,
1068 MachineInstr &SecondLdSt,
1069 unsigned NumLoads) const {
1070 llvm_unreachable("target did not implement shouldClusterMemOps()");
1073 /// Can this target fuse the given instructions if they are scheduled
1074 /// adjacent. Note that you have to add:
1075 /// DAG.addMutation(createMacroFusionDAGMutation());
1076 /// to TargetPassConfig::createMachineScheduler() to have an effect.
1077 virtual bool shouldScheduleAdjacent(const MachineInstr &First,
1078 const MachineInstr &Second) const {
1079 llvm_unreachable("target did not implement shouldScheduleAdjacent()");
1082 /// Reverses the branch condition of the specified condition list,
1083 /// returning false on success and true if it cannot be reversed.
1085 bool reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1089 /// Insert a noop into the instruction stream at the specified point.
1090 virtual void insertNoop(MachineBasicBlock &MBB,
1091 MachineBasicBlock::iterator MI) const;
1094 /// Return the noop instruction to use for a noop.
1095 virtual void getNoopForMachoTarget(MCInst &NopInst) const;
1097 /// Return true for post-incremented instructions.
1098 virtual bool isPostIncrement(const MachineInstr &MI) const {
1102 /// Returns true if the instruction is already predicated.
1103 virtual bool isPredicated(const MachineInstr &MI) const {
1107 /// Returns true if the instruction is a
1108 /// terminator instruction that has not been predicated.
1109 virtual bool isUnpredicatedTerminator(const MachineInstr &MI) const;
1111 /// Convert the instruction into a predicated instruction.
1112 /// It returns true if the operation was successful.
1113 virtual bool PredicateInstruction(MachineInstr &MI,
1114 ArrayRef<MachineOperand> Pred) const;
1116 /// Returns true if the first specified predicate
1117 /// subsumes the second, e.g. GE subsumes GT.
1119 bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1120 ArrayRef<MachineOperand> Pred2) const {
1124 /// If the specified instruction defines any predicate
1125 /// or condition code register(s) used for predication, returns true as well
1126 /// as the definition predicate(s) by reference.
1127 virtual bool DefinesPredicate(MachineInstr &MI,
1128 std::vector<MachineOperand> &Pred) const {
1132 /// Return true if the specified instruction can be predicated.
1133 /// By default, this returns true for every instruction with a
1134 /// PredicateOperand.
1135 virtual bool isPredicable(MachineInstr &MI) const {
1136 return MI.getDesc().isPredicable();
1139 /// Return true if it's safe to move a machine
1140 /// instruction that defines the specified register class.
1141 virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
1145 /// Test if the given instruction should be considered a scheduling boundary.
1146 /// This primarily includes labels and terminators.
1147 virtual bool isSchedulingBoundary(const MachineInstr &MI,
1148 const MachineBasicBlock *MBB,
1149 const MachineFunction &MF) const;
1151 /// Measure the specified inline asm to determine an approximation of its
1153 virtual unsigned getInlineAsmLength(const char *Str,
1154 const MCAsmInfo &MAI) const;
1156 /// Allocate and return a hazard recognizer to use for this target when
1157 /// scheduling the machine instructions before register allocation.
1158 virtual ScheduleHazardRecognizer*
1159 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1160 const ScheduleDAG *DAG) const;
1162 /// Allocate and return a hazard recognizer to use for this target when
1163 /// scheduling the machine instructions before register allocation.
1164 virtual ScheduleHazardRecognizer*
1165 CreateTargetMIHazardRecognizer(const InstrItineraryData*,
1166 const ScheduleDAG *DAG) const;
1168 /// Allocate and return a hazard recognizer to use for this target when
1169 /// scheduling the machine instructions after register allocation.
1170 virtual ScheduleHazardRecognizer*
1171 CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,
1172 const ScheduleDAG *DAG) const;
1174 /// Allocate and return a hazard recognizer to use for by non-scheduling
1176 virtual ScheduleHazardRecognizer*
1177 CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
1181 /// Provide a global flag for disabling the PreRA hazard recognizer that
1182 /// targets may choose to honor.
1183 bool usePreRAHazardRecognizer() const;
1185 /// For a comparison instruction, return the source registers
1186 /// in SrcReg and SrcReg2 if having two register operands, and the value it
1187 /// compares against in CmpValue. Return true if the comparison instruction
1188 /// can be analyzed.
1189 virtual bool analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
1190 unsigned &SrcReg2, int &Mask, int &Value) const {
1194 /// See if the comparison instruction can be converted
1195 /// into something more efficient. E.g., on ARM most instructions can set the
1196 /// flags register, obviating the need for a separate CMP.
1197 virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
1198 unsigned SrcReg2, int Mask, int Value,
1199 const MachineRegisterInfo *MRI) const {
1202 virtual bool optimizeCondBranch(MachineInstr &MI) const { return false; }
1204 /// Try to remove the load by folding it to a register operand at the use.
1205 /// We fold the load instructions if and only if the
1206 /// def and use are in the same BB. We only look at one load and see
1207 /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
1208 /// defined by the load we are trying to fold. DefMI returns the machine
1209 /// instruction that defines FoldAsLoadDefReg, and the function returns
1210 /// the machine instruction generated due to folding.
1211 virtual MachineInstr *optimizeLoadInstr(MachineInstr &MI,
1212 const MachineRegisterInfo *MRI,
1213 unsigned &FoldAsLoadDefReg,
1214 MachineInstr *&DefMI) const {
1218 /// 'Reg' is known to be defined by a move immediate instruction,
1219 /// try to fold the immediate into the use instruction.
1220 /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
1221 /// then the caller may assume that DefMI has been erased from its parent
1222 /// block. The caller may assume that it will not be erased by this
1223 /// function otherwise.
1224 virtual bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1225 unsigned Reg, MachineRegisterInfo *MRI) const {
1229 /// Return the number of u-operations the given machine
1230 /// instruction will be decoded to on the target cpu. The itinerary's
1231 /// IssueWidth is the number of microops that can be dispatched each
1232 /// cycle. An instruction with zero microops takes no dispatch resources.
1233 virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
1234 const MachineInstr &MI) const;
1236 /// Return true for pseudo instructions that don't consume any
1237 /// machine resources in their current form. These are common cases that the
1238 /// scheduler should consider free, rather than conservatively handling them
1239 /// as instructions with no itinerary.
1240 bool isZeroCost(unsigned Opcode) const {
1241 return Opcode <= TargetOpcode::COPY;
1244 virtual int getOperandLatency(const InstrItineraryData *ItinData,
1245 SDNode *DefNode, unsigned DefIdx,
1246 SDNode *UseNode, unsigned UseIdx) const;
1248 /// Compute and return the use operand latency of a given pair of def and use.
1249 /// In most cases, the static scheduling itinerary was enough to determine the
1250 /// operand latency. But it may not be possible for instructions with variable
1251 /// number of defs / uses.
1253 /// This is a raw interface to the itinerary that may be directly overridden
1254 /// by a target. Use computeOperandLatency to get the best estimate of
1256 virtual int getOperandLatency(const InstrItineraryData *ItinData,
1257 const MachineInstr &DefMI, unsigned DefIdx,
1258 const MachineInstr &UseMI,
1259 unsigned UseIdx) const;
1261 /// Compute the instruction latency of a given instruction.
1262 /// If the instruction has higher cost when predicated, it's returned via
1264 virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1265 const MachineInstr &MI,
1266 unsigned *PredCost = nullptr) const;
1268 virtual unsigned getPredicationCost(const MachineInstr &MI) const;
1270 virtual int getInstrLatency(const InstrItineraryData *ItinData,
1271 SDNode *Node) const;
1273 /// Return the default expected latency for a def based on its opcode.
1274 unsigned defaultDefLatency(const MCSchedModel &SchedModel,
1275 const MachineInstr &DefMI) const;
1277 int computeDefOperandLatency(const InstrItineraryData *ItinData,
1278 const MachineInstr &DefMI) const;
1280 /// Return true if this opcode has high latency to its result.
1281 virtual bool isHighLatencyDef(int opc) const { return false; }
1283 /// Compute operand latency between a def of 'Reg'
1284 /// and a use in the current loop. Return true if the target considered
1285 /// it 'high'. This is used by optimization passes such as machine LICM to
1286 /// determine whether it makes sense to hoist an instruction out even in a
1287 /// high register pressure situation.
1288 virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
1289 const MachineRegisterInfo *MRI,
1290 const MachineInstr &DefMI, unsigned DefIdx,
1291 const MachineInstr &UseMI,
1292 unsigned UseIdx) const {
1296 /// Compute operand latency of a def of 'Reg'. Return true
1297 /// if the target considered it 'low'.
1298 virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel,
1299 const MachineInstr &DefMI,
1300 unsigned DefIdx) const;
1302 /// Perform target-specific instruction verification.
1303 virtual bool verifyInstruction(const MachineInstr &MI,
1304 StringRef &ErrInfo) const {
1308 /// Return the current execution domain and bit mask of
1309 /// possible domains for instruction.
1311 /// Some micro-architectures have multiple execution domains, and multiple
1312 /// opcodes that perform the same operation in different domains. For
1313 /// example, the x86 architecture provides the por, orps, and orpd
1314 /// instructions that all do the same thing. There is a latency penalty if a
1315 /// register is written in one domain and read in another.
1317 /// This function returns a pair (domain, mask) containing the execution
1318 /// domain of MI, and a bit mask of possible domains. The setExecutionDomain
1319 /// function can be used to change the opcode to one of the domains in the
1320 /// bit mask. Instructions whose execution domain can't be changed should
1321 /// return a 0 mask.
1323 /// The execution domain numbers don't have any special meaning except domain
1324 /// 0 is used for instructions that are not associated with any interesting
1325 /// execution domain.
1327 virtual std::pair<uint16_t, uint16_t>
1328 getExecutionDomain(const MachineInstr &MI) const {
1329 return std::make_pair(0, 0);
1332 /// Change the opcode of MI to execute in Domain.
1334 /// The bit (1 << Domain) must be set in the mask returned from
1335 /// getExecutionDomain(MI).
1336 virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const {}
1338 /// Returns the preferred minimum clearance
1339 /// before an instruction with an unwanted partial register update.
1341 /// Some instructions only write part of a register, and implicitly need to
1342 /// read the other parts of the register. This may cause unwanted stalls
1343 /// preventing otherwise unrelated instructions from executing in parallel in
1344 /// an out-of-order CPU.
1346 /// For example, the x86 instruction cvtsi2ss writes its result to bits
1347 /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
1348 /// the instruction needs to wait for the old value of the register to become
1351 /// addps %xmm1, %xmm0
1352 /// movaps %xmm0, (%rax)
1353 /// cvtsi2ss %rbx, %xmm0
1355 /// In the code above, the cvtsi2ss instruction needs to wait for the addps
1356 /// instruction before it can issue, even though the high bits of %xmm0
1357 /// probably aren't needed.
1359 /// This hook returns the preferred clearance before MI, measured in
1360 /// instructions. Other defs of MI's operand OpNum are avoided in the last N
1361 /// instructions before MI. It should only return a positive value for
1362 /// unwanted dependencies. If the old bits of the defined register have
1363 /// useful values, or if MI is determined to otherwise read the dependency,
1364 /// the hook should return 0.
1366 /// The unwanted dependency may be handled by:
1368 /// 1. Allocating the same register for an MI def and use. That makes the
1369 /// unwanted dependency identical to a required dependency.
1371 /// 2. Allocating a register for the def that has no defs in the previous N
1374 /// 3. Calling breakPartialRegDependency() with the same arguments. This
1375 /// allows the target to insert a dependency breaking instruction.
1378 getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum,
1379 const TargetRegisterInfo *TRI) const {
1380 // The default implementation returns 0 for no partial register dependency.
1384 /// \brief Return the minimum clearance before an instruction that reads an
1385 /// unused register.
1387 /// For example, AVX instructions may copy part of a register operand into
1388 /// the unused high bits of the destination register.
1390 /// vcvtsi2sdq %rax, %xmm0<undef>, %xmm14
1392 /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
1393 /// false dependence on any previous write to %xmm0.
1395 /// This hook works similarly to getPartialRegUpdateClearance, except that it
1396 /// does not take an operand index. Instead sets \p OpNum to the index of the
1397 /// unused register.
1398 virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned &OpNum,
1399 const TargetRegisterInfo *TRI) const {
1400 // The default implementation returns 0 for no undef register dependency.
1404 /// Insert a dependency-breaking instruction
1405 /// before MI to eliminate an unwanted dependency on OpNum.
1407 /// If it wasn't possible to avoid a def in the last N instructions before MI
1408 /// (see getPartialRegUpdateClearance), this hook will be called to break the
1409 /// unwanted dependency.
1411 /// On x86, an xorps instruction can be used as a dependency breaker:
1413 /// addps %xmm1, %xmm0
1414 /// movaps %xmm0, (%rax)
1415 /// xorps %xmm0, %xmm0
1416 /// cvtsi2ss %rbx, %xmm0
1418 /// An <imp-kill> operand should be added to MI if an instruction was
1419 /// inserted. This ties the instructions together in the post-ra scheduler.
1421 virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
1422 const TargetRegisterInfo *TRI) const {}
1424 /// Create machine specific model for scheduling.
1425 virtual DFAPacketizer *
1426 CreateTargetScheduleState(const TargetSubtargetInfo &) const {
1430 // Sometimes, it is possible for the target
1431 // to tell, even without aliasing information, that two MIs access different
1432 // memory addresses. This function returns true if two MIs access different
1433 // memory addresses and false otherwise.
1435 areMemAccessesTriviallyDisjoint(MachineInstr &MIa, MachineInstr &MIb,
1436 AliasAnalysis *AA = nullptr) const {
1437 assert((MIa.mayLoad() || MIa.mayStore()) &&
1438 "MIa must load from or modify a memory location");
1439 assert((MIb.mayLoad() || MIb.mayStore()) &&
1440 "MIb must load from or modify a memory location");
1444 /// \brief Return the value to use for the MachineCSE's LookAheadLimit,
1445 /// which is a heuristic used for CSE'ing phys reg defs.
1446 virtual unsigned getMachineCSELookAheadLimit () const {
1447 // The default lookahead is small to prevent unprofitable quadratic
1452 /// Return an array that contains the ids of the target indices (used for the
1453 /// TargetIndex machine operand) and their names.
1455 /// MIR Serialization is able to serialize only the target indices that are
1456 /// defined by this method.
1457 virtual ArrayRef<std::pair<int, const char *>>
1458 getSerializableTargetIndices() const {
1462 /// Decompose the machine operand's target flags into two values - the direct
1463 /// target flag value and any of bit flags that are applied.
1464 virtual std::pair<unsigned, unsigned>
1465 decomposeMachineOperandsTargetFlags(unsigned /*TF*/) const {
1466 return std::make_pair(0u, 0u);
1469 /// Return an array that contains the direct target flag values and their
1472 /// MIR Serialization is able to serialize only the target flags that are
1473 /// defined by this method.
1474 virtual ArrayRef<std::pair<unsigned, const char *>>
1475 getSerializableDirectMachineOperandTargetFlags() const {
1479 /// Return an array that contains the bitmask target flag values and their
1482 /// MIR Serialization is able to serialize only the target flags that are
1483 /// defined by this method.
1484 virtual ArrayRef<std::pair<unsigned, const char *>>
1485 getSerializableBitmaskMachineOperandTargetFlags() const {
1489 /// Determines whether |Inst| is a tail call instruction.
1490 virtual bool isTailCall(const MachineInstr &Inst) const {
1495 unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
1496 unsigned CatchRetOpcode;
1497 unsigned ReturnOpcode;
1500 /// \brief Provide DenseMapInfo for TargetInstrInfo::RegSubRegPair.
1502 struct DenseMapInfo<TargetInstrInfo::RegSubRegPair> {
1503 typedef DenseMapInfo<unsigned> RegInfo;
1505 static inline TargetInstrInfo::RegSubRegPair getEmptyKey() {
1506 return TargetInstrInfo::RegSubRegPair(RegInfo::getEmptyKey(),
1507 RegInfo::getEmptyKey());
1509 static inline TargetInstrInfo::RegSubRegPair getTombstoneKey() {
1510 return TargetInstrInfo::RegSubRegPair(RegInfo::getTombstoneKey(),
1511 RegInfo::getTombstoneKey());
1513 /// \brief Reuse getHashValue implementation from
1514 /// std::pair<unsigned, unsigned>.
1515 static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val) {
1516 std::pair<unsigned, unsigned> PairVal =
1517 std::make_pair(Val.Reg, Val.SubReg);
1518 return DenseMapInfo<std::pair<unsigned, unsigned>>::getHashValue(PairVal);
1520 static bool isEqual(const TargetInstrInfo::RegSubRegPair &LHS,
1521 const TargetInstrInfo::RegSubRegPair &RHS) {
1522 return RegInfo::isEqual(LHS.Reg, RHS.Reg) &&
1523 RegInfo::isEqual(LHS.SubReg, RHS.SubReg);
1527 } // end namespace llvm
1529 #endif // LLVM_TARGET_TARGETINSTRINFO_H