1 //===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// This file describes how to lower LLVM code to machine code. This has two
13 /// 1. Which ValueTypes are natively supported by the target.
14 /// 2. Which operations are supported for supported ValueTypes.
15 /// 3. Cost thresholds for alternative implementations of certain operations.
17 /// In addition it has a few other components, like information about FP
20 //===----------------------------------------------------------------------===//
22 #ifndef LLVM_CODEGEN_TARGETLOWERING_H
23 #define LLVM_CODEGEN_TARGETLOWERING_H
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
32 #include "llvm/CodeGen/DAGCombine.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/RuntimeLibcalls.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/TargetCallingConv.h"
38 #include "llvm/CodeGen/ValueTypes.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/CallSite.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/IRBuilder.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Type.h"
50 #include "llvm/MC/MCRegisterInfo.h"
51 #include "llvm/Support/AtomicOrdering.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MachineValueType.h"
55 #include "llvm/Target/TargetMachine.h"
68 class BranchProbability
;
73 class FunctionLoweringInfo
;
78 class MachineBasicBlock
;
79 class MachineFunction
;
81 class MachineJumpTableInfo
;
83 class MachineRegisterInfo
;
87 class TargetRegisterClass
;
88 class TargetLibraryInfo
;
89 class TargetRegisterInfo
;
95 None
, // No preference
96 Source
, // Follow source order.
97 RegPressure
, // Scheduling for lowest register pressure.
98 Hybrid
, // Scheduling for both latency and register pressure.
99 ILP
, // Scheduling for ILP in low register pressure mode.
100 VLIW
// Scheduling for VLIW targets.
103 } // end namespace Sched
105 /// This base class for TargetLowering contains the SelectionDAG-independent
106 /// parts that can be used from the rest of CodeGen.
107 class TargetLoweringBase
{
109 /// This enum indicates whether operations are valid for a target, and if not,
110 /// what action should be used to make them valid.
111 enum LegalizeAction
: uint8_t {
112 Legal
, // The target natively supports this operation.
113 Promote
, // This operation should be executed in a larger type.
114 Expand
, // Try to expand this to other ops, otherwise use a libcall.
115 LibCall
, // Don't try to expand this to other ops, always use a libcall.
116 Custom
// Use the LowerOperation hook to implement custom lowering.
119 /// This enum indicates whether a types are legal for a target, and if not,
120 /// what action should be used to make them valid.
121 enum LegalizeTypeAction
: uint8_t {
122 TypeLegal
, // The target natively supports this type.
123 TypePromoteInteger
, // Replace this integer with a larger one.
124 TypeExpandInteger
, // Split this integer into two of half the size.
125 TypeSoftenFloat
, // Convert this float to a same size integer type,
126 // if an operation is not supported in target HW.
127 TypeExpandFloat
, // Split this float into two of half the size.
128 TypeScalarizeVector
, // Replace this one-element vector with its element.
129 TypeSplitVector
, // Split this vector into two of half the size.
130 TypeWidenVector
, // This vector should be widened into a larger vector.
131 TypePromoteFloat
// Replace this float with a larger one.
134 /// LegalizeKind holds the legalization kind that needs to happen to EVT
135 /// in order to type-legalize it.
136 using LegalizeKind
= std::pair
<LegalizeTypeAction
, EVT
>;
138 /// Enum that describes how the target represents true/false values.
139 enum BooleanContent
{
140 UndefinedBooleanContent
, // Only bit 0 counts, the rest can hold garbage.
141 ZeroOrOneBooleanContent
, // All bits zero except for bit 0.
142 ZeroOrNegativeOneBooleanContent
// All bits equal to bit 0.
145 /// Enum that describes what type of support for selects the target has.
146 enum SelectSupportKind
{
147 ScalarValSelect
, // The target supports scalar selects (ex: cmov).
148 ScalarCondVectorVal
, // The target supports selects with a scalar condition
149 // and vector values (ex: cmov).
150 VectorMaskSelect
// The target supports vector selects with a vector
151 // mask (ex: x86 blends).
154 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
155 /// to, if at all. Exists because different targets have different levels of
156 /// support for these atomic instructions, and also have different options
157 /// w.r.t. what they should expand to.
158 enum class AtomicExpansionKind
{
159 None
, // Don't expand the instruction.
160 LLSC
, // Expand the instruction into loadlinked/storeconditional; used
162 LLOnly
, // Expand the (load) instruction into just a load-linked, which has
163 // greater atomic guarantees than a normal load.
164 CmpXChg
, // Expand the instruction into cmpxchg; used by at least X86.
165 MaskedIntrinsic
, // Use a target-specific intrinsic for the LL/SC loop.
168 /// Enum that specifies when a multiplication should be expanded.
169 enum class MulExpansionKind
{
170 Always
, // Always expand the instruction.
171 OnlyLegalOrCustom
, // Only expand when the resulting instructions are legal
177 Value
*Val
= nullptr;
178 SDValue Node
= SDValue();
188 bool IsSwiftSelf
: 1;
189 bool IsSwiftError
: 1;
190 uint16_t Alignment
= 0;
193 : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
194 IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
195 IsSwiftSelf(false), IsSwiftError(false) {}
197 void setAttributes(const CallBase
*Call
, unsigned ArgIdx
);
199 void setAttributes(ImmutableCallSite
*CS
, unsigned ArgIdx
) {
200 return setAttributes(cast
<CallBase
>(CS
->getInstruction()), ArgIdx
);
203 using ArgListTy
= std::vector
<ArgListEntry
>;
205 virtual void markLibCallAttributes(MachineFunction
*MF
, unsigned CC
,
206 ArgListTy
&Args
) const {};
208 static ISD::NodeType
getExtendForContent(BooleanContent Content
) {
210 case UndefinedBooleanContent
:
211 // Extend by adding rubbish bits.
212 return ISD::ANY_EXTEND
;
213 case ZeroOrOneBooleanContent
:
214 // Extend by adding zero bits.
215 return ISD::ZERO_EXTEND
;
216 case ZeroOrNegativeOneBooleanContent
:
217 // Extend by copying the sign bit.
218 return ISD::SIGN_EXTEND
;
220 llvm_unreachable("Invalid content kind");
223 /// NOTE: The TargetMachine owns TLOF.
224 explicit TargetLoweringBase(const TargetMachine
&TM
);
225 TargetLoweringBase(const TargetLoweringBase
&) = delete;
226 TargetLoweringBase
&operator=(const TargetLoweringBase
&) = delete;
227 virtual ~TargetLoweringBase() = default;
230 /// Initialize all of the actions to default values.
234 const TargetMachine
&getTargetMachine() const { return TM
; }
236 virtual bool useSoftFloat() const { return false; }
238 /// Return the pointer type for the given address space, defaults to
239 /// the pointer type from the data layout.
240 /// FIXME: The default needs to be removed once all the code is updated.
241 MVT
getPointerTy(const DataLayout
&DL
, uint32_t AS
= 0) const {
242 return MVT::getIntegerVT(DL
.getPointerSizeInBits(AS
));
245 /// Return the type for frame index, which is determined by
246 /// the alloca address space specified through the data layout.
247 MVT
getFrameIndexTy(const DataLayout
&DL
) const {
248 return getPointerTy(DL
, DL
.getAllocaAddrSpace());
251 /// Return the type for operands of fence.
252 /// TODO: Let fence operands be of i32 type and remove this.
253 virtual MVT
getFenceOperandTy(const DataLayout
&DL
) const {
254 return getPointerTy(DL
);
257 /// EVT is not used in-tree, but is used by out-of-tree target.
258 /// A documentation for this function would be nice...
259 virtual MVT
getScalarShiftAmountTy(const DataLayout
&, EVT
) const;
261 EVT
getShiftAmountTy(EVT LHSTy
, const DataLayout
&DL
,
262 bool LegalTypes
= true) const;
264 /// Returns the type to be used for the index operand of:
265 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
266 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
267 virtual MVT
getVectorIdxTy(const DataLayout
&DL
) const {
268 return getPointerTy(DL
);
271 virtual bool isSelectSupported(SelectSupportKind
/*kind*/) const {
275 /// Return true if it is profitable to convert a select of FP constants into
276 /// a constant pool load whose address depends on the select condition. The
277 /// parameter may be used to differentiate a select with FP compare from
279 virtual bool reduceSelectOfFPConstantLoads(bool IsFPSetCC
) const {
283 /// Return true if multiple condition registers are available.
284 bool hasMultipleConditionRegisters() const {
285 return HasMultipleConditionRegisters
;
288 /// Return true if the target has BitExtract instructions.
289 bool hasExtractBitsInsn() const { return HasExtractBitsInsn
; }
291 /// Return the preferred vector type legalization action.
292 virtual TargetLoweringBase::LegalizeTypeAction
293 getPreferredVectorAction(MVT VT
) const {
294 // The default action for one element vectors is to scalarize
295 if (VT
.getVectorNumElements() == 1)
296 return TypeScalarizeVector
;
297 // The default action for other vectors is to promote
298 return TypePromoteInteger
;
301 // There are two general methods for expanding a BUILD_VECTOR node:
302 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
304 // 2. Build the vector on the stack and then load it.
305 // If this function returns true, then method (1) will be used, subject to
306 // the constraint that all of the necessary shuffles are legal (as determined
307 // by isShuffleMaskLegal). If this function returns false, then method (2) is
308 // always used. The vector type, and the number of defined values, are
311 shouldExpandBuildVectorWithShuffles(EVT
/* VT */,
312 unsigned DefinedValues
) const {
313 return DefinedValues
< 3;
316 /// Return true if integer divide is usually cheaper than a sequence of
317 /// several shifts, adds, and multiplies for this target.
318 /// The definition of "cheaper" may depend on whether we're optimizing
319 /// for speed or for size.
320 virtual bool isIntDivCheap(EVT VT
, AttributeList Attr
) const { return false; }
322 /// Return true if the target can handle a standalone remainder operation.
323 virtual bool hasStandaloneRem(EVT VT
) const {
327 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
328 virtual bool isFsqrtCheap(SDValue X
, SelectionDAG
&DAG
) const {
329 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
333 /// Reciprocal estimate status values used by the functions below.
334 enum ReciprocalEstimate
: int {
340 /// Return a ReciprocalEstimate enum value for a square root of the given type
341 /// based on the function's attributes. If the operation is not overridden by
342 /// the function's attributes, "Unspecified" is returned and target defaults
343 /// are expected to be used for instruction selection.
344 int getRecipEstimateSqrtEnabled(EVT VT
, MachineFunction
&MF
) const;
346 /// Return a ReciprocalEstimate enum value for a division of the given type
347 /// based on the function's attributes. If the operation is not overridden by
348 /// the function's attributes, "Unspecified" is returned and target defaults
349 /// are expected to be used for instruction selection.
350 int getRecipEstimateDivEnabled(EVT VT
, MachineFunction
&MF
) const;
352 /// Return the refinement step count for a square root of the given type based
353 /// on the function's attributes. If the operation is not overridden by
354 /// the function's attributes, "Unspecified" is returned and target defaults
355 /// are expected to be used for instruction selection.
356 int getSqrtRefinementSteps(EVT VT
, MachineFunction
&MF
) const;
358 /// Return the refinement step count for a division of the given type based
359 /// on the function's attributes. If the operation is not overridden by
360 /// the function's attributes, "Unspecified" is returned and target defaults
361 /// are expected to be used for instruction selection.
362 int getDivRefinementSteps(EVT VT
, MachineFunction
&MF
) const;
364 /// Returns true if target has indicated at least one type should be bypassed.
365 bool isSlowDivBypassed() const { return !BypassSlowDivWidths
.empty(); }
367 /// Returns map of slow types for division or remainder with corresponding
369 const DenseMap
<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
370 return BypassSlowDivWidths
;
373 /// Return true if Flow Control is an expensive operation that should be
375 bool isJumpExpensive() const { return JumpIsExpensive
; }
377 /// Return true if selects are only cheaper than branches if the branch is
378 /// unlikely to be predicted right.
379 bool isPredictableSelectExpensive() const {
380 return PredictableSelectIsExpensive
;
383 /// If a branch or a select condition is skewed in one direction by more than
384 /// this factor, it is very likely to be predicted correctly.
385 virtual BranchProbability
getPredictableBranchThreshold() const;
387 /// Return true if the following transform is beneficial:
388 /// fold (conv (load x)) -> (load (conv*)x)
389 /// On architectures that don't natively support some vector loads
390 /// efficiently, casting the load to a smaller vector of larger types and
391 /// loading is more efficient, however, this can be undone by optimizations in
393 virtual bool isLoadBitCastBeneficial(EVT LoadVT
,
394 EVT BitcastVT
) const {
395 // Don't do if we could do an indexed load on the original type, but not on
397 if (!LoadVT
.isSimple() || !BitcastVT
.isSimple())
400 MVT LoadMVT
= LoadVT
.getSimpleVT();
402 // Don't bother doing this if it's just going to be promoted again later, as
403 // doing so might interfere with other combines.
404 if (getOperationAction(ISD::LOAD
, LoadMVT
) == Promote
&&
405 getTypeToPromoteTo(ISD::LOAD
, LoadMVT
) == BitcastVT
.getSimpleVT())
411 /// Return true if the following transform is beneficial:
412 /// (store (y (conv x)), y*)) -> (store x, (x*))
413 virtual bool isStoreBitCastBeneficial(EVT StoreVT
, EVT BitcastVT
) const {
414 // Default to the same logic as loads.
415 return isLoadBitCastBeneficial(StoreVT
, BitcastVT
);
418 /// Return true if it is expected to be cheaper to do a store of a non-zero
419 /// vector constant with the given size and type for the address space than to
420 /// store the individual scalar element constants.
421 virtual bool storeOfVectorConstantIsCheap(EVT MemVT
,
423 unsigned AddrSpace
) const {
427 /// Allow store merging after legalization in addition to before legalization.
428 /// This may catch stores that do not exist earlier (eg, stores created from
430 virtual bool mergeStoresAfterLegalization() const { return true; }
432 /// Returns if it's reasonable to merge stores to MemVT size.
433 virtual bool canMergeStoresTo(unsigned AS
, EVT MemVT
,
434 const SelectionDAG
&DAG
) const {
438 /// Return true if it is cheap to speculate a call to intrinsic cttz.
439 virtual bool isCheapToSpeculateCttz() const {
443 /// Return true if it is cheap to speculate a call to intrinsic ctlz.
444 virtual bool isCheapToSpeculateCtlz() const {
448 /// Return true if ctlz instruction is fast.
449 virtual bool isCtlzFast() const {
453 /// Return true if it is safe to transform an integer-domain bitwise operation
454 /// into the equivalent floating-point operation. This should be set to true
455 /// if the target has IEEE-754-compliant fabs/fneg operations for the input
457 virtual bool hasBitPreservingFPLogic(EVT VT
) const {
461 /// Return true if it is cheaper to split the store of a merged int val
462 /// from a pair of smaller values into multiple stores.
463 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy
, EVT HTy
) const {
467 /// Return if the target supports combining a
470 /// %andResult = and %val1, #mask
471 /// %icmpResult = icmp %andResult, 0
473 /// into a single machine instruction of a form like:
475 /// cc = test %register, #mask
477 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction
&AndI
) const {
481 /// Use bitwise logic to make pairs of compares more efficient. For example:
482 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
483 /// This should be true when it takes more than one instruction to lower
484 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
485 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
486 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT
) const {
490 /// Return the preferred operand type if the target has a quick way to compare
491 /// integer values of the given size. Assume that any legal integer type can
492 /// be compared efficiently. Targets may override this to allow illegal wide
493 /// types to return a vector type if there is support to compare that type.
494 virtual MVT
hasFastEqualityCompare(unsigned NumBits
) const {
495 MVT VT
= MVT::getIntegerVT(NumBits
);
496 return isTypeLegal(VT
) ? VT
: MVT::INVALID_SIMPLE_VALUE_TYPE
;
499 /// Return true if the target should transform:
500 /// (X & Y) == Y ---> (~X & Y) == 0
501 /// (X & Y) != Y ---> (~X & Y) != 0
503 /// This may be profitable if the target has a bitwise and-not operation that
504 /// sets comparison flags. A target may want to limit the transformation based
505 /// on the type of Y or if Y is a constant.
507 /// Note that the transform will not occur if Y is known to be a power-of-2
508 /// because a mask and compare of a single bit can be handled by inverting the
509 /// predicate, for example:
510 /// (X & 8) == 8 ---> (X & 8) != 0
511 virtual bool hasAndNotCompare(SDValue Y
) const {
515 /// Return true if the target has a bitwise and-not operation:
517 /// This can be used to simplify select or other instructions.
518 virtual bool hasAndNot(SDValue X
) const {
519 // If the target has the more complex version of this operation, assume that
520 // it has this operation too.
521 return hasAndNotCompare(X
);
524 /// There are two ways to clear extreme bits (either low or high):
525 /// Mask: x & (-1 << y) (the instcombine canonical form)
526 /// Shifts: x >> y << y
527 /// Return true if the variant with 2 shifts is preferred.
528 /// Return false if there is no preference.
529 virtual bool preferShiftsToClearExtremeBits(SDValue X
) const {
530 // By default, let's assume that no one prefers shifts.
534 /// Should we tranform the IR-optimal check for whether given truncation
535 /// down into KeptBits would be truncating or not:
536 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
537 /// Into it's more traditional form:
538 /// ((%x << C) a>> C) dstcond %x
539 /// Return true if we should transform.
540 /// Return false if there is no preference.
541 virtual bool shouldTransformSignedTruncationCheck(EVT XVT
,
542 unsigned KeptBits
) const {
543 // By default, let's assume that no one prefers shifts.
547 /// Return true if the target wants to use the optimization that
548 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
549 /// promotedInst1(...(promotedInstN(ext(load)))).
550 bool enableExtLdPromotion() const { return EnableExtLdPromotion
; }
552 /// Return true if the target can combine store(extractelement VectorTy,
554 /// \p Cost[out] gives the cost of that transformation when this is true.
555 virtual bool canCombineStoreAndExtract(Type
*VectorTy
, Value
*Idx
,
556 unsigned &Cost
) const {
560 /// Return true if inserting a scalar into a variable element of an undef
561 /// vector is more efficiently handled by splatting the scalar instead.
562 virtual bool shouldSplatInsEltVarIndex(EVT
) const {
566 /// Return true if target supports floating point exceptions.
567 bool hasFloatingPointExceptions() const {
568 return HasFloatingPointExceptions
;
571 /// Return true if target always beneficiates from combining into FMA for a
572 /// given value type. This must typically return false on targets where FMA
573 /// takes more cycles to execute than FADD.
574 virtual bool enableAggressiveFMAFusion(EVT VT
) const {
578 /// Return the ValueType of the result of SETCC operations.
579 virtual EVT
getSetCCResultType(const DataLayout
&DL
, LLVMContext
&Context
,
582 /// Return the ValueType for comparison libcalls. Comparions libcalls include
583 /// floating point comparion calls, and Ordered/Unordered check calls on
584 /// floating point numbers.
586 MVT::SimpleValueType
getCmpLibcallReturnType() const;
588 /// For targets without i1 registers, this gives the nature of the high-bits
589 /// of boolean values held in types wider than i1.
591 /// "Boolean values" are special true/false values produced by nodes like
592 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
593 /// Not to be confused with general values promoted from i1. Some cpus
594 /// distinguish between vectors of boolean and scalars; the isVec parameter
595 /// selects between the two kinds. For example on X86 a scalar boolean should
596 /// be zero extended from i1, while the elements of a vector of booleans
597 /// should be sign extended from i1.
599 /// Some cpus also treat floating point types the same way as they treat
600 /// vectors instead of the way they treat scalars.
601 BooleanContent
getBooleanContents(bool isVec
, bool isFloat
) const {
603 return BooleanVectorContents
;
604 return isFloat
? BooleanFloatContents
: BooleanContents
;
607 BooleanContent
getBooleanContents(EVT Type
) const {
608 return getBooleanContents(Type
.isVector(), Type
.isFloatingPoint());
611 /// Return target scheduling preference.
612 Sched::Preference
getSchedulingPreference() const {
613 return SchedPreferenceInfo
;
616 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
617 /// for different nodes. This function returns the preference (or none) for
619 virtual Sched::Preference
getSchedulingPreference(SDNode
*) const {
623 /// Return the register class that should be used for the specified value
625 virtual const TargetRegisterClass
*getRegClassFor(MVT VT
) const {
626 const TargetRegisterClass
*RC
= RegClassForVT
[VT
.SimpleTy
];
627 assert(RC
&& "This value type is not natively supported!");
631 /// Return the 'representative' register class for the specified value
634 /// The 'representative' register class is the largest legal super-reg
635 /// register class for the register class of the value type. For example, on
636 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
637 /// register class is GR64 on x86_64.
638 virtual const TargetRegisterClass
*getRepRegClassFor(MVT VT
) const {
639 const TargetRegisterClass
*RC
= RepRegClassForVT
[VT
.SimpleTy
];
643 /// Return the cost of the 'representative' register class for the specified
645 virtual uint8_t getRepRegClassCostFor(MVT VT
) const {
646 return RepRegClassCostForVT
[VT
.SimpleTy
];
649 /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
650 /// instructions, and false if a library call is preferred (e.g for code-size
652 virtual bool shouldExpandShift(SelectionDAG
&DAG
, SDNode
*N
) const {
656 /// Return true if the target has native support for the specified value type.
657 /// This means that it has a register that directly holds it without
658 /// promotions or expansions.
659 bool isTypeLegal(EVT VT
) const {
660 assert(!VT
.isSimple() ||
661 (unsigned)VT
.getSimpleVT().SimpleTy
< array_lengthof(RegClassForVT
));
662 return VT
.isSimple() && RegClassForVT
[VT
.getSimpleVT().SimpleTy
] != nullptr;
665 class ValueTypeActionImpl
{
666 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
667 /// that indicates how instruction selection should deal with the type.
668 LegalizeTypeAction ValueTypeActions
[MVT::LAST_VALUETYPE
];
671 ValueTypeActionImpl() {
672 std::fill(std::begin(ValueTypeActions
), std::end(ValueTypeActions
),
676 LegalizeTypeAction
getTypeAction(MVT VT
) const {
677 return ValueTypeActions
[VT
.SimpleTy
];
680 void setTypeAction(MVT VT
, LegalizeTypeAction Action
) {
681 ValueTypeActions
[VT
.SimpleTy
] = Action
;
685 const ValueTypeActionImpl
&getValueTypeActions() const {
686 return ValueTypeActions
;
689 /// Return how we should legalize values of this type, either it is already
690 /// legal (return 'Legal') or we need to promote it to a larger type (return
691 /// 'Promote'), or we need to expand it into multiple registers of smaller
692 /// integer type (return 'Expand'). 'Custom' is not an option.
693 LegalizeTypeAction
getTypeAction(LLVMContext
&Context
, EVT VT
) const {
694 return getTypeConversion(Context
, VT
).first
;
696 LegalizeTypeAction
getTypeAction(MVT VT
) const {
697 return ValueTypeActions
.getTypeAction(VT
);
700 /// For types supported by the target, this is an identity function. For
701 /// types that must be promoted to larger types, this returns the larger type
702 /// to promote to. For integer types that are larger than the largest integer
703 /// register, this contains one step in the expansion to get to the smaller
704 /// register. For illegal floating point types, this returns the integer type
706 EVT
getTypeToTransformTo(LLVMContext
&Context
, EVT VT
) const {
707 return getTypeConversion(Context
, VT
).second
;
710 /// For types supported by the target, this is an identity function. For
711 /// types that must be expanded (i.e. integer types that are larger than the
712 /// largest integer register or illegal floating point types), this returns
713 /// the largest legal type it will be expanded to.
714 EVT
getTypeToExpandTo(LLVMContext
&Context
, EVT VT
) const {
715 assert(!VT
.isVector());
717 switch (getTypeAction(Context
, VT
)) {
720 case TypeExpandInteger
:
721 VT
= getTypeToTransformTo(Context
, VT
);
724 llvm_unreachable("Type is not legal nor is it to be expanded!");
729 /// Vector types are broken down into some number of legal first class types.
730 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
731 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
732 /// turns into 4 EVT::i32 values with both PPC and X86.
734 /// This method returns the number of registers needed, and the VT for each
735 /// register. It also returns the VT and quantity of the intermediate values
736 /// before they are promoted/expanded.
737 unsigned getVectorTypeBreakdown(LLVMContext
&Context
, EVT VT
,
739 unsigned &NumIntermediates
,
740 MVT
&RegisterVT
) const;
742 /// Certain targets such as MIPS require that some types such as vectors are
743 /// always broken down into scalars in some contexts. This occurs even if the
744 /// vector type is legal.
745 virtual unsigned getVectorTypeBreakdownForCallingConv(
746 LLVMContext
&Context
, CallingConv::ID CC
, EVT VT
, EVT
&IntermediateVT
,
747 unsigned &NumIntermediates
, MVT
&RegisterVT
) const {
748 return getVectorTypeBreakdown(Context
, VT
, IntermediateVT
, NumIntermediates
,
752 struct IntrinsicInfo
{
753 unsigned opc
= 0; // target opcode
754 EVT memVT
; // memory VT
756 // value representing memory location
757 PointerUnion
<const Value
*, const PseudoSourceValue
*> ptrVal
;
759 int offset
= 0; // offset off of ptrVal
760 unsigned size
= 0; // the size of the memory location
761 // (taken from memVT if zero)
762 unsigned align
= 1; // alignment
764 MachineMemOperand::Flags flags
= MachineMemOperand::MONone
;
765 IntrinsicInfo() = default;
768 /// Given an intrinsic, checks if on the target the intrinsic will need to map
769 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
770 /// true and store the intrinsic information into the IntrinsicInfo that was
771 /// passed to the function.
772 virtual bool getTgtMemIntrinsic(IntrinsicInfo
&, const CallInst
&,
774 unsigned /*Intrinsic*/) const {
778 /// Returns true if the target can instruction select the specified FP
779 /// immediate natively. If false, the legalizer will materialize the FP
780 /// immediate as a load from a constant pool.
781 virtual bool isFPImmLegal(const APFloat
&/*Imm*/, EVT
/*VT*/) const {
785 /// Targets can use this to indicate that they only support *some*
786 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
787 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
789 virtual bool isShuffleMaskLegal(ArrayRef
<int> /*Mask*/, EVT
/*VT*/) const {
793 /// Returns true if the operation can trap for the value type.
795 /// VT must be a legal type. By default, we optimistically assume most
796 /// operations don't trap except for integer divide and remainder.
797 virtual bool canOpTrap(unsigned Op
, EVT VT
) const;
799 /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
800 /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
801 /// constant pool entry.
802 virtual bool isVectorClearMaskLegal(ArrayRef
<int> /*Mask*/,
807 /// Return how this operation should be treated: either it is legal, needs to
808 /// be promoted to a larger size, needs to be expanded to some other code
809 /// sequence, or the target has a custom expander for it.
810 LegalizeAction
getOperationAction(unsigned Op
, EVT VT
) const {
811 if (VT
.isExtended()) return Expand
;
812 // If a target-specific SDNode requires legalization, require the target
813 // to provide custom legalization for it.
814 if (Op
>= array_lengthof(OpActions
[0])) return Custom
;
815 return OpActions
[(unsigned)VT
.getSimpleVT().SimpleTy
][Op
];
818 /// Custom method defined by each target to indicate if an operation which
819 /// may require a scale is supported natively by the target.
820 /// If not, the operation is illegal.
821 virtual bool isSupportedFixedPointOperation(unsigned Op
, EVT VT
,
822 unsigned Scale
) const {
826 /// Some fixed point operations may be natively supported by the target but
827 /// only for specific scales. This method allows for checking
828 /// if the width is supported by the target for a given operation that may
830 LegalizeAction
getFixedPointOperationAction(unsigned Op
, EVT VT
,
831 unsigned Scale
) const {
832 auto Action
= getOperationAction(Op
, VT
);
836 // This operation is supported in this type but may only work on specific
841 llvm_unreachable("Unexpected fixed point operation.");
844 Supported
= isSupportedFixedPointOperation(Op
, VT
, Scale
);
848 return Supported
? Action
: Expand
;
851 LegalizeAction
getStrictFPOperationAction(unsigned Op
, EVT VT
) const {
854 default: llvm_unreachable("Unexpected FP pseudo-opcode");
855 case ISD::STRICT_FADD
: EqOpc
= ISD::FADD
; break;
856 case ISD::STRICT_FSUB
: EqOpc
= ISD::FSUB
; break;
857 case ISD::STRICT_FMUL
: EqOpc
= ISD::FMUL
; break;
858 case ISD::STRICT_FDIV
: EqOpc
= ISD::FDIV
; break;
859 case ISD::STRICT_FREM
: EqOpc
= ISD::FREM
; break;
860 case ISD::STRICT_FSQRT
: EqOpc
= ISD::FSQRT
; break;
861 case ISD::STRICT_FPOW
: EqOpc
= ISD::FPOW
; break;
862 case ISD::STRICT_FPOWI
: EqOpc
= ISD::FPOWI
; break;
863 case ISD::STRICT_FMA
: EqOpc
= ISD::FMA
; break;
864 case ISD::STRICT_FSIN
: EqOpc
= ISD::FSIN
; break;
865 case ISD::STRICT_FCOS
: EqOpc
= ISD::FCOS
; break;
866 case ISD::STRICT_FEXP
: EqOpc
= ISD::FEXP
; break;
867 case ISD::STRICT_FEXP2
: EqOpc
= ISD::FEXP2
; break;
868 case ISD::STRICT_FLOG
: EqOpc
= ISD::FLOG
; break;
869 case ISD::STRICT_FLOG10
: EqOpc
= ISD::FLOG10
; break;
870 case ISD::STRICT_FLOG2
: EqOpc
= ISD::FLOG2
; break;
871 case ISD::STRICT_FRINT
: EqOpc
= ISD::FRINT
; break;
872 case ISD::STRICT_FNEARBYINT
: EqOpc
= ISD::FNEARBYINT
; break;
873 case ISD::STRICT_FMAXNUM
: EqOpc
= ISD::FMAXNUM
; break;
874 case ISD::STRICT_FMINNUM
: EqOpc
= ISD::FMINNUM
; break;
875 case ISD::STRICT_FCEIL
: EqOpc
= ISD::FCEIL
; break;
876 case ISD::STRICT_FFLOOR
: EqOpc
= ISD::FFLOOR
; break;
877 case ISD::STRICT_FROUND
: EqOpc
= ISD::FROUND
; break;
878 case ISD::STRICT_FTRUNC
: EqOpc
= ISD::FTRUNC
; break;
881 auto Action
= getOperationAction(EqOpc
, VT
);
883 // We don't currently handle Custom or Promote for strict FP pseudo-ops.
884 // For now, we just expand for those cases.
891 /// Return true if the specified operation is legal on this target or can be
892 /// made legal with custom lowering. This is used to help guide high-level
893 /// lowering decisions.
894 bool isOperationLegalOrCustom(unsigned Op
, EVT VT
) const {
895 return (VT
== MVT::Other
|| isTypeLegal(VT
)) &&
896 (getOperationAction(Op
, VT
) == Legal
||
897 getOperationAction(Op
, VT
) == Custom
);
900 /// Return true if the specified operation is legal on this target or can be
901 /// made legal using promotion. This is used to help guide high-level lowering
903 bool isOperationLegalOrPromote(unsigned Op
, EVT VT
) const {
904 return (VT
== MVT::Other
|| isTypeLegal(VT
)) &&
905 (getOperationAction(Op
, VT
) == Legal
||
906 getOperationAction(Op
, VT
) == Promote
);
909 /// Return true if the specified operation is legal on this target or can be
910 /// made legal with custom lowering or using promotion. This is used to help
911 /// guide high-level lowering decisions.
912 bool isOperationLegalOrCustomOrPromote(unsigned Op
, EVT VT
) const {
913 return (VT
== MVT::Other
|| isTypeLegal(VT
)) &&
914 (getOperationAction(Op
, VT
) == Legal
||
915 getOperationAction(Op
, VT
) == Custom
||
916 getOperationAction(Op
, VT
) == Promote
);
919 /// Return true if the operation uses custom lowering, regardless of whether
920 /// the type is legal or not.
921 bool isOperationCustom(unsigned Op
, EVT VT
) const {
922 return getOperationAction(Op
, VT
) == Custom
;
925 /// Return true if lowering to a jump table is allowed.
926 virtual bool areJTsAllowed(const Function
*Fn
) const {
927 if (Fn
->getFnAttribute("no-jump-tables").getValueAsString() == "true")
930 return isOperationLegalOrCustom(ISD::BR_JT
, MVT::Other
) ||
931 isOperationLegalOrCustom(ISD::BRIND
, MVT::Other
);
934 /// Check whether the range [Low,High] fits in a machine word.
935 bool rangeFitsInWord(const APInt
&Low
, const APInt
&High
,
936 const DataLayout
&DL
) const {
937 // FIXME: Using the pointer type doesn't seem ideal.
938 uint64_t BW
= DL
.getIndexSizeInBits(0u);
939 uint64_t Range
= (High
- Low
).getLimitedValue(UINT64_MAX
- 1) + 1;
943 /// Return true if lowering to a jump table is suitable for a set of case
944 /// clusters which may contain \p NumCases cases, \p Range range of values.
945 /// FIXME: This function check the maximum table size and density, but the
946 /// minimum size is not checked. It would be nice if the minimum size is
947 /// also combined within this function. Currently, the minimum size check is
948 /// performed in findJumpTable() in SelectionDAGBuiler and
949 /// getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
950 virtual bool isSuitableForJumpTable(const SwitchInst
*SI
, uint64_t NumCases
,
951 uint64_t Range
) const {
952 const bool OptForSize
= SI
->getParent()->getParent()->optForSize();
953 const unsigned MinDensity
= getMinimumJumpTableDensity(OptForSize
);
954 const unsigned MaxJumpTableSize
=
955 OptForSize
|| getMaximumJumpTableSize() == 0
957 : getMaximumJumpTableSize();
958 // Check whether a range of clusters is dense enough for a jump table.
959 if (Range
<= MaxJumpTableSize
&&
960 (NumCases
* 100 >= Range
* MinDensity
)) {
966 /// Return true if lowering to a bit test is suitable for a set of case
967 /// clusters which contains \p NumDests unique destinations, \p Low and
968 /// \p High as its lowest and highest case values, and expects \p NumCmps
969 /// case value comparisons. Check if the number of destinations, comparison
970 /// metric, and range are all suitable.
971 bool isSuitableForBitTests(unsigned NumDests
, unsigned NumCmps
,
972 const APInt
&Low
, const APInt
&High
,
973 const DataLayout
&DL
) const {
974 // FIXME: I don't think NumCmps is the correct metric: a single case and a
975 // range of cases both require only one branch to lower. Just looking at the
976 // number of clusters and destinations should be enough to decide whether to
979 // To lower a range with bit tests, the range must fit the bitwidth of a
981 if (!rangeFitsInWord(Low
, High
, DL
))
984 // Decide whether it's profitable to lower this range with bit tests. Each
985 // destination requires a bit test and branch, and there is an overall range
986 // check branch. For a small number of clusters, separate comparisons might
987 // be cheaper, and for many destinations, splitting the range might be
989 return (NumDests
== 1 && NumCmps
>= 3) || (NumDests
== 2 && NumCmps
>= 5) ||
990 (NumDests
== 3 && NumCmps
>= 6);
993 /// Return true if the specified operation is illegal on this target or
994 /// unlikely to be made legal with custom lowering. This is used to help guide
995 /// high-level lowering decisions.
996 bool isOperationExpand(unsigned Op
, EVT VT
) const {
997 return (!isTypeLegal(VT
) || getOperationAction(Op
, VT
) == Expand
);
1000 /// Return true if the specified operation is legal on this target.
1001 bool isOperationLegal(unsigned Op
, EVT VT
) const {
1002 return (VT
== MVT::Other
|| isTypeLegal(VT
)) &&
1003 getOperationAction(Op
, VT
) == Legal
;
1006 /// Return how this load with extension should be treated: either it is legal,
1007 /// needs to be promoted to a larger size, needs to be expanded to some other
1008 /// code sequence, or the target has a custom expander for it.
1009 LegalizeAction
getLoadExtAction(unsigned ExtType
, EVT ValVT
,
1011 if (ValVT
.isExtended() || MemVT
.isExtended()) return Expand
;
1012 unsigned ValI
= (unsigned) ValVT
.getSimpleVT().SimpleTy
;
1013 unsigned MemI
= (unsigned) MemVT
.getSimpleVT().SimpleTy
;
1014 assert(ExtType
< ISD::LAST_LOADEXT_TYPE
&& ValI
< MVT::LAST_VALUETYPE
&&
1015 MemI
< MVT::LAST_VALUETYPE
&& "Table isn't big enough!");
1016 unsigned Shift
= 4 * ExtType
;
1017 return (LegalizeAction
)((LoadExtActions
[ValI
][MemI
] >> Shift
) & 0xf);
1020 /// Return true if the specified load with extension is legal on this target.
1021 bool isLoadExtLegal(unsigned ExtType
, EVT ValVT
, EVT MemVT
) const {
1022 return getLoadExtAction(ExtType
, ValVT
, MemVT
) == Legal
;
1025 /// Return true if the specified load with extension is legal or custom
1027 bool isLoadExtLegalOrCustom(unsigned ExtType
, EVT ValVT
, EVT MemVT
) const {
1028 return getLoadExtAction(ExtType
, ValVT
, MemVT
) == Legal
||
1029 getLoadExtAction(ExtType
, ValVT
, MemVT
) == Custom
;
1032 /// Return how this store with truncation should be treated: either it is
1033 /// legal, needs to be promoted to a larger size, needs to be expanded to some
1034 /// other code sequence, or the target has a custom expander for it.
1035 LegalizeAction
getTruncStoreAction(EVT ValVT
, EVT MemVT
) const {
1036 if (ValVT
.isExtended() || MemVT
.isExtended()) return Expand
;
1037 unsigned ValI
= (unsigned) ValVT
.getSimpleVT().SimpleTy
;
1038 unsigned MemI
= (unsigned) MemVT
.getSimpleVT().SimpleTy
;
1039 assert(ValI
< MVT::LAST_VALUETYPE
&& MemI
< MVT::LAST_VALUETYPE
&&
1040 "Table isn't big enough!");
1041 return TruncStoreActions
[ValI
][MemI
];
1044 /// Return true if the specified store with truncation is legal on this
1046 bool isTruncStoreLegal(EVT ValVT
, EVT MemVT
) const {
1047 return isTypeLegal(ValVT
) && getTruncStoreAction(ValVT
, MemVT
) == Legal
;
1050 /// Return true if the specified store with truncation has solution on this
1052 bool isTruncStoreLegalOrCustom(EVT ValVT
, EVT MemVT
) const {
1053 return isTypeLegal(ValVT
) &&
1054 (getTruncStoreAction(ValVT
, MemVT
) == Legal
||
1055 getTruncStoreAction(ValVT
, MemVT
) == Custom
);
1058 /// Return how the indexed load should be treated: either it is legal, needs
1059 /// to be promoted to a larger size, needs to be expanded to some other code
1060 /// sequence, or the target has a custom expander for it.
1062 getIndexedLoadAction(unsigned IdxMode
, MVT VT
) const {
1063 assert(IdxMode
< ISD::LAST_INDEXED_MODE
&& VT
.isValid() &&
1064 "Table isn't big enough!");
1065 unsigned Ty
= (unsigned)VT
.SimpleTy
;
1066 return (LegalizeAction
)((IndexedModeActions
[Ty
][IdxMode
] & 0xf0) >> 4);
1069 /// Return true if the specified indexed load is legal on this target.
1070 bool isIndexedLoadLegal(unsigned IdxMode
, EVT VT
) const {
1071 return VT
.isSimple() &&
1072 (getIndexedLoadAction(IdxMode
, VT
.getSimpleVT()) == Legal
||
1073 getIndexedLoadAction(IdxMode
, VT
.getSimpleVT()) == Custom
);
1076 /// Return how the indexed store should be treated: either it is legal, needs
1077 /// to be promoted to a larger size, needs to be expanded to some other code
1078 /// sequence, or the target has a custom expander for it.
1080 getIndexedStoreAction(unsigned IdxMode
, MVT VT
) const {
1081 assert(IdxMode
< ISD::LAST_INDEXED_MODE
&& VT
.isValid() &&
1082 "Table isn't big enough!");
1083 unsigned Ty
= (unsigned)VT
.SimpleTy
;
1084 return (LegalizeAction
)(IndexedModeActions
[Ty
][IdxMode
] & 0x0f);
1087 /// Return true if the specified indexed load is legal on this target.
1088 bool isIndexedStoreLegal(unsigned IdxMode
, EVT VT
) const {
1089 return VT
.isSimple() &&
1090 (getIndexedStoreAction(IdxMode
, VT
.getSimpleVT()) == Legal
||
1091 getIndexedStoreAction(IdxMode
, VT
.getSimpleVT()) == Custom
);
1094 /// Return how the condition code should be treated: either it is legal, needs
1095 /// to be expanded to some other code sequence, or the target has a custom
1096 /// expander for it.
1098 getCondCodeAction(ISD::CondCode CC
, MVT VT
) const {
1099 assert((unsigned)CC
< array_lengthof(CondCodeActions
) &&
1100 ((unsigned)VT
.SimpleTy
>> 3) < array_lengthof(CondCodeActions
[0]) &&
1101 "Table isn't big enough!");
1102 // See setCondCodeAction for how this is encoded.
1103 uint32_t Shift
= 4 * (VT
.SimpleTy
& 0x7);
1104 uint32_t Value
= CondCodeActions
[CC
][VT
.SimpleTy
>> 3];
1105 LegalizeAction Action
= (LegalizeAction
) ((Value
>> Shift
) & 0xF);
1106 assert(Action
!= Promote
&& "Can't promote condition code!");
1110 /// Return true if the specified condition code is legal on this target.
1111 bool isCondCodeLegal(ISD::CondCode CC
, MVT VT
) const {
1112 return getCondCodeAction(CC
, VT
) == Legal
;
1115 /// Return true if the specified condition code is legal or custom on this
1117 bool isCondCodeLegalOrCustom(ISD::CondCode CC
, MVT VT
) const {
1118 return getCondCodeAction(CC
, VT
) == Legal
||
1119 getCondCodeAction(CC
, VT
) == Custom
;
1122 /// If the action for this operation is to promote, this method returns the
1123 /// ValueType to promote to.
1124 MVT
getTypeToPromoteTo(unsigned Op
, MVT VT
) const {
1125 assert(getOperationAction(Op
, VT
) == Promote
&&
1126 "This operation isn't promoted!");
1128 // See if this has an explicit type specified.
1129 std::map
<std::pair
<unsigned, MVT::SimpleValueType
>,
1130 MVT::SimpleValueType
>::const_iterator PTTI
=
1131 PromoteToType
.find(std::make_pair(Op
, VT
.SimpleTy
));
1132 if (PTTI
!= PromoteToType
.end()) return PTTI
->second
;
1134 assert((VT
.isInteger() || VT
.isFloatingPoint()) &&
1135 "Cannot autopromote this type, add it with AddPromotedToType.");
1139 NVT
= (MVT::SimpleValueType
)(NVT
.SimpleTy
+1);
1140 assert(NVT
.isInteger() == VT
.isInteger() && NVT
!= MVT::isVoid
&&
1141 "Didn't find type to promote to!");
1142 } while (!isTypeLegal(NVT
) ||
1143 getOperationAction(Op
, NVT
) == Promote
);
1147 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1148 /// operations except for the pointer size. If AllowUnknown is true, this
1149 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1150 /// otherwise it will assert.
1151 EVT
getValueType(const DataLayout
&DL
, Type
*Ty
,
1152 bool AllowUnknown
= false) const {
1153 // Lower scalar pointers to native pointer types.
1154 if (PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
))
1155 return getPointerTy(DL
, PTy
->getAddressSpace());
1157 if (Ty
->isVectorTy()) {
1158 VectorType
*VTy
= cast
<VectorType
>(Ty
);
1159 Type
*Elm
= VTy
->getElementType();
1160 // Lower vectors of pointers to native pointer types.
1161 if (PointerType
*PT
= dyn_cast
<PointerType
>(Elm
)) {
1162 EVT
PointerTy(getPointerTy(DL
, PT
->getAddressSpace()));
1163 Elm
= PointerTy
.getTypeForEVT(Ty
->getContext());
1166 return EVT::getVectorVT(Ty
->getContext(), EVT::getEVT(Elm
, false),
1167 VTy
->getNumElements());
1169 return EVT::getEVT(Ty
, AllowUnknown
);
1172 /// Return the MVT corresponding to this LLVM type. See getValueType.
1173 MVT
getSimpleValueType(const DataLayout
&DL
, Type
*Ty
,
1174 bool AllowUnknown
= false) const {
1175 return getValueType(DL
, Ty
, AllowUnknown
).getSimpleVT();
1178 /// Return the desired alignment for ByVal or InAlloca aggregate function
1179 /// arguments in the caller parameter area. This is the actual alignment, not
1181 virtual unsigned getByValTypeAlignment(Type
*Ty
, const DataLayout
&DL
) const;
1183 /// Return the type of registers that this ValueType will eventually require.
1184 MVT
getRegisterType(MVT VT
) const {
1185 assert((unsigned)VT
.SimpleTy
< array_lengthof(RegisterTypeForVT
));
1186 return RegisterTypeForVT
[VT
.SimpleTy
];
1189 /// Return the type of registers that this ValueType will eventually require.
1190 MVT
getRegisterType(LLVMContext
&Context
, EVT VT
) const {
1191 if (VT
.isSimple()) {
1192 assert((unsigned)VT
.getSimpleVT().SimpleTy
<
1193 array_lengthof(RegisterTypeForVT
));
1194 return RegisterTypeForVT
[VT
.getSimpleVT().SimpleTy
];
1196 if (VT
.isVector()) {
1199 unsigned NumIntermediates
;
1200 (void)getVectorTypeBreakdown(Context
, VT
, VT1
,
1201 NumIntermediates
, RegisterVT
);
1204 if (VT
.isInteger()) {
1205 return getRegisterType(Context
, getTypeToTransformTo(Context
, VT
));
1207 llvm_unreachable("Unsupported extended type!");
1210 /// Return the number of registers that this ValueType will eventually
1213 /// This is one for any types promoted to live in larger registers, but may be
1214 /// more than one for types (like i64) that are split into pieces. For types
1215 /// like i140, which are first promoted then expanded, it is the number of
1216 /// registers needed to hold all the bits of the original type. For an i140
1217 /// on a 32 bit machine this means 5 registers.
1218 unsigned getNumRegisters(LLVMContext
&Context
, EVT VT
) const {
1219 if (VT
.isSimple()) {
1220 assert((unsigned)VT
.getSimpleVT().SimpleTy
<
1221 array_lengthof(NumRegistersForVT
));
1222 return NumRegistersForVT
[VT
.getSimpleVT().SimpleTy
];
1224 if (VT
.isVector()) {
1227 unsigned NumIntermediates
;
1228 return getVectorTypeBreakdown(Context
, VT
, VT1
, NumIntermediates
, VT2
);
1230 if (VT
.isInteger()) {
1231 unsigned BitWidth
= VT
.getSizeInBits();
1232 unsigned RegWidth
= getRegisterType(Context
, VT
).getSizeInBits();
1233 return (BitWidth
+ RegWidth
- 1) / RegWidth
;
1235 llvm_unreachable("Unsupported extended type!");
1238 /// Certain combinations of ABIs, Targets and features require that types
1239 /// are legal for some operations and not for other operations.
1240 /// For MIPS all vector types must be passed through the integer register set.
1241 virtual MVT
getRegisterTypeForCallingConv(LLVMContext
&Context
,
1242 CallingConv::ID CC
, EVT VT
) const {
1243 return getRegisterType(Context
, VT
);
1246 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1247 /// this occurs when a vector type is used, as vector are passed through the
1248 /// integer register set.
1249 virtual unsigned getNumRegistersForCallingConv(LLVMContext
&Context
,
1252 return getNumRegisters(Context
, VT
);
1255 /// Certain targets have context senstive alignment requirements, where one
1256 /// type has the alignment requirement of another type.
1257 virtual unsigned getABIAlignmentForCallingConv(Type
*ArgTy
,
1258 DataLayout DL
) const {
1259 return DL
.getABITypeAlignment(ArgTy
);
1262 /// If true, then instruction selection should seek to shrink the FP constant
1263 /// of the specified type to a smaller type in order to save space and / or
1265 virtual bool ShouldShrinkFPConstant(EVT
) const { return true; }
1267 /// Return true if it is profitable to reduce a load to a smaller type.
1268 /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1269 virtual bool shouldReduceLoadWidth(SDNode
*Load
, ISD::LoadExtType ExtTy
,
1271 // By default, assume that it is cheaper to extract a subvector from a wide
1272 // vector load rather than creating multiple narrow vector loads.
1273 if (NewVT
.isVector() && !Load
->hasOneUse())
1279 /// When splitting a value of the specified type into parts, does the Lo
1280 /// or Hi part come first? This usually follows the endianness, except
1281 /// for ppcf128, where the Hi part always comes first.
1282 bool hasBigEndianPartOrdering(EVT VT
, const DataLayout
&DL
) const {
1283 return DL
.isBigEndian() || VT
== MVT::ppcf128
;
1286 /// If true, the target has custom DAG combine transformations that it can
1287 /// perform for the specified node.
1288 bool hasTargetDAGCombine(ISD::NodeType NT
) const {
1289 assert(unsigned(NT
>> 3) < array_lengthof(TargetDAGCombineArray
));
1290 return TargetDAGCombineArray
[NT
>> 3] & (1 << (NT
&7));
1293 unsigned getGatherAllAliasesMaxDepth() const {
1294 return GatherAllAliasesMaxDepth
;
1297 /// Returns the size of the platform's va_list object.
1298 virtual unsigned getVaListSizeInBits(const DataLayout
&DL
) const {
1299 return getPointerTy(DL
).getSizeInBits();
1302 /// Get maximum # of store operations permitted for llvm.memset
1304 /// This function returns the maximum number of store operations permitted
1305 /// to replace a call to llvm.memset. The value is set by the target at the
1306 /// performance threshold for such a replacement. If OptSize is true,
1307 /// return the limit for functions that have OptSize attribute.
1308 unsigned getMaxStoresPerMemset(bool OptSize
) const {
1309 return OptSize
? MaxStoresPerMemsetOptSize
: MaxStoresPerMemset
;
1312 /// Get maximum # of store operations permitted for llvm.memcpy
1314 /// This function returns the maximum number of store operations permitted
1315 /// to replace a call to llvm.memcpy. The value is set by the target at the
1316 /// performance threshold for such a replacement. If OptSize is true,
1317 /// return the limit for functions that have OptSize attribute.
1318 unsigned getMaxStoresPerMemcpy(bool OptSize
) const {
1319 return OptSize
? MaxStoresPerMemcpyOptSize
: MaxStoresPerMemcpy
;
1322 /// \brief Get maximum # of store operations to be glued together
1324 /// This function returns the maximum number of store operations permitted
1325 /// to glue together during lowering of llvm.memcpy. The value is set by
1326 // the target at the performance threshold for such a replacement.
1327 virtual unsigned getMaxGluedStoresPerMemcpy() const {
1328 return MaxGluedStoresPerMemcpy
;
1331 /// Get maximum # of load operations permitted for memcmp
1333 /// This function returns the maximum number of load operations permitted
1334 /// to replace a call to memcmp. The value is set by the target at the
1335 /// performance threshold for such a replacement. If OptSize is true,
1336 /// return the limit for functions that have OptSize attribute.
1337 unsigned getMaxExpandSizeMemcmp(bool OptSize
) const {
1338 return OptSize
? MaxLoadsPerMemcmpOptSize
: MaxLoadsPerMemcmp
;
1341 /// For memcmp expansion when the memcmp result is only compared equal or
1342 /// not-equal to 0, allow up to this number of load pairs per block. As an
1343 /// example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
1344 /// a0 = load2bytes &a[0]
1345 /// b0 = load2bytes &b[0]
1346 /// a2 = load1byte &a[2]
1347 /// b2 = load1byte &b[2]
1348 /// r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
1349 virtual unsigned getMemcmpEqZeroLoadsPerBlock() const {
1353 /// Get maximum # of store operations permitted for llvm.memmove
1355 /// This function returns the maximum number of store operations permitted
1356 /// to replace a call to llvm.memmove. The value is set by the target at the
1357 /// performance threshold for such a replacement. If OptSize is true,
1358 /// return the limit for functions that have OptSize attribute.
1359 unsigned getMaxStoresPerMemmove(bool OptSize
) const {
1360 return OptSize
? MaxStoresPerMemmoveOptSize
: MaxStoresPerMemmove
;
1363 /// Determine if the target supports unaligned memory accesses.
1365 /// This function returns true if the target allows unaligned memory accesses
1366 /// of the specified type in the given address space. If true, it also returns
1367 /// whether the unaligned memory access is "fast" in the last argument by
1368 /// reference. This is used, for example, in situations where an array
1369 /// copy/move/set is converted to a sequence of store operations. Its use
1370 /// helps to ensure that such replacements don't generate code that causes an
1371 /// alignment error (trap) on the target machine.
1372 virtual bool allowsMisalignedMemoryAccesses(EVT
,
1373 unsigned AddrSpace
= 0,
1375 bool * /*Fast*/ = nullptr) const {
1379 /// Return true if the target supports a memory access of this type for the
1380 /// given address space and alignment. If the access is allowed, the optional
1381 /// final parameter returns if the access is also fast (as defined by the
1383 bool allowsMemoryAccess(LLVMContext
&Context
, const DataLayout
&DL
, EVT VT
,
1384 unsigned AddrSpace
= 0, unsigned Alignment
= 1,
1385 bool *Fast
= nullptr) const;
1387 /// Returns the target specific optimal type for load and store operations as
1388 /// a result of memset, memcpy, and memmove lowering.
1390 /// If DstAlign is zero that means it's safe to destination alignment can
1391 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1392 /// a need to check it against alignment requirement, probably because the
1393 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1394 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1395 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1396 /// does not need to be loaded. It returns EVT::Other if the type should be
1397 /// determined using generic target-independent logic.
1398 virtual EVT
getOptimalMemOpType(uint64_t /*Size*/,
1399 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
1401 bool /*ZeroMemset*/,
1402 bool /*MemcpyStrSrc*/,
1403 MachineFunction
&/*MF*/) const {
1407 /// Returns true if it's safe to use load / store of the specified type to
1408 /// expand memcpy / memset inline.
1410 /// This is mostly true for all types except for some special cases. For
1411 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1412 /// fstpl which also does type conversion. Note the specified type doesn't
1413 /// have to be legal as the hook is used before type legalization.
1414 virtual bool isSafeMemOpType(MVT
/*VT*/) const { return true; }
1416 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1417 bool usesUnderscoreSetJmp() const {
1418 return UseUnderscoreSetJmp
;
1421 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1422 bool usesUnderscoreLongJmp() const {
1423 return UseUnderscoreLongJmp
;
1426 /// Return lower limit for number of blocks in a jump table.
1427 virtual unsigned getMinimumJumpTableEntries() const;
1429 /// Return lower limit of the density in a jump table.
1430 unsigned getMinimumJumpTableDensity(bool OptForSize
) const;
1432 /// Return upper limit for number of entries in a jump table.
1433 /// Zero if no limit.
1434 unsigned getMaximumJumpTableSize() const;
1436 virtual bool isJumpTableRelative() const {
1437 return TM
.isPositionIndependent();
1440 /// If a physical register, this specifies the register that
1441 /// llvm.savestack/llvm.restorestack should save and restore.
1442 unsigned getStackPointerRegisterToSaveRestore() const {
1443 return StackPointerRegisterToSaveRestore
;
1446 /// If a physical register, this returns the register that receives the
1447 /// exception address on entry to an EH pad.
1449 getExceptionPointerRegister(const Constant
*PersonalityFn
) const {
1450 // 0 is guaranteed to be the NoRegister value on all targets
1454 /// If a physical register, this returns the register that receives the
1455 /// exception typeid on entry to a landing pad.
1457 getExceptionSelectorRegister(const Constant
*PersonalityFn
) const {
1458 // 0 is guaranteed to be the NoRegister value on all targets
1462 virtual bool needsFixedCatchObjects() const {
1463 report_fatal_error("Funclet EH is not implemented for this target");
1466 /// Returns the target's jmp_buf size in bytes (if never set, the default is
1468 unsigned getJumpBufSize() const {
1472 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1474 unsigned getJumpBufAlignment() const {
1475 return JumpBufAlignment
;
1478 /// Return the minimum stack alignment of an argument.
1479 unsigned getMinStackArgumentAlignment() const {
1480 return MinStackArgumentAlignment
;
1483 /// Return the minimum function alignment.
1484 unsigned getMinFunctionAlignment() const {
1485 return MinFunctionAlignment
;
1488 /// Return the preferred function alignment.
1489 unsigned getPrefFunctionAlignment() const {
1490 return PrefFunctionAlignment
;
1493 /// Return the preferred loop alignment.
1494 virtual unsigned getPrefLoopAlignment(MachineLoop
*ML
= nullptr) const {
1495 return PrefLoopAlignment
;
1498 /// Should loops be aligned even when the function is marked OptSize (but not
1500 virtual bool alignLoopsWithOptSize() const {
1504 /// If the target has a standard location for the stack protector guard,
1505 /// returns the address of that location. Otherwise, returns nullptr.
1506 /// DEPRECATED: please override useLoadStackGuardNode and customize
1507 /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1508 virtual Value
*getIRStackGuard(IRBuilder
<> &IRB
) const;
1510 /// Inserts necessary declarations for SSP (stack protection) purpose.
1511 /// Should be used only when getIRStackGuard returns nullptr.
1512 virtual void insertSSPDeclarations(Module
&M
) const;
1514 /// Return the variable that's previously inserted by insertSSPDeclarations,
1515 /// if any, otherwise return nullptr. Should be used only when
1516 /// getIRStackGuard returns nullptr.
1517 virtual Value
*getSDagStackGuard(const Module
&M
) const;
1519 /// If this function returns true, stack protection checks should XOR the
1520 /// frame pointer (or whichever pointer is used to address locals) into the
1521 /// stack guard value before checking it. getIRStackGuard must return nullptr
1522 /// if this returns true.
1523 virtual bool useStackGuardXorFP() const { return false; }
1525 /// If the target has a standard stack protection check function that
1526 /// performs validation and error handling, returns the function. Otherwise,
1527 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1528 /// Should be used only when getIRStackGuard returns nullptr.
1529 virtual Function
*getSSPStackGuardCheck(const Module
&M
) const;
1532 Value
*getDefaultSafeStackPointerLocation(IRBuilder
<> &IRB
,
1536 /// Returns the target-specific address of the unsafe stack pointer.
1537 virtual Value
*getSafeStackPointerLocation(IRBuilder
<> &IRB
) const;
1539 /// Returns the name of the symbol used to emit stack probes or the empty
1540 /// string if not applicable.
1541 virtual StringRef
getStackProbeSymbolName(MachineFunction
&MF
) const {
1545 /// Returns true if a cast between SrcAS and DestAS is a noop.
1546 virtual bool isNoopAddrSpaceCast(unsigned SrcAS
, unsigned DestAS
) const {
1550 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1551 /// are happy to sink it into basic blocks.
1552 virtual bool isCheapAddrSpaceCast(unsigned SrcAS
, unsigned DestAS
) const {
1553 return isNoopAddrSpaceCast(SrcAS
, DestAS
);
1556 /// Return true if the pointer arguments to CI should be aligned by aligning
1557 /// the object whose address is being passed. If so then MinSize is set to the
1558 /// minimum size the object must be to be aligned and PrefAlign is set to the
1559 /// preferred alignment.
1560 virtual bool shouldAlignPointerArgs(CallInst
* /*CI*/, unsigned & /*MinSize*/,
1561 unsigned & /*PrefAlign*/) const {
1565 //===--------------------------------------------------------------------===//
1566 /// \name Helpers for TargetTransformInfo implementations
1569 /// Get the ISD node that corresponds to the Instruction class opcode.
1570 int InstructionOpcodeToISD(unsigned Opcode
) const;
1572 /// Estimate the cost of type-legalization and the legalized type.
1573 std::pair
<int, MVT
> getTypeLegalizationCost(const DataLayout
&DL
,
1578 //===--------------------------------------------------------------------===//
1579 /// \name Helpers for atomic expansion.
1582 /// Returns the maximum atomic operation size (in bits) supported by
1583 /// the backend. Atomic operations greater than this size (as well
1584 /// as ones that are not naturally aligned), will be expanded by
1585 /// AtomicExpandPass into an __atomic_* library call.
1586 unsigned getMaxAtomicSizeInBitsSupported() const {
1587 return MaxAtomicSizeInBitsSupported
;
1590 /// Returns the size of the smallest cmpxchg or ll/sc instruction
1591 /// the backend supports. Any smaller operations are widened in
1592 /// AtomicExpandPass.
1594 /// Note that *unlike* operations above the maximum size, atomic ops
1595 /// are still natively supported below the minimum; they just
1596 /// require a more complex expansion.
1597 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits
; }
1599 /// Whether the target supports unaligned atomic operations.
1600 bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics
; }
1602 /// Whether AtomicExpandPass should automatically insert fences and reduce
1603 /// ordering for this atomic. This should be true for most architectures with
1604 /// weak memory ordering. Defaults to false.
1605 virtual bool shouldInsertFencesForAtomic(const Instruction
*I
) const {
1609 /// Perform a load-linked operation on Addr, returning a "Value *" with the
1610 /// corresponding pointee type. This may entail some non-trivial operations to
1611 /// truncate or reconstruct types that will be illegal in the backend. See
1612 /// ARMISelLowering for an example implementation.
1613 virtual Value
*emitLoadLinked(IRBuilder
<> &Builder
, Value
*Addr
,
1614 AtomicOrdering Ord
) const {
1615 llvm_unreachable("Load linked unimplemented on this target");
1618 /// Perform a store-conditional operation to Addr. Return the status of the
1619 /// store. This should be 0 if the store succeeded, non-zero otherwise.
1620 virtual Value
*emitStoreConditional(IRBuilder
<> &Builder
, Value
*Val
,
1621 Value
*Addr
, AtomicOrdering Ord
) const {
1622 llvm_unreachable("Store conditional unimplemented on this target");
1625 /// Perform a masked atomicrmw using a target-specific intrinsic. This
1626 /// represents the core LL/SC loop which will be lowered at a late stage by
1628 virtual Value
*emitMaskedAtomicRMWIntrinsic(IRBuilder
<> &Builder
,
1630 Value
*AlignedAddr
, Value
*Incr
,
1631 Value
*Mask
, Value
*ShiftAmt
,
1632 AtomicOrdering Ord
) const {
1633 llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
1636 /// Perform a masked cmpxchg using a target-specific intrinsic. This
1637 /// represents the core LL/SC loop which will be lowered at a late stage by
1639 virtual Value
*emitMaskedAtomicCmpXchgIntrinsic(
1640 IRBuilder
<> &Builder
, AtomicCmpXchgInst
*CI
, Value
*AlignedAddr
,
1641 Value
*CmpVal
, Value
*NewVal
, Value
*Mask
, AtomicOrdering Ord
) const {
1642 llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
1645 /// Inserts in the IR a target-specific intrinsic specifying a fence.
1646 /// It is called by AtomicExpandPass before expanding an
1647 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1648 /// if shouldInsertFencesForAtomic returns true.
1650 /// Inst is the original atomic instruction, prior to other expansions that
1651 /// may be performed.
1653 /// This function should either return a nullptr, or a pointer to an IR-level
1654 /// Instruction*. Even complex fence sequences can be represented by a
1655 /// single Instruction* through an intrinsic to be lowered later.
1656 /// Backends should override this method to produce target-specific intrinsic
1657 /// for their fences.
1658 /// FIXME: Please note that the default implementation here in terms of
1659 /// IR-level fences exists for historical/compatibility reasons and is
1660 /// *unsound* ! Fences cannot, in general, be used to restore sequential
1661 /// consistency. For example, consider the following example:
1662 /// atomic<int> x = y = 0;
1663 /// int r1, r2, r3, r4;
1674 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1675 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1676 /// IR-level fences can prevent it.
1678 virtual Instruction
*emitLeadingFence(IRBuilder
<> &Builder
, Instruction
*Inst
,
1679 AtomicOrdering Ord
) const {
1680 if (isReleaseOrStronger(Ord
) && Inst
->hasAtomicStore())
1681 return Builder
.CreateFence(Ord
);
1686 virtual Instruction
*emitTrailingFence(IRBuilder
<> &Builder
,
1688 AtomicOrdering Ord
) const {
1689 if (isAcquireOrStronger(Ord
))
1690 return Builder
.CreateFence(Ord
);
1696 // Emits code that executes when the comparison result in the ll/sc
1697 // expansion of a cmpxchg instruction is such that the store-conditional will
1698 // not execute. This makes it possible to balance out the load-linked with
1699 // a dedicated instruction, if desired.
1700 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1701 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1702 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder
<> &Builder
) const {}
1704 /// Returns true if the given (atomic) store should be expanded by the
1705 /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1706 virtual bool shouldExpandAtomicStoreInIR(StoreInst
*SI
) const {
1710 /// Returns true if arguments should be sign-extended in lib calls.
1711 virtual bool shouldSignExtendTypeInLibCall(EVT Type
, bool IsSigned
) const {
1715 /// Returns how the given (atomic) load should be expanded by the
1716 /// IR-level AtomicExpand pass.
1717 virtual AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst
*LI
) const {
1718 return AtomicExpansionKind::None
;
1721 /// Returns how the given atomic cmpxchg should be expanded by the IR-level
1722 /// AtomicExpand pass.
1723 virtual AtomicExpansionKind
1724 shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst
*AI
) const {
1725 return AtomicExpansionKind::None
;
1728 /// Returns how the IR-level AtomicExpand pass should expand the given
1729 /// AtomicRMW, if at all. Default is to never expand.
1730 virtual AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst
*RMW
) const {
1731 return RMW
->isFloatingPointOperation() ?
1732 AtomicExpansionKind::CmpXChg
: AtomicExpansionKind::None
;
1735 /// On some platforms, an AtomicRMW that never actually modifies the value
1736 /// (such as fetch_add of 0) can be turned into a fence followed by an
1737 /// atomic load. This may sound useless, but it makes it possible for the
1738 /// processor to keep the cacheline shared, dramatically improving
1739 /// performance. And such idempotent RMWs are useful for implementing some
1740 /// kinds of locks, see for example (justification + benchmarks):
1741 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1742 /// This method tries doing that transformation, returning the atomic load if
1743 /// it succeeds, and nullptr otherwise.
1744 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1745 /// another round of expansion.
1747 lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst
*RMWI
) const {
1751 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1752 /// SIGN_EXTEND, or ANY_EXTEND).
1753 virtual ISD::NodeType
getExtendForAtomicOps() const {
1754 return ISD::ZERO_EXTEND
;
1759 /// Returns true if we should normalize
1760 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1761 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1762 /// that it saves us from materializing N0 and N1 in an integer register.
1763 /// Targets that are able to perform and/or on flags should return false here.
1764 virtual bool shouldNormalizeToSelectSequence(LLVMContext
&Context
,
1766 // If a target has multiple condition registers, then it likely has logical
1767 // operations on those registers.
1768 if (hasMultipleConditionRegisters())
1770 // Only do the transform if the value won't be split into multiple
1772 LegalizeTypeAction Action
= getTypeAction(Context
, VT
);
1773 return Action
!= TypeExpandInteger
&& Action
!= TypeExpandFloat
&&
1774 Action
!= TypeSplitVector
;
1777 virtual bool isProfitableToCombineMinNumMaxNum(EVT VT
) const { return true; }
1779 /// Return true if a select of constants (select Cond, C1, C2) should be
1780 /// transformed into simple math ops with the condition value. For example:
1781 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1782 virtual bool convertSelectOfConstantsToMath(EVT VT
) const {
1786 /// Return true if it is profitable to transform an integer
1787 /// multiplication-by-constant into simpler operations like shifts and adds.
1788 /// This may be true if the target does not directly support the
1789 /// multiplication operation for the specified type or the sequence of simpler
1790 /// ops is faster than the multiply.
1791 virtual bool decomposeMulByConstant(EVT VT
, SDValue C
) const {
1795 /// Return true if it is more correct/profitable to use strict FP_TO_INT
1796 /// conversion operations - canonicalizing the FP source value instead of
1797 /// converting all cases and then selecting based on value.
1798 /// This may be true if the target throws exceptions for out of bounds
1799 /// conversions or has fast FP CMOV.
1800 virtual bool shouldUseStrictFP_TO_INT(EVT FpVT
, EVT IntVT
,
1801 bool IsSigned
) const {
1805 //===--------------------------------------------------------------------===//
1806 // TargetLowering Configuration Methods - These methods should be invoked by
1807 // the derived class constructor to configure this object for the target.
1810 /// Specify how the target extends the result of integer and floating point
1811 /// boolean values from i1 to a wider type. See getBooleanContents.
1812 void setBooleanContents(BooleanContent Ty
) {
1813 BooleanContents
= Ty
;
1814 BooleanFloatContents
= Ty
;
1817 /// Specify how the target extends the result of integer and floating point
1818 /// boolean values from i1 to a wider type. See getBooleanContents.
1819 void setBooleanContents(BooleanContent IntTy
, BooleanContent FloatTy
) {
1820 BooleanContents
= IntTy
;
1821 BooleanFloatContents
= FloatTy
;
1824 /// Specify how the target extends the result of a vector boolean value from a
1825 /// vector of i1 to a wider type. See getBooleanContents.
1826 void setBooleanVectorContents(BooleanContent Ty
) {
1827 BooleanVectorContents
= Ty
;
1830 /// Specify the target scheduling preference.
1831 void setSchedulingPreference(Sched::Preference Pref
) {
1832 SchedPreferenceInfo
= Pref
;
1835 /// Indicate whether this target prefers to use _setjmp to implement
1836 /// llvm.setjmp or the version without _. Defaults to false.
1837 void setUseUnderscoreSetJmp(bool Val
) {
1838 UseUnderscoreSetJmp
= Val
;
1841 /// Indicate whether this target prefers to use _longjmp to implement
1842 /// llvm.longjmp or the version without _. Defaults to false.
1843 void setUseUnderscoreLongJmp(bool Val
) {
1844 UseUnderscoreLongJmp
= Val
;
1847 /// Indicate the minimum number of blocks to generate jump tables.
1848 void setMinimumJumpTableEntries(unsigned Val
);
1850 /// Indicate the maximum number of entries in jump tables.
1851 /// Set to zero to generate unlimited jump tables.
1852 void setMaximumJumpTableSize(unsigned);
1854 /// If set to a physical register, this specifies the register that
1855 /// llvm.savestack/llvm.restorestack should save and restore.
1856 void setStackPointerRegisterToSaveRestore(unsigned R
) {
1857 StackPointerRegisterToSaveRestore
= R
;
1860 /// Tells the code generator that the target has multiple (allocatable)
1861 /// condition registers that can be used to store the results of comparisons
1862 /// for use by selects and conditional branches. With multiple condition
1863 /// registers, the code generator will not aggressively sink comparisons into
1864 /// the blocks of their users.
1865 void setHasMultipleConditionRegisters(bool hasManyRegs
= true) {
1866 HasMultipleConditionRegisters
= hasManyRegs
;
1869 /// Tells the code generator that the target has BitExtract instructions.
1870 /// The code generator will aggressively sink "shift"s into the blocks of
1871 /// their users if the users will generate "and" instructions which can be
1872 /// combined with "shift" to BitExtract instructions.
1873 void setHasExtractBitsInsn(bool hasExtractInsn
= true) {
1874 HasExtractBitsInsn
= hasExtractInsn
;
1877 /// Tells the code generator not to expand logic operations on comparison
1878 /// predicates into separate sequences that increase the amount of flow
1880 void setJumpIsExpensive(bool isExpensive
= true);
1882 /// Tells the code generator that this target supports floating point
1883 /// exceptions and cares about preserving floating point exception behavior.
1884 void setHasFloatingPointExceptions(bool FPExceptions
= true) {
1885 HasFloatingPointExceptions
= FPExceptions
;
1888 /// Tells the code generator which bitwidths to bypass.
1889 void addBypassSlowDiv(unsigned int SlowBitWidth
, unsigned int FastBitWidth
) {
1890 BypassSlowDivWidths
[SlowBitWidth
] = FastBitWidth
;
1893 /// Add the specified register class as an available regclass for the
1894 /// specified value type. This indicates the selector can handle values of
1895 /// that class natively.
1896 void addRegisterClass(MVT VT
, const TargetRegisterClass
*RC
) {
1897 assert((unsigned)VT
.SimpleTy
< array_lengthof(RegClassForVT
));
1898 RegClassForVT
[VT
.SimpleTy
] = RC
;
1901 /// Return the largest legal super-reg register class of the register class
1902 /// for the specified type and its associated "cost".
1903 virtual std::pair
<const TargetRegisterClass
*, uint8_t>
1904 findRepresentativeClass(const TargetRegisterInfo
*TRI
, MVT VT
) const;
1906 /// Once all of the register classes are added, this allows us to compute
1907 /// derived properties we expose.
1908 void computeRegisterProperties(const TargetRegisterInfo
*TRI
);
1910 /// Indicate that the specified operation does not work with the specified
1911 /// type and indicate what to do about it. Note that VT may refer to either
1912 /// the type of a result or that of an operand of Op.
1913 void setOperationAction(unsigned Op
, MVT VT
,
1914 LegalizeAction Action
) {
1915 assert(Op
< array_lengthof(OpActions
[0]) && "Table isn't big enough!");
1916 OpActions
[(unsigned)VT
.SimpleTy
][Op
] = Action
;
1919 /// Indicate that the specified load with extension does not work with the
1920 /// specified type and indicate what to do about it.
1921 void setLoadExtAction(unsigned ExtType
, MVT ValVT
, MVT MemVT
,
1922 LegalizeAction Action
) {
1923 assert(ExtType
< ISD::LAST_LOADEXT_TYPE
&& ValVT
.isValid() &&
1924 MemVT
.isValid() && "Table isn't big enough!");
1925 assert((unsigned)Action
< 0x10 && "too many bits for bitfield array");
1926 unsigned Shift
= 4 * ExtType
;
1927 LoadExtActions
[ValVT
.SimpleTy
][MemVT
.SimpleTy
] &= ~((uint16_t)0xF << Shift
);
1928 LoadExtActions
[ValVT
.SimpleTy
][MemVT
.SimpleTy
] |= (uint16_t)Action
<< Shift
;
1931 /// Indicate that the specified truncating store does not work with the
1932 /// specified type and indicate what to do about it.
1933 void setTruncStoreAction(MVT ValVT
, MVT MemVT
,
1934 LegalizeAction Action
) {
1935 assert(ValVT
.isValid() && MemVT
.isValid() && "Table isn't big enough!");
1936 TruncStoreActions
[(unsigned)ValVT
.SimpleTy
][MemVT
.SimpleTy
] = Action
;
1939 /// Indicate that the specified indexed load does or does not work with the
1940 /// specified type and indicate what to do abort it.
1942 /// NOTE: All indexed mode loads are initialized to Expand in
1943 /// TargetLowering.cpp
1944 void setIndexedLoadAction(unsigned IdxMode
, MVT VT
,
1945 LegalizeAction Action
) {
1946 assert(VT
.isValid() && IdxMode
< ISD::LAST_INDEXED_MODE
&&
1947 (unsigned)Action
< 0xf && "Table isn't big enough!");
1948 // Load action are kept in the upper half.
1949 IndexedModeActions
[(unsigned)VT
.SimpleTy
][IdxMode
] &= ~0xf0;
1950 IndexedModeActions
[(unsigned)VT
.SimpleTy
][IdxMode
] |= ((uint8_t)Action
) <<4;
1953 /// Indicate that the specified indexed store does or does not work with the
1954 /// specified type and indicate what to do about it.
1956 /// NOTE: All indexed mode stores are initialized to Expand in
1957 /// TargetLowering.cpp
1958 void setIndexedStoreAction(unsigned IdxMode
, MVT VT
,
1959 LegalizeAction Action
) {
1960 assert(VT
.isValid() && IdxMode
< ISD::LAST_INDEXED_MODE
&&
1961 (unsigned)Action
< 0xf && "Table isn't big enough!");
1962 // Store action are kept in the lower half.
1963 IndexedModeActions
[(unsigned)VT
.SimpleTy
][IdxMode
] &= ~0x0f;
1964 IndexedModeActions
[(unsigned)VT
.SimpleTy
][IdxMode
] |= ((uint8_t)Action
);
1967 /// Indicate that the specified condition code is or isn't supported on the
1968 /// target and indicate what to do about it.
1969 void setCondCodeAction(ISD::CondCode CC
, MVT VT
,
1970 LegalizeAction Action
) {
1971 assert(VT
.isValid() && (unsigned)CC
< array_lengthof(CondCodeActions
) &&
1972 "Table isn't big enough!");
1973 assert((unsigned)Action
< 0x10 && "too many bits for bitfield array");
1974 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
1975 /// value and the upper 29 bits index into the second dimension of the array
1976 /// to select what 32-bit value to use.
1977 uint32_t Shift
= 4 * (VT
.SimpleTy
& 0x7);
1978 CondCodeActions
[CC
][VT
.SimpleTy
>> 3] &= ~((uint32_t)0xF << Shift
);
1979 CondCodeActions
[CC
][VT
.SimpleTy
>> 3] |= (uint32_t)Action
<< Shift
;
1982 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1983 /// to trying a larger integer/fp until it can find one that works. If that
1984 /// default is insufficient, this method can be used by the target to override
1986 void AddPromotedToType(unsigned Opc
, MVT OrigVT
, MVT DestVT
) {
1987 PromoteToType
[std::make_pair(Opc
, OrigVT
.SimpleTy
)] = DestVT
.SimpleTy
;
1990 /// Convenience method to set an operation to Promote and specify the type
1991 /// in a single call.
1992 void setOperationPromotedToType(unsigned Opc
, MVT OrigVT
, MVT DestVT
) {
1993 setOperationAction(Opc
, OrigVT
, Promote
);
1994 AddPromotedToType(Opc
, OrigVT
, DestVT
);
1997 /// Targets should invoke this method for each target independent node that
1998 /// they want to provide a custom DAG combiner for by implementing the
1999 /// PerformDAGCombine virtual method.
2000 void setTargetDAGCombine(ISD::NodeType NT
) {
2001 assert(unsigned(NT
>> 3) < array_lengthof(TargetDAGCombineArray
));
2002 TargetDAGCombineArray
[NT
>> 3] |= 1 << (NT
&7);
2005 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
2006 void setJumpBufSize(unsigned Size
) {
2010 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
2012 void setJumpBufAlignment(unsigned Align
) {
2013 JumpBufAlignment
= Align
;
2016 /// Set the target's minimum function alignment (in log2(bytes))
2017 void setMinFunctionAlignment(unsigned Align
) {
2018 MinFunctionAlignment
= Align
;
2021 /// Set the target's preferred function alignment. This should be set if
2022 /// there is a performance benefit to higher-than-minimum alignment (in
2024 void setPrefFunctionAlignment(unsigned Align
) {
2025 PrefFunctionAlignment
= Align
;
2028 /// Set the target's preferred loop alignment. Default alignment is zero, it
2029 /// means the target does not care about loop alignment. The alignment is
2030 /// specified in log2(bytes). The target may also override
2031 /// getPrefLoopAlignment to provide per-loop values.
2032 void setPrefLoopAlignment(unsigned Align
) {
2033 PrefLoopAlignment
= Align
;
2036 /// Set the minimum stack alignment of an argument (in log2(bytes)).
2037 void setMinStackArgumentAlignment(unsigned Align
) {
2038 MinStackArgumentAlignment
= Align
;
2041 /// Set the maximum atomic operation size supported by the
2042 /// backend. Atomic operations greater than this size (as well as
2043 /// ones that are not naturally aligned), will be expanded by
2044 /// AtomicExpandPass into an __atomic_* library call.
2045 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits
) {
2046 MaxAtomicSizeInBitsSupported
= SizeInBits
;
2049 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2050 void setMinCmpXchgSizeInBits(unsigned SizeInBits
) {
2051 MinCmpXchgSizeInBits
= SizeInBits
;
2054 /// Sets whether unaligned atomic operations are supported.
2055 void setSupportsUnalignedAtomics(bool UnalignedSupported
) {
2056 SupportsUnalignedAtomics
= UnalignedSupported
;
2060 //===--------------------------------------------------------------------===//
2061 // Addressing mode description hooks (used by LSR etc).
2064 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2065 /// instructions reading the address. This allows as much computation as
2066 /// possible to be done in the address mode for that operand. This hook lets
2067 /// targets also pass back when this should be done on intrinsics which
2069 virtual bool getAddrModeArguments(IntrinsicInst
* /*I*/,
2070 SmallVectorImpl
<Value
*> &/*Ops*/,
2071 Type
*&/*AccessTy*/) const {
2075 /// This represents an addressing mode of:
2076 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2077 /// If BaseGV is null, there is no BaseGV.
2078 /// If BaseOffs is zero, there is no base offset.
2079 /// If HasBaseReg is false, there is no base register.
2080 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2083 GlobalValue
*BaseGV
= nullptr;
2084 int64_t BaseOffs
= 0;
2085 bool HasBaseReg
= false;
2087 AddrMode() = default;
2090 /// Return true if the addressing mode represented by AM is legal for this
2091 /// target, for a load/store of the specified type.
2093 /// The type may be VoidTy, in which case only return true if the addressing
2094 /// mode is legal for a load/store of any legal type. TODO: Handle
2095 /// pre/postinc as well.
2097 /// If the address space cannot be determined, it will be -1.
2099 /// TODO: Remove default argument
2100 virtual bool isLegalAddressingMode(const DataLayout
&DL
, const AddrMode
&AM
,
2101 Type
*Ty
, unsigned AddrSpace
,
2102 Instruction
*I
= nullptr) const;
2104 /// Return the cost of the scaling factor used in the addressing mode
2105 /// represented by AM for this target, for a load/store of the specified type.
2107 /// If the AM is supported, the return value must be >= 0.
2108 /// If the AM is not supported, it returns a negative value.
2109 /// TODO: Handle pre/postinc as well.
2110 /// TODO: Remove default argument
2111 virtual int getScalingFactorCost(const DataLayout
&DL
, const AddrMode
&AM
,
2112 Type
*Ty
, unsigned AS
= 0) const {
2113 // Default: assume that any scaling factor used in a legal AM is free.
2114 if (isLegalAddressingMode(DL
, AM
, Ty
, AS
))
2119 /// Return true if the specified immediate is legal icmp immediate, that is
2120 /// the target has icmp instructions which can compare a register against the
2121 /// immediate without having to materialize the immediate into a register.
2122 virtual bool isLegalICmpImmediate(int64_t) const {
2126 /// Return true if the specified immediate is legal add immediate, that is the
2127 /// target has add instructions which can add a register with the immediate
2128 /// without having to materialize the immediate into a register.
2129 virtual bool isLegalAddImmediate(int64_t) const {
2133 /// Return true if the specified immediate is legal for the value input of a
2134 /// store instruction.
2135 virtual bool isLegalStoreImmediate(int64_t Value
) const {
2136 // Default implementation assumes that at least 0 works since it is likely
2137 // that a zero register exists or a zero immediate is allowed.
2141 /// Return true if it's significantly cheaper to shift a vector by a uniform
2142 /// scalar than by an amount which will vary across each lane. On x86, for
2143 /// example, there is a "psllw" instruction for the former case, but no simple
2144 /// instruction for a general "a << b" operation on vectors.
2145 virtual bool isVectorShiftByScalarCheap(Type
*Ty
) const {
2149 /// Returns true if the opcode is a commutative binary operation.
2150 virtual bool isCommutativeBinOp(unsigned Opcode
) const {
2151 // FIXME: This should get its info from the td file.
2161 case ISD::SMUL_LOHI
:
2162 case ISD::UMUL_LOHI
:
2179 default: return false;
2183 /// Return true if it's free to truncate a value of type FromTy to type
2184 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2185 /// by referencing its sub-register AX.
2186 /// Targets must return false when FromTy <= ToTy.
2187 virtual bool isTruncateFree(Type
*FromTy
, Type
*ToTy
) const {
2191 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2192 /// whether a call is in tail position. Typically this means that both results
2193 /// would be assigned to the same register or stack slot, but it could mean
2194 /// the target performs adequate checks of its own before proceeding with the
2195 /// tail call. Targets must return false when FromTy <= ToTy.
2196 virtual bool allowTruncateForTailCall(Type
*FromTy
, Type
*ToTy
) const {
2200 virtual bool isTruncateFree(EVT FromVT
, EVT ToVT
) const {
2204 virtual bool isProfitableToHoist(Instruction
*I
) const { return true; }
2206 /// Return true if the extension represented by \p I is free.
2207 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2208 /// this method can use the context provided by \p I to decide
2209 /// whether or not \p I is free.
2210 /// This method extends the behavior of the is[Z|FP]ExtFree family.
2211 /// In other words, if is[Z|FP]Free returns true, then this method
2212 /// returns true as well. The converse is not true.
2213 /// The target can perform the adequate checks by overriding isExtFreeImpl.
2214 /// \pre \p I must be a sign, zero, or fp extension.
2215 bool isExtFree(const Instruction
*I
) const {
2216 switch (I
->getOpcode()) {
2217 case Instruction::FPExt
:
2218 if (isFPExtFree(EVT::getEVT(I
->getType()),
2219 EVT::getEVT(I
->getOperand(0)->getType())))
2222 case Instruction::ZExt
:
2223 if (isZExtFree(I
->getOperand(0)->getType(), I
->getType()))
2226 case Instruction::SExt
:
2229 llvm_unreachable("Instruction is not an extension");
2231 return isExtFreeImpl(I
);
2234 /// Return true if \p Load and \p Ext can form an ExtLoad.
2235 /// For example, in AArch64
2236 /// %L = load i8, i8* %ptr
2237 /// %E = zext i8 %L to i32
2238 /// can be lowered into one load instruction
2240 bool isExtLoad(const LoadInst
*Load
, const Instruction
*Ext
,
2241 const DataLayout
&DL
) const {
2242 EVT VT
= getValueType(DL
, Ext
->getType());
2243 EVT LoadVT
= getValueType(DL
, Load
->getType());
2245 // If the load has other users and the truncate is not free, the ext
2246 // probably isn't free.
2247 if (!Load
->hasOneUse() && (isTypeLegal(LoadVT
) || !isTypeLegal(VT
)) &&
2248 !isTruncateFree(Ext
->getType(), Load
->getType()))
2251 // Check whether the target supports casts folded into loads.
2253 if (isa
<ZExtInst
>(Ext
))
2254 LType
= ISD::ZEXTLOAD
;
2256 assert(isa
<SExtInst
>(Ext
) && "Unexpected ext type!");
2257 LType
= ISD::SEXTLOAD
;
2260 return isLoadExtLegal(LType
, VT
, LoadVT
);
2263 /// Return true if any actual instruction that defines a value of type FromTy
2264 /// implicitly zero-extends the value to ToTy in the result register.
2266 /// The function should return true when it is likely that the truncate can
2267 /// be freely folded with an instruction defining a value of FromTy. If
2268 /// the defining instruction is unknown (because you're looking at a
2269 /// function argument, PHI, etc.) then the target may require an
2270 /// explicit truncate, which is not necessarily free, but this function
2271 /// does not deal with those cases.
2272 /// Targets must return false when FromTy >= ToTy.
2273 virtual bool isZExtFree(Type
*FromTy
, Type
*ToTy
) const {
2277 virtual bool isZExtFree(EVT FromTy
, EVT ToTy
) const {
2281 /// Return true if sign-extension from FromTy to ToTy is cheaper than
2283 virtual bool isSExtCheaperThanZExt(EVT FromTy
, EVT ToTy
) const {
2287 /// Return true if sinking I's operands to the same basic block as I is
2288 /// profitable, e.g. because the operands can be folded into a target
2289 /// instruction during instruction selection. After calling the function
2290 /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2292 virtual bool shouldSinkOperands(Instruction
*I
,
2293 SmallVectorImpl
<Use
*> &Ops
) const {
2297 /// Return true if the target supplies and combines to a paired load
2298 /// two loaded values of type LoadedType next to each other in memory.
2299 /// RequiredAlignment gives the minimal alignment constraints that must be met
2300 /// to be able to select this paired load.
2302 /// This information is *not* used to generate actual paired loads, but it is
2303 /// used to generate a sequence of loads that is easier to combine into a
2305 /// For instance, something like this:
2306 /// a = load i64* addr
2307 /// b = trunc i64 a to i32
2308 /// c = lshr i64 a, 32
2309 /// d = trunc i64 c to i32
2310 /// will be optimized into:
2311 /// b = load i32* addr1
2312 /// d = load i32* addr2
2313 /// Where addr1 = addr2 +/- sizeof(i32).
2315 /// In other words, unless the target performs a post-isel load combining,
2316 /// this information should not be provided because it will generate more
2318 virtual bool hasPairedLoad(EVT
/*LoadedType*/,
2319 unsigned & /*RequiredAlignment*/) const {
2323 /// Return true if the target has a vector blend instruction.
2324 virtual bool hasVectorBlend() const { return false; }
2326 /// Get the maximum supported factor for interleaved memory accesses.
2327 /// Default to be the minimum interleave factor: 2.
2328 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2330 /// Lower an interleaved load to target specific intrinsics. Return
2331 /// true on success.
2333 /// \p LI is the vector load instruction.
2334 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2335 /// \p Indices is the corresponding indices for each shufflevector.
2336 /// \p Factor is the interleave factor.
2337 virtual bool lowerInterleavedLoad(LoadInst
*LI
,
2338 ArrayRef
<ShuffleVectorInst
*> Shuffles
,
2339 ArrayRef
<unsigned> Indices
,
2340 unsigned Factor
) const {
2344 /// Lower an interleaved store to target specific intrinsics. Return
2345 /// true on success.
2347 /// \p SI is the vector store instruction.
2348 /// \p SVI is the shufflevector to RE-interleave the stored vector.
2349 /// \p Factor is the interleave factor.
2350 virtual bool lowerInterleavedStore(StoreInst
*SI
, ShuffleVectorInst
*SVI
,
2351 unsigned Factor
) const {
2355 /// Return true if zero-extending the specific node Val to type VT2 is free
2356 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2357 /// because it's folded such as X86 zero-extending loads).
2358 virtual bool isZExtFree(SDValue Val
, EVT VT2
) const {
2359 return isZExtFree(Val
.getValueType(), VT2
);
2362 /// Return true if an fpext operation is free (for instance, because
2363 /// single-precision floating-point numbers are implicitly extended to
2364 /// double-precision).
2365 virtual bool isFPExtFree(EVT DestVT
, EVT SrcVT
) const {
2366 assert(SrcVT
.isFloatingPoint() && DestVT
.isFloatingPoint() &&
2367 "invalid fpext types");
2371 /// Return true if an fpext operation input to an \p Opcode operation is free
2372 /// (for instance, because half-precision floating-point numbers are
2373 /// implicitly extended to float-precision) for an FMA instruction.
2374 virtual bool isFPExtFoldable(unsigned Opcode
, EVT DestVT
, EVT SrcVT
) const {
2375 assert(DestVT
.isFloatingPoint() && SrcVT
.isFloatingPoint() &&
2376 "invalid fpext types");
2377 return isFPExtFree(DestVT
, SrcVT
);
2380 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2381 /// extend node) is profitable.
2382 virtual bool isVectorLoadExtDesirable(SDValue ExtVal
) const { return false; }
2384 /// Return true if an fneg operation is free to the point where it is never
2385 /// worthwhile to replace it with a bitwise operation.
2386 virtual bool isFNegFree(EVT VT
) const {
2387 assert(VT
.isFloatingPoint());
2391 /// Return true if an fabs operation is free to the point where it is never
2392 /// worthwhile to replace it with a bitwise operation.
2393 virtual bool isFAbsFree(EVT VT
) const {
2394 assert(VT
.isFloatingPoint());
2398 /// Return true if an FMA operation is faster than a pair of fmul and fadd
2399 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2400 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2402 /// NOTE: This may be called before legalization on types for which FMAs are
2403 /// not legal, but should return true if those types will eventually legalize
2404 /// to types that support FMAs. After legalization, it will only be called on
2405 /// types that support FMAs (via Legal or Custom actions)
2406 virtual bool isFMAFasterThanFMulAndFAdd(EVT
) const {
2410 /// Return true if it's profitable to narrow operations of type VT1 to
2411 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2413 virtual bool isNarrowingProfitable(EVT
/*VT1*/, EVT
/*VT2*/) const {
2417 /// Return true if it is beneficial to convert a load of a constant to
2418 /// just the constant itself.
2419 /// On some targets it might be more efficient to use a combination of
2420 /// arithmetic instructions to materialize the constant instead of loading it
2421 /// from a constant pool.
2422 virtual bool shouldConvertConstantLoadToIntImm(const APInt
&Imm
,
2427 /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2428 /// from this source type with this index. This is needed because
2429 /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2430 /// the first element, and only the target knows which lowering is cheap.
2431 virtual bool isExtractSubvectorCheap(EVT ResVT
, EVT SrcVT
,
2432 unsigned Index
) const {
2436 /// Try to convert an extract element of a vector binary operation into an
2437 /// extract element followed by a scalar operation.
2438 virtual bool shouldScalarizeBinop(SDValue VecOp
) const {
2442 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2443 // even if the vector itself has multiple uses.
2444 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT
) const {
2448 // Return true if CodeGenPrepare should consider splitting large offset of a
2449 // GEP to make the GEP fit into the addressing mode and can be sunk into the
2450 // same blocks of its users.
2451 virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
2453 //===--------------------------------------------------------------------===//
2454 // Runtime Library hooks
2457 /// Rename the default libcall routine name for the specified libcall.
2458 void setLibcallName(RTLIB::Libcall Call
, const char *Name
) {
2459 LibcallRoutineNames
[Call
] = Name
;
2462 /// Get the libcall routine name for the specified libcall.
2463 const char *getLibcallName(RTLIB::Libcall Call
) const {
2464 return LibcallRoutineNames
[Call
];
2467 /// Override the default CondCode to be used to test the result of the
2468 /// comparison libcall against zero.
2469 void setCmpLibcallCC(RTLIB::Libcall Call
, ISD::CondCode CC
) {
2470 CmpLibcallCCs
[Call
] = CC
;
2473 /// Get the CondCode that's to be used to test the result of the comparison
2474 /// libcall against zero.
2475 ISD::CondCode
getCmpLibcallCC(RTLIB::Libcall Call
) const {
2476 return CmpLibcallCCs
[Call
];
2479 /// Set the CallingConv that should be used for the specified libcall.
2480 void setLibcallCallingConv(RTLIB::Libcall Call
, CallingConv::ID CC
) {
2481 LibcallCallingConvs
[Call
] = CC
;
2484 /// Get the CallingConv that should be used for the specified libcall.
2485 CallingConv::ID
getLibcallCallingConv(RTLIB::Libcall Call
) const {
2486 return LibcallCallingConvs
[Call
];
2489 /// Execute target specific actions to finalize target lowering.
2490 /// This is used to set extra flags in MachineFrameInformation and freezing
2491 /// the set of reserved registers.
2492 /// The default implementation just freezes the set of reserved registers.
2493 virtual void finalizeLowering(MachineFunction
&MF
) const;
2496 const TargetMachine
&TM
;
2498 /// Tells the code generator that the target has multiple (allocatable)
2499 /// condition registers that can be used to store the results of comparisons
2500 /// for use by selects and conditional branches. With multiple condition
2501 /// registers, the code generator will not aggressively sink comparisons into
2502 /// the blocks of their users.
2503 bool HasMultipleConditionRegisters
;
2505 /// Tells the code generator that the target has BitExtract instructions.
2506 /// The code generator will aggressively sink "shift"s into the blocks of
2507 /// their users if the users will generate "and" instructions which can be
2508 /// combined with "shift" to BitExtract instructions.
2509 bool HasExtractBitsInsn
;
2511 /// Tells the code generator to bypass slow divide or remainder
2512 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2513 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2514 /// div/rem when the operands are positive and less than 256.
2515 DenseMap
<unsigned int, unsigned int> BypassSlowDivWidths
;
2517 /// Tells the code generator that it shouldn't generate extra flow control
2518 /// instructions and should attempt to combine flow control instructions via
2520 bool JumpIsExpensive
;
2522 /// Whether the target supports or cares about preserving floating point
2523 /// exception behavior.
2524 bool HasFloatingPointExceptions
;
2526 /// This target prefers to use _setjmp to implement llvm.setjmp.
2528 /// Defaults to false.
2529 bool UseUnderscoreSetJmp
;
2531 /// This target prefers to use _longjmp to implement llvm.longjmp.
2533 /// Defaults to false.
2534 bool UseUnderscoreLongJmp
;
2536 /// Information about the contents of the high-bits in boolean values held in
2537 /// a type wider than i1. See getBooleanContents.
2538 BooleanContent BooleanContents
;
2540 /// Information about the contents of the high-bits in boolean values held in
2541 /// a type wider than i1. See getBooleanContents.
2542 BooleanContent BooleanFloatContents
;
2544 /// Information about the contents of the high-bits in boolean vector values
2545 /// when the element type is wider than i1. See getBooleanContents.
2546 BooleanContent BooleanVectorContents
;
2548 /// The target scheduling preference: shortest possible total cycles or lowest
2550 Sched::Preference SchedPreferenceInfo
;
2552 /// The size, in bytes, of the target's jmp_buf buffers
2553 unsigned JumpBufSize
;
2555 /// The alignment, in bytes, of the target's jmp_buf buffers
2556 unsigned JumpBufAlignment
;
2558 /// The minimum alignment that any argument on the stack needs to have.
2559 unsigned MinStackArgumentAlignment
;
2561 /// The minimum function alignment (used when optimizing for size, and to
2562 /// prevent explicitly provided alignment from leading to incorrect code).
2563 unsigned MinFunctionAlignment
;
2565 /// The preferred function alignment (used when alignment unspecified and
2566 /// optimizing for speed).
2567 unsigned PrefFunctionAlignment
;
2569 /// The preferred loop alignment.
2570 unsigned PrefLoopAlignment
;
2572 /// Size in bits of the maximum atomics size the backend supports.
2573 /// Accesses larger than this will be expanded by AtomicExpandPass.
2574 unsigned MaxAtomicSizeInBitsSupported
;
2576 /// Size in bits of the minimum cmpxchg or ll/sc operation the
2577 /// backend supports.
2578 unsigned MinCmpXchgSizeInBits
;
2580 /// This indicates if the target supports unaligned atomic operations.
2581 bool SupportsUnalignedAtomics
;
2583 /// If set to a physical register, this specifies the register that
2584 /// llvm.savestack/llvm.restorestack should save and restore.
2585 unsigned StackPointerRegisterToSaveRestore
;
2587 /// This indicates the default register class to use for each ValueType the
2588 /// target supports natively.
2589 const TargetRegisterClass
*RegClassForVT
[MVT::LAST_VALUETYPE
];
2590 unsigned char NumRegistersForVT
[MVT::LAST_VALUETYPE
];
2591 MVT RegisterTypeForVT
[MVT::LAST_VALUETYPE
];
2593 /// This indicates the "representative" register class to use for each
2594 /// ValueType the target supports natively. This information is used by the
2595 /// scheduler to track register pressure. By default, the representative
2596 /// register class is the largest legal super-reg register class of the
2597 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2598 /// representative class would be GR32.
2599 const TargetRegisterClass
*RepRegClassForVT
[MVT::LAST_VALUETYPE
];
2601 /// This indicates the "cost" of the "representative" register class for each
2602 /// ValueType. The cost is used by the scheduler to approximate register
2604 uint8_t RepRegClassCostForVT
[MVT::LAST_VALUETYPE
];
2606 /// For any value types we are promoting or expanding, this contains the value
2607 /// type that we are changing to. For Expanded types, this contains one step
2608 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2609 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2610 /// the same type (e.g. i32 -> i32).
2611 MVT TransformToType
[MVT::LAST_VALUETYPE
];
2613 /// For each operation and each value type, keep a LegalizeAction that
2614 /// indicates how instruction selection should deal with the operation. Most
2615 /// operations are Legal (aka, supported natively by the target), but
2616 /// operations that are not should be described. Note that operations on
2617 /// non-legal value types are not described here.
2618 LegalizeAction OpActions
[MVT::LAST_VALUETYPE
][ISD::BUILTIN_OP_END
];
2620 /// For each load extension type and each value type, keep a LegalizeAction
2621 /// that indicates how instruction selection should deal with a load of a
2622 /// specific value type and extension type. Uses 4-bits to store the action
2623 /// for each of the 4 load ext types.
2624 uint16_t LoadExtActions
[MVT::LAST_VALUETYPE
][MVT::LAST_VALUETYPE
];
2626 /// For each value type pair keep a LegalizeAction that indicates whether a
2627 /// truncating store of a specific value type and truncating type is legal.
2628 LegalizeAction TruncStoreActions
[MVT::LAST_VALUETYPE
][MVT::LAST_VALUETYPE
];
2630 /// For each indexed mode and each value type, keep a pair of LegalizeAction
2631 /// that indicates how instruction selection should deal with the load /
2634 /// The first dimension is the value_type for the reference. The second
2635 /// dimension represents the various modes for load store.
2636 uint8_t IndexedModeActions
[MVT::LAST_VALUETYPE
][ISD::LAST_INDEXED_MODE
];
2638 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2639 /// indicates how instruction selection should deal with the condition code.
2641 /// Because each CC action takes up 4 bits, we need to have the array size be
2642 /// large enough to fit all of the value types. This can be done by rounding
2643 /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2644 uint32_t CondCodeActions
[ISD::SETCC_INVALID
][(MVT::LAST_VALUETYPE
+ 7) / 8];
2647 ValueTypeActionImpl ValueTypeActions
;
2650 LegalizeKind
getTypeConversion(LLVMContext
&Context
, EVT VT
) const;
2652 /// Targets can specify ISD nodes that they would like PerformDAGCombine
2653 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2656 TargetDAGCombineArray
[(ISD::BUILTIN_OP_END
+CHAR_BIT
-1)/CHAR_BIT
];
2658 /// For operations that must be promoted to a specific type, this holds the
2659 /// destination type. This map should be sparse, so don't hold it as an
2662 /// Targets add entries to this map with AddPromotedToType(..), clients access
2663 /// this with getTypeToPromoteTo(..).
2664 std::map
<std::pair
<unsigned, MVT::SimpleValueType
>, MVT::SimpleValueType
>
2667 /// Stores the name each libcall.
2668 const char *LibcallRoutineNames
[RTLIB::UNKNOWN_LIBCALL
+ 1];
2670 /// The ISD::CondCode that should be used to test the result of each of the
2671 /// comparison libcall against zero.
2672 ISD::CondCode CmpLibcallCCs
[RTLIB::UNKNOWN_LIBCALL
];
2674 /// Stores the CallingConv that should be used for each libcall.
2675 CallingConv::ID LibcallCallingConvs
[RTLIB::UNKNOWN_LIBCALL
];
2677 /// Set default libcall names and calling conventions.
2678 void InitLibcalls(const Triple
&TT
);
2681 /// Return true if the extension represented by \p I is free.
2682 /// \pre \p I is a sign, zero, or fp extension and
2683 /// is[Z|FP]ExtFree of the related types is not true.
2684 virtual bool isExtFreeImpl(const Instruction
*I
) const { return false; }
2686 /// Depth that GatherAllAliases should should continue looking for chain
2687 /// dependencies when trying to find a more preferable chain. As an
2688 /// approximation, this should be more than the number of consecutive stores
2689 /// expected to be merged.
2690 unsigned GatherAllAliasesMaxDepth
;
2692 /// Specify maximum number of store instructions per memset call.
2694 /// When lowering \@llvm.memset this field specifies the maximum number of
2695 /// store operations that may be substituted for the call to memset. Targets
2696 /// must set this value based on the cost threshold for that target. Targets
2697 /// should assume that the memset will be done using as many of the largest
2698 /// store operations first, followed by smaller ones, if necessary, per
2699 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2700 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2701 /// store. This only applies to setting a constant array of a constant size.
2702 unsigned MaxStoresPerMemset
;
2704 /// Maximum number of stores operations that may be substituted for the call
2705 /// to memset, used for functions with OptSize attribute.
2706 unsigned MaxStoresPerMemsetOptSize
;
2708 /// Specify maximum bytes of store instructions per memcpy call.
2710 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2711 /// store operations that may be substituted for a call to memcpy. Targets
2712 /// must set this value based on the cost threshold for that target. Targets
2713 /// should assume that the memcpy will be done using as many of the largest
2714 /// store operations first, followed by smaller ones, if necessary, per
2715 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2716 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2717 /// and one 1-byte store. This only applies to copying a constant array of
2719 unsigned MaxStoresPerMemcpy
;
2722 /// \brief Specify max number of store instructions to glue in inlined memcpy.
2724 /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
2725 /// of store instructions to keep together. This helps in pairing and
2726 // vectorization later on.
2727 unsigned MaxGluedStoresPerMemcpy
= 0;
2729 /// Maximum number of store operations that may be substituted for a call to
2730 /// memcpy, used for functions with OptSize attribute.
2731 unsigned MaxStoresPerMemcpyOptSize
;
2732 unsigned MaxLoadsPerMemcmp
;
2733 unsigned MaxLoadsPerMemcmpOptSize
;
2735 /// Specify maximum bytes of store instructions per memmove call.
2737 /// When lowering \@llvm.memmove this field specifies the maximum number of
2738 /// store instructions that may be substituted for a call to memmove. Targets
2739 /// must set this value based on the cost threshold for that target. Targets
2740 /// should assume that the memmove will be done using as many of the largest
2741 /// store operations first, followed by smaller ones, if necessary, per
2742 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2743 /// with 8-bit alignment would result in nine 1-byte stores. This only
2744 /// applies to copying a constant array of constant size.
2745 unsigned MaxStoresPerMemmove
;
2747 /// Maximum number of store instructions that may be substituted for a call to
2748 /// memmove, used for functions with OptSize attribute.
2749 unsigned MaxStoresPerMemmoveOptSize
;
2751 /// Tells the code generator that select is more expensive than a branch if
2752 /// the branch is usually predicted right.
2753 bool PredictableSelectIsExpensive
;
2755 /// \see enableExtLdPromotion.
2756 bool EnableExtLdPromotion
;
2758 /// Return true if the value types that can be represented by the specified
2759 /// register class are all legal.
2760 bool isLegalRC(const TargetRegisterInfo
&TRI
,
2761 const TargetRegisterClass
&RC
) const;
2763 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2764 /// sequence of memory operands that is recognized by PrologEpilogInserter.
2765 MachineBasicBlock
*emitPatchPoint(MachineInstr
&MI
,
2766 MachineBasicBlock
*MBB
) const;
2768 /// Replace/modify the XRay custom event operands with target-dependent
2770 MachineBasicBlock
*emitXRayCustomEvent(MachineInstr
&MI
,
2771 MachineBasicBlock
*MBB
) const;
2773 /// Replace/modify the XRay typed event operands with target-dependent
2775 MachineBasicBlock
*emitXRayTypedEvent(MachineInstr
&MI
,
2776 MachineBasicBlock
*MBB
) const;
2779 /// This class defines information used to lower LLVM code to legal SelectionDAG
2780 /// operators that the target instruction selector can accept natively.
2782 /// This class also defines callbacks that targets must implement to lower
2783 /// target-specific constructs to SelectionDAG operators.
2784 class TargetLowering
: public TargetLoweringBase
{
2786 struct DAGCombinerInfo
;
2788 TargetLowering(const TargetLowering
&) = delete;
2789 TargetLowering
&operator=(const TargetLowering
&) = delete;
2791 /// NOTE: The TargetMachine owns TLOF.
2792 explicit TargetLowering(const TargetMachine
&TM
);
2794 bool isPositionIndependent() const;
2796 virtual bool isSDNodeSourceOfDivergence(const SDNode
*N
,
2797 FunctionLoweringInfo
*FLI
,
2798 LegacyDivergenceAnalysis
*DA
) const {
2802 virtual bool isSDNodeAlwaysUniform(const SDNode
* N
) const {
2806 /// Returns true by value, base pointer and offset pointer and addressing mode
2807 /// by reference if the node's address can be legally represented as
2808 /// pre-indexed load / store address.
2809 virtual bool getPreIndexedAddressParts(SDNode
* /*N*/, SDValue
&/*Base*/,
2810 SDValue
&/*Offset*/,
2811 ISD::MemIndexedMode
&/*AM*/,
2812 SelectionDAG
&/*DAG*/) const {
2816 /// Returns true by value, base pointer and offset pointer and addressing mode
2817 /// by reference if this node can be combined with a load / store to form a
2818 /// post-indexed load / store.
2819 virtual bool getPostIndexedAddressParts(SDNode
* /*N*/, SDNode
* /*Op*/,
2821 SDValue
&/*Offset*/,
2822 ISD::MemIndexedMode
&/*AM*/,
2823 SelectionDAG
&/*DAG*/) const {
2827 /// Return the entry encoding for a jump table in the current function. The
2828 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2829 virtual unsigned getJumpTableEncoding() const;
2831 virtual const MCExpr
*
2832 LowerCustomJumpTableEntry(const MachineJumpTableInfo
* /*MJTI*/,
2833 const MachineBasicBlock
* /*MBB*/, unsigned /*uid*/,
2834 MCContext
&/*Ctx*/) const {
2835 llvm_unreachable("Need to implement this hook if target has custom JTIs");
2838 /// Returns relocation base for the given PIC jumptable.
2839 virtual SDValue
getPICJumpTableRelocBase(SDValue Table
,
2840 SelectionDAG
&DAG
) const;
2842 /// This returns the relocation base for the given PIC jumptable, the same as
2843 /// getPICJumpTableRelocBase, but as an MCExpr.
2844 virtual const MCExpr
*
2845 getPICJumpTableRelocBaseExpr(const MachineFunction
*MF
,
2846 unsigned JTI
, MCContext
&Ctx
) const;
2848 /// Return true if folding a constant offset with the given GlobalAddress is
2849 /// legal. It is frequently not legal in PIC relocation models.
2850 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode
*GA
) const;
2852 bool isInTailCallPosition(SelectionDAG
&DAG
, SDNode
*Node
,
2853 SDValue
&Chain
) const;
2855 void softenSetCCOperands(SelectionDAG
&DAG
, EVT VT
, SDValue
&NewLHS
,
2856 SDValue
&NewRHS
, ISD::CondCode
&CCCode
,
2857 const SDLoc
&DL
) const;
2859 /// Returns a pair of (return value, chain).
2860 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2861 std::pair
<SDValue
, SDValue
> makeLibCall(
2862 SelectionDAG
&DAG
, RTLIB::Libcall LC
, EVT RetVT
, ArrayRef
<SDValue
> Ops
,
2863 bool isSigned
, const SDLoc
&dl
, bool doesNotReturn
= false,
2864 bool isReturnValueUsed
= true, bool isPostTypeLegalization
= false) const;
2866 /// Check whether parameters to a call that are passed in callee saved
2867 /// registers are the same as from the calling function. This needs to be
2868 /// checked for tail call eligibility.
2869 bool parametersInCSRMatch(const MachineRegisterInfo
&MRI
,
2870 const uint32_t *CallerPreservedMask
,
2871 const SmallVectorImpl
<CCValAssign
> &ArgLocs
,
2872 const SmallVectorImpl
<SDValue
> &OutVals
) const;
2874 //===--------------------------------------------------------------------===//
2875 // TargetLowering Optimization Methods
2878 /// A convenience struct that encapsulates a DAG, and two SDValues for
2879 /// returning information from TargetLowering to its clients that want to
2881 struct TargetLoweringOpt
{
2888 explicit TargetLoweringOpt(SelectionDAG
&InDAG
,
2890 DAG(InDAG
), LegalTys(LT
), LegalOps(LO
) {}
2892 bool LegalTypes() const { return LegalTys
; }
2893 bool LegalOperations() const { return LegalOps
; }
2895 bool CombineTo(SDValue O
, SDValue N
) {
2902 /// Check to see if the specified operand of the specified instruction is a
2903 /// constant integer. If so, check to see if there are any bits set in the
2904 /// constant that are not demanded. If so, shrink the constant and return
2906 bool ShrinkDemandedConstant(SDValue Op
, const APInt
&Demanded
,
2907 TargetLoweringOpt
&TLO
) const;
2909 // Target hook to do target-specific const optimization, which is called by
2910 // ShrinkDemandedConstant. This function should return true if the target
2911 // doesn't want ShrinkDemandedConstant to further optimize the constant.
2912 virtual bool targetShrinkDemandedConstant(SDValue Op
, const APInt
&Demanded
,
2913 TargetLoweringOpt
&TLO
) const {
2917 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
2918 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
2919 /// generalized for targets with other types of implicit widening casts.
2920 bool ShrinkDemandedOp(SDValue Op
, unsigned BitWidth
, const APInt
&Demanded
,
2921 TargetLoweringOpt
&TLO
) const;
2923 /// Look at Op. At this point, we know that only the DemandedBits bits of the
2924 /// result of Op are ever used downstream. If we can use this information to
2925 /// simplify Op, create a new simplified DAG node and return true, returning
2926 /// the original and new nodes in Old and New. Otherwise, analyze the
2927 /// expression and return a mask of KnownOne and KnownZero bits for the
2928 /// expression (used to simplify the caller). The KnownZero/One bits may only
2929 /// be accurate for those bits in the Demanded masks.
2930 /// \p AssumeSingleUse When this parameter is true, this function will
2931 /// attempt to simplify \p Op even if there are multiple uses.
2932 /// Callers are responsible for correctly updating the DAG based on the
2933 /// results of this function, because simply replacing replacing TLO.Old
2934 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2935 /// has multiple uses.
2936 bool SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
2937 const APInt
&DemandedElts
, KnownBits
&Known
,
2938 TargetLoweringOpt
&TLO
, unsigned Depth
= 0,
2939 bool AssumeSingleUse
= false) const;
2941 /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
2942 /// Adds Op back to the worklist upon success.
2943 bool SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
2944 KnownBits
&Known
, TargetLoweringOpt
&TLO
,
2946 bool AssumeSingleUse
= false) const;
2948 /// Helper wrapper around SimplifyDemandedBits.
2949 /// Adds Op back to the worklist upon success.
2950 bool SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedMask
,
2951 DAGCombinerInfo
&DCI
) const;
2953 /// Look at Vector Op. At this point, we know that only the DemandedElts
2954 /// elements of the result of Op are ever used downstream. If we can use
2955 /// this information to simplify Op, create a new simplified DAG node and
2956 /// return true, storing the original and new nodes in TLO.
2957 /// Otherwise, analyze the expression and return a mask of KnownUndef and
2958 /// KnownZero elements for the expression (used to simplify the caller).
2959 /// The KnownUndef/Zero elements may only be accurate for those bits
2960 /// in the DemandedMask.
2961 /// \p AssumeSingleUse When this parameter is true, this function will
2962 /// attempt to simplify \p Op even if there are multiple uses.
2963 /// Callers are responsible for correctly updating the DAG based on the
2964 /// results of this function, because simply replacing replacing TLO.Old
2965 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2966 /// has multiple uses.
2967 bool SimplifyDemandedVectorElts(SDValue Op
, const APInt
&DemandedEltMask
,
2968 APInt
&KnownUndef
, APInt
&KnownZero
,
2969 TargetLoweringOpt
&TLO
, unsigned Depth
= 0,
2970 bool AssumeSingleUse
= false) const;
2972 /// Helper wrapper around SimplifyDemandedVectorElts.
2973 /// Adds Op back to the worklist upon success.
2974 bool SimplifyDemandedVectorElts(SDValue Op
, const APInt
&DemandedElts
,
2975 APInt
&KnownUndef
, APInt
&KnownZero
,
2976 DAGCombinerInfo
&DCI
) const;
2978 /// Determine which of the bits specified in Mask are known to be either zero
2979 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
2980 /// argument allows us to only collect the known bits that are shared by the
2981 /// requested vector elements.
2982 virtual void computeKnownBitsForTargetNode(const SDValue Op
,
2984 const APInt
&DemandedElts
,
2985 const SelectionDAG
&DAG
,
2986 unsigned Depth
= 0) const;
2988 /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
2989 /// Default implementation computes low bits based on alignment
2990 /// information. This should preserve known bits passed into it.
2991 virtual void computeKnownBitsForFrameIndex(const SDValue FIOp
,
2993 const APInt
&DemandedElts
,
2994 const SelectionDAG
&DAG
,
2995 unsigned Depth
= 0) const;
2997 /// This method can be implemented by targets that want to expose additional
2998 /// information about sign bits to the DAG Combiner. The DemandedElts
2999 /// argument allows us to only collect the minimum sign bits that are shared
3000 /// by the requested vector elements.
3001 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op
,
3002 const APInt
&DemandedElts
,
3003 const SelectionDAG
&DAG
,
3004 unsigned Depth
= 0) const;
3006 /// Attempt to simplify any target nodes based on the demanded vector
3007 /// elements, returning true on success. Otherwise, analyze the expression and
3008 /// return a mask of KnownUndef and KnownZero elements for the expression
3009 /// (used to simplify the caller). The KnownUndef/Zero elements may only be
3010 /// accurate for those bits in the DemandedMask.
3011 virtual bool SimplifyDemandedVectorEltsForTargetNode(
3012 SDValue Op
, const APInt
&DemandedElts
, APInt
&KnownUndef
,
3013 APInt
&KnownZero
, TargetLoweringOpt
&TLO
, unsigned Depth
= 0) const;
3015 /// Attempt to simplify any target nodes based on the demanded bits/elts,
3016 /// returning true on success. Otherwise, analyze the
3017 /// expression and return a mask of KnownOne and KnownZero bits for the
3018 /// expression (used to simplify the caller). The KnownZero/One bits may only
3019 /// be accurate for those bits in the Demanded masks.
3020 virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op
,
3021 const APInt
&DemandedBits
,
3022 const APInt
&DemandedElts
,
3024 TargetLoweringOpt
&TLO
,
3025 unsigned Depth
= 0) const;
3027 /// If \p SNaN is false, \returns true if \p Op is known to never be any
3028 /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
3030 virtual bool isKnownNeverNaNForTargetNode(SDValue Op
,
3031 const SelectionDAG
&DAG
,
3033 unsigned Depth
= 0) const;
3034 struct DAGCombinerInfo
{
3035 void *DC
; // The DAG Combiner object.
3037 bool CalledByLegalizer
;
3042 DAGCombinerInfo(SelectionDAG
&dag
, CombineLevel level
, bool cl
, void *dc
)
3043 : DC(dc
), Level(level
), CalledByLegalizer(cl
), DAG(dag
) {}
3045 bool isBeforeLegalize() const { return Level
== BeforeLegalizeTypes
; }
3046 bool isBeforeLegalizeOps() const { return Level
< AfterLegalizeVectorOps
; }
3047 bool isAfterLegalizeDAG() const {
3048 return Level
== AfterLegalizeDAG
;
3050 CombineLevel
getDAGCombineLevel() { return Level
; }
3051 bool isCalledByLegalizer() const { return CalledByLegalizer
; }
3053 void AddToWorklist(SDNode
*N
);
3054 SDValue
CombineTo(SDNode
*N
, ArrayRef
<SDValue
> To
, bool AddTo
= true);
3055 SDValue
CombineTo(SDNode
*N
, SDValue Res
, bool AddTo
= true);
3056 SDValue
CombineTo(SDNode
*N
, SDValue Res0
, SDValue Res1
, bool AddTo
= true);
3058 void CommitTargetLoweringOpt(const TargetLoweringOpt
&TLO
);
3061 /// Return if the N is a constant or constant vector equal to the true value
3062 /// from getBooleanContents().
3063 bool isConstTrueVal(const SDNode
*N
) const;
3065 /// Return if the N is a constant or constant vector equal to the false value
3066 /// from getBooleanContents().
3067 bool isConstFalseVal(const SDNode
*N
) const;
3069 /// Return if \p N is a True value when extended to \p VT.
3070 bool isExtendedTrueVal(const ConstantSDNode
*N
, EVT VT
, bool SExt
) const;
3072 /// Try to simplify a setcc built with the specified operands and cc. If it is
3073 /// unable to simplify it, return a null SDValue.
3074 SDValue
SimplifySetCC(EVT VT
, SDValue N0
, SDValue N1
, ISD::CondCode Cond
,
3075 bool foldBooleans
, DAGCombinerInfo
&DCI
,
3076 const SDLoc
&dl
) const;
3078 // For targets which wrap address, unwrap for analysis.
3079 virtual SDValue
unwrapAddress(SDValue N
) const { return N
; }
3081 /// Returns true (and the GlobalValue and the offset) if the node is a
3082 /// GlobalAddress + offset.
3084 isGAPlusOffset(SDNode
*N
, const GlobalValue
* &GA
, int64_t &Offset
) const;
3086 /// This method will be invoked for all target nodes and for any
3087 /// target-independent nodes that the target has registered with invoke it
3090 /// The semantics are as follows:
3092 /// SDValue.Val == 0 - No change was made
3093 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
3094 /// otherwise - N should be replaced by the returned Operand.
3096 /// In addition, methods provided by DAGCombinerInfo may be used to perform
3097 /// more complex transformations.
3099 virtual SDValue
PerformDAGCombine(SDNode
*N
, DAGCombinerInfo
&DCI
) const;
3101 /// Return true if it is profitable to move this shift by a constant amount
3102 /// though its operand, adjusting any immediate operands as necessary to
3103 /// preserve semantics. This transformation may not be desirable if it
3104 /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
3105 /// extraction in AArch64). By default, it returns true.
3107 /// @param N the shift node
3108 /// @param Level the current DAGCombine legalization level.
3109 virtual bool isDesirableToCommuteWithShift(const SDNode
*N
,
3110 CombineLevel Level
) const {
3114 /// Return true if it is profitable to fold a pair of shifts into a mask.
3115 /// This is usually true on most targets. But some targets, like Thumb1,
3116 /// have immediate shift instructions, but no immediate "and" instruction;
3117 /// this makes the fold unprofitable.
3118 virtual bool shouldFoldShiftPairToMask(const SDNode
*N
,
3119 CombineLevel Level
) const {
3123 // Return true if it is profitable to combine a BUILD_VECTOR with a stride-pattern
3124 // to a shuffle and a truncate.
3125 // Example of such a combine:
3126 // v4i32 build_vector((extract_elt V, 1),
3127 // (extract_elt V, 3),
3128 // (extract_elt V, 5),
3129 // (extract_elt V, 7))
3131 // v4i32 truncate (bitcast (shuffle<1,u,3,u,5,u,7,u> V, u) to v4i64)
3132 virtual bool isDesirableToCombineBuildVectorToShuffleTruncate(
3133 ArrayRef
<int> ShuffleMask
, EVT SrcVT
, EVT TruncVT
) const {
3137 /// Return true if the target has native support for the specified value type
3138 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
3139 /// i16 is legal, but undesirable since i16 instruction encodings are longer
3140 /// and some i16 instructions are slow.
3141 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT
) const {
3142 // By default, assume all legal types are desirable.
3143 return isTypeLegal(VT
);
3146 /// Return true if it is profitable for dag combiner to transform a floating
3147 /// point op of specified opcode to a equivalent op of an integer
3148 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
3149 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
3154 /// This method query the target whether it is beneficial for dag combiner to
3155 /// promote the specified node. If true, it should return the desired
3156 /// promotion type by reference.
3157 virtual bool IsDesirableToPromoteOp(SDValue
/*Op*/, EVT
&/*PVT*/) const {
3161 /// Return true if the target supports swifterror attribute. It optimizes
3162 /// loads and stores to reading and writing a specific register.
3163 virtual bool supportSwiftError() const {
3167 /// Return true if the target supports that a subset of CSRs for the given
3168 /// machine function is handled explicitly via copies.
3169 virtual bool supportSplitCSR(MachineFunction
*MF
) const {
3173 /// Perform necessary initialization to handle a subset of CSRs explicitly
3174 /// via copies. This function is called at the beginning of instruction
3176 virtual void initializeSplitCSR(MachineBasicBlock
*Entry
) const {
3177 llvm_unreachable("Not Implemented");
3180 /// Insert explicit copies in entry and exit blocks. We copy a subset of
3181 /// CSRs to virtual registers in the entry block, and copy them back to
3182 /// physical registers in the exit blocks. This function is called at the end
3183 /// of instruction selection.
3184 virtual void insertCopiesSplitCSR(
3185 MachineBasicBlock
*Entry
,
3186 const SmallVectorImpl
<MachineBasicBlock
*> &Exits
) const {
3187 llvm_unreachable("Not Implemented");
3190 //===--------------------------------------------------------------------===//
3191 // Lowering methods - These methods must be implemented by targets so that
3192 // the SelectionDAGBuilder code knows how to lower these.
3195 /// This hook must be implemented to lower the incoming (formal) arguments,
3196 /// described by the Ins array, into the specified DAG. The implementation
3197 /// should fill in the InVals array with legal-type argument values, and
3198 /// return the resulting token chain value.
3199 virtual SDValue
LowerFormalArguments(
3200 SDValue
/*Chain*/, CallingConv::ID
/*CallConv*/, bool /*isVarArg*/,
3201 const SmallVectorImpl
<ISD::InputArg
> & /*Ins*/, const SDLoc
& /*dl*/,
3202 SelectionDAG
& /*DAG*/, SmallVectorImpl
<SDValue
> & /*InVals*/) const {
3203 llvm_unreachable("Not Implemented");
3206 /// This structure contains all information that is necessary for lowering
3207 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
3208 /// needs to lower a call, and targets will see this struct in their LowerCall
3210 struct CallLoweringInfo
{
3212 Type
*RetTy
= nullptr;
3217 bool DoesNotReturn
: 1;
3218 bool IsReturnValueUsed
: 1;
3219 bool IsConvergent
: 1;
3220 bool IsPatchPoint
: 1;
3222 // IsTailCall should be modified by implementations of
3223 // TargetLowering::LowerCall that perform tail call conversions.
3224 bool IsTailCall
= false;
3226 // Is Call lowering done post SelectionDAG type legalization.
3227 bool IsPostTypeLegalization
= false;
3229 unsigned NumFixedArgs
= -1;
3230 CallingConv::ID CallConv
= CallingConv::C
;
3235 ImmutableCallSite CS
;
3236 SmallVector
<ISD::OutputArg
, 32> Outs
;
3237 SmallVector
<SDValue
, 32> OutVals
;
3238 SmallVector
<ISD::InputArg
, 32> Ins
;
3239 SmallVector
<SDValue
, 4> InVals
;
3241 CallLoweringInfo(SelectionDAG
&DAG
)
3242 : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
3243 DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
3244 IsPatchPoint(false), DAG(DAG
) {}
3246 CallLoweringInfo
&setDebugLoc(const SDLoc
&dl
) {
3251 CallLoweringInfo
&setChain(SDValue InChain
) {
3256 // setCallee with target/module-specific attributes
3257 CallLoweringInfo
&setLibCallee(CallingConv::ID CC
, Type
*ResultType
,
3258 SDValue Target
, ArgListTy
&&ArgsList
) {
3262 NumFixedArgs
= ArgsList
.size();
3263 Args
= std::move(ArgsList
);
3265 DAG
.getTargetLoweringInfo().markLibCallAttributes(
3266 &(DAG
.getMachineFunction()), CC
, Args
);
3270 CallLoweringInfo
&setCallee(CallingConv::ID CC
, Type
*ResultType
,
3271 SDValue Target
, ArgListTy
&&ArgsList
) {
3275 NumFixedArgs
= ArgsList
.size();
3276 Args
= std::move(ArgsList
);
3280 CallLoweringInfo
&setCallee(Type
*ResultType
, FunctionType
*FTy
,
3281 SDValue Target
, ArgListTy
&&ArgsList
,
3282 ImmutableCallSite Call
) {
3285 IsInReg
= Call
.hasRetAttr(Attribute::InReg
);
3287 Call
.doesNotReturn() ||
3288 (!Call
.isInvoke() &&
3289 isa
<UnreachableInst
>(Call
.getInstruction()->getNextNode()));
3290 IsVarArg
= FTy
->isVarArg();
3291 IsReturnValueUsed
= !Call
.getInstruction()->use_empty();
3292 RetSExt
= Call
.hasRetAttr(Attribute::SExt
);
3293 RetZExt
= Call
.hasRetAttr(Attribute::ZExt
);
3297 CallConv
= Call
.getCallingConv();
3298 NumFixedArgs
= FTy
->getNumParams();
3299 Args
= std::move(ArgsList
);
3306 CallLoweringInfo
&setInRegister(bool Value
= true) {
3311 CallLoweringInfo
&setNoReturn(bool Value
= true) {
3312 DoesNotReturn
= Value
;
3316 CallLoweringInfo
&setVarArg(bool Value
= true) {
3321 CallLoweringInfo
&setTailCall(bool Value
= true) {
3326 CallLoweringInfo
&setDiscardResult(bool Value
= true) {
3327 IsReturnValueUsed
= !Value
;
3331 CallLoweringInfo
&setConvergent(bool Value
= true) {
3332 IsConvergent
= Value
;
3336 CallLoweringInfo
&setSExtResult(bool Value
= true) {
3341 CallLoweringInfo
&setZExtResult(bool Value
= true) {
3346 CallLoweringInfo
&setIsPatchPoint(bool Value
= true) {
3347 IsPatchPoint
= Value
;
3351 CallLoweringInfo
&setIsPostTypeLegalization(bool Value
=true) {
3352 IsPostTypeLegalization
= Value
;
3356 ArgListTy
&getArgs() {
3361 /// This function lowers an abstract call to a function into an actual call.
3362 /// This returns a pair of operands. The first element is the return value
3363 /// for the function (if RetTy is not VoidTy). The second element is the
3364 /// outgoing token chain. It calls LowerCall to do the actual lowering.
3365 std::pair
<SDValue
, SDValue
> LowerCallTo(CallLoweringInfo
&CLI
) const;
3367 /// This hook must be implemented to lower calls into the specified
3368 /// DAG. The outgoing arguments to the call are described by the Outs array,
3369 /// and the values to be returned by the call are described by the Ins
3370 /// array. The implementation should fill in the InVals array with legal-type
3371 /// return values from the call, and return the resulting token chain value.
3373 LowerCall(CallLoweringInfo
&/*CLI*/,
3374 SmallVectorImpl
<SDValue
> &/*InVals*/) const {
3375 llvm_unreachable("Not Implemented");
3378 /// Target-specific cleanup for formal ByVal parameters.
3379 virtual void HandleByVal(CCState
*, unsigned &, unsigned) const {}
3381 /// This hook should be implemented to check whether the return values
3382 /// described by the Outs array can fit into the return registers. If false
3383 /// is returned, an sret-demotion is performed.
3384 virtual bool CanLowerReturn(CallingConv::ID
/*CallConv*/,
3385 MachineFunction
&/*MF*/, bool /*isVarArg*/,
3386 const SmallVectorImpl
<ISD::OutputArg
> &/*Outs*/,
3387 LLVMContext
&/*Context*/) const
3389 // Return true by default to get preexisting behavior.
3393 /// This hook must be implemented to lower outgoing return values, described
3394 /// by the Outs array, into the specified DAG. The implementation should
3395 /// return the resulting token chain value.
3396 virtual SDValue
LowerReturn(SDValue
/*Chain*/, CallingConv::ID
/*CallConv*/,
3398 const SmallVectorImpl
<ISD::OutputArg
> & /*Outs*/,
3399 const SmallVectorImpl
<SDValue
> & /*OutVals*/,
3400 const SDLoc
& /*dl*/,
3401 SelectionDAG
& /*DAG*/) const {
3402 llvm_unreachable("Not Implemented");
3405 /// Return true if result of the specified node is used by a return node
3406 /// only. It also compute and return the input chain for the tail call.
3408 /// This is used to determine whether it is possible to codegen a libcall as
3409 /// tail call at legalization time.
3410 virtual bool isUsedByReturnOnly(SDNode
*, SDValue
&/*Chain*/) const {
3414 /// Return true if the target may be able emit the call instruction as a tail
3415 /// call. This is used by optimization passes to determine if it's profitable
3416 /// to duplicate return instructions to enable tailcall optimization.
3417 virtual bool mayBeEmittedAsTailCall(const CallInst
*) const {
3421 /// Return the builtin name for the __builtin___clear_cache intrinsic
3422 /// Default is to invoke the clear cache library call
3423 virtual const char * getClearCacheBuiltinName() const {
3424 return "__clear_cache";
3427 /// Return the register ID of the name passed in. Used by named register
3428 /// global variables extension. There is no target-independent behaviour
3429 /// so the default action is to bail.
3430 virtual unsigned getRegisterByName(const char* RegName
, EVT VT
,
3431 SelectionDAG
&DAG
) const {
3432 report_fatal_error("Named registers not implemented for this target");
3435 /// Return the type that should be used to zero or sign extend a
3436 /// zeroext/signext integer return value. FIXME: Some C calling conventions
3437 /// require the return type to be promoted, but this is not true all the time,
3438 /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
3439 /// conventions. The frontend should handle this and include all of the
3440 /// necessary information.
3441 virtual EVT
getTypeForExtReturn(LLVMContext
&Context
, EVT VT
,
3442 ISD::NodeType
/*ExtendKind*/) const {
3443 EVT MinVT
= getRegisterType(Context
, MVT::i32
);
3444 return VT
.bitsLT(MinVT
) ? MinVT
: VT
;
3447 /// For some targets, an LLVM struct type must be broken down into multiple
3448 /// simple types, but the calling convention specifies that the entire struct
3449 /// must be passed in a block of consecutive registers.
3451 functionArgumentNeedsConsecutiveRegisters(Type
*Ty
, CallingConv::ID CallConv
,
3452 bool isVarArg
) const {
3456 /// Returns a 0 terminated array of registers that can be safely used as
3457 /// scratch registers.
3458 virtual const MCPhysReg
*getScratchRegisters(CallingConv::ID CC
) const {
3462 /// This callback is used to prepare for a volatile or atomic load.
3463 /// It takes a chain node as input and returns the chain for the load itself.
3465 /// Having a callback like this is necessary for targets like SystemZ,
3466 /// which allows a CPU to reuse the result of a previous load indefinitely,
3467 /// even if a cache-coherent store is performed by another CPU. The default
3468 /// implementation does nothing.
3469 virtual SDValue
prepareVolatileOrAtomicLoad(SDValue Chain
, const SDLoc
&DL
,
3470 SelectionDAG
&DAG
) const {
3474 /// This callback is used to inspect load/store instructions and add
3475 /// target-specific MachineMemOperand flags to them. The default
3476 /// implementation does nothing.
3477 virtual MachineMemOperand::Flags
getMMOFlags(const Instruction
&I
) const {
3478 return MachineMemOperand::MONone
;
3481 /// This callback is invoked by the type legalizer to legalize nodes with an
3482 /// illegal operand type but legal result types. It replaces the
3483 /// LowerOperation callback in the type Legalizer. The reason we can not do
3484 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
3485 /// use this callback.
3487 /// TODO: Consider merging with ReplaceNodeResults.
3489 /// The target places new result values for the node in Results (their number
3490 /// and types must exactly match those of the original return values of
3491 /// the node), or leaves Results empty, which indicates that the node is not
3492 /// to be custom lowered after all.
3493 /// The default implementation calls LowerOperation.
3494 virtual void LowerOperationWrapper(SDNode
*N
,
3495 SmallVectorImpl
<SDValue
> &Results
,
3496 SelectionDAG
&DAG
) const;
3498 /// This callback is invoked for operations that are unsupported by the
3499 /// target, which are registered to use 'custom' lowering, and whose defined
3500 /// values are all legal. If the target has no operations that require custom
3501 /// lowering, it need not implement this. The default implementation of this
3503 virtual SDValue
LowerOperation(SDValue Op
, SelectionDAG
&DAG
) const;
3505 /// This callback is invoked when a node result type is illegal for the
3506 /// target, and the operation was registered to use 'custom' lowering for that
3507 /// result type. The target places new result values for the node in Results
3508 /// (their number and types must exactly match those of the original return
3509 /// values of the node), or leaves Results empty, which indicates that the
3510 /// node is not to be custom lowered after all.
3512 /// If the target has no operations that require custom lowering, it need not
3513 /// implement this. The default implementation aborts.
3514 virtual void ReplaceNodeResults(SDNode
* /*N*/,
3515 SmallVectorImpl
<SDValue
> &/*Results*/,
3516 SelectionDAG
&/*DAG*/) const {
3517 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
3520 /// This method returns the name of a target specific DAG node.
3521 virtual const char *getTargetNodeName(unsigned Opcode
) const;
3523 /// This method returns a target specific FastISel object, or null if the
3524 /// target does not support "fast" ISel.
3525 virtual FastISel
*createFastISel(FunctionLoweringInfo
&,
3526 const TargetLibraryInfo
*) const {
3530 bool verifyReturnAddressArgumentIsConstant(SDValue Op
,
3531 SelectionDAG
&DAG
) const;
3533 //===--------------------------------------------------------------------===//
3534 // Inline Asm Support hooks
3537 /// This hook allows the target to expand an inline asm call to be explicit
3538 /// llvm code if it wants to. This is useful for turning simple inline asms
3539 /// into LLVM intrinsics, which gives the compiler more information about the
3540 /// behavior of the code.
3541 virtual bool ExpandInlineAsm(CallInst
*) const {
3545 enum ConstraintType
{
3546 C_Register
, // Constraint represents specific register(s).
3547 C_RegisterClass
, // Constraint represents any of register(s) in class.
3548 C_Memory
, // Memory constraint.
3549 C_Other
, // Something else.
3550 C_Unknown
// Unsupported constraint.
3553 enum ConstraintWeight
{
3555 CW_Invalid
= -1, // No match.
3556 CW_Okay
= 0, // Acceptable.
3557 CW_Good
= 1, // Good weight.
3558 CW_Better
= 2, // Better weight.
3559 CW_Best
= 3, // Best weight.
3561 // Well-known weights.
3562 CW_SpecificReg
= CW_Okay
, // Specific register operands.
3563 CW_Register
= CW_Good
, // Register operands.
3564 CW_Memory
= CW_Better
, // Memory operands.
3565 CW_Constant
= CW_Best
, // Constant operand.
3566 CW_Default
= CW_Okay
// Default or don't know type.
3569 /// This contains information for each constraint that we are lowering.
3570 struct AsmOperandInfo
: public InlineAsm::ConstraintInfo
{
3571 /// This contains the actual string for the code, like "m". TargetLowering
3572 /// picks the 'best' code from ConstraintInfo::Codes that most closely
3573 /// matches the operand.
3574 std::string ConstraintCode
;
3576 /// Information about the constraint code, e.g. Register, RegisterClass,
3577 /// Memory, Other, Unknown.
3578 TargetLowering::ConstraintType ConstraintType
= TargetLowering::C_Unknown
;
3580 /// If this is the result output operand or a clobber, this is null,
3581 /// otherwise it is the incoming operand to the CallInst. This gets
3582 /// modified as the asm is processed.
3583 Value
*CallOperandVal
= nullptr;
3585 /// The ValueType for the operand value.
3586 MVT ConstraintVT
= MVT::Other
;
3588 /// Copy constructor for copying from a ConstraintInfo.
3589 AsmOperandInfo(InlineAsm::ConstraintInfo Info
)
3590 : InlineAsm::ConstraintInfo(std::move(Info
)) {}
3592 /// Return true of this is an input operand that is a matching constraint
3594 bool isMatchingInputConstraint() const;
3596 /// If this is an input matching constraint, this method returns the output
3597 /// operand it matches.
3598 unsigned getMatchedOperand() const;
3601 using AsmOperandInfoVector
= std::vector
<AsmOperandInfo
>;
3603 /// Split up the constraint string from the inline assembly value into the
3604 /// specific constraints and their prefixes, and also tie in the associated
3605 /// operand values. If this returns an empty vector, and if the constraint
3606 /// string itself isn't empty, there was an error parsing.
3607 virtual AsmOperandInfoVector
ParseConstraints(const DataLayout
&DL
,
3608 const TargetRegisterInfo
*TRI
,
3609 ImmutableCallSite CS
) const;
3611 /// Examine constraint type and operand type and determine a weight value.
3612 /// The operand object must already have been set up with the operand type.
3613 virtual ConstraintWeight
getMultipleConstraintMatchWeight(
3614 AsmOperandInfo
&info
, int maIndex
) const;
3616 /// Examine constraint string and operand type and determine a weight value.
3617 /// The operand object must already have been set up with the operand type.
3618 virtual ConstraintWeight
getSingleConstraintMatchWeight(
3619 AsmOperandInfo
&info
, const char *constraint
) const;
3621 /// Determines the constraint code and constraint type to use for the specific
3622 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3623 /// If the actual operand being passed in is available, it can be passed in as
3624 /// Op, otherwise an empty SDValue can be passed.
3625 virtual void ComputeConstraintToUse(AsmOperandInfo
&OpInfo
,
3627 SelectionDAG
*DAG
= nullptr) const;
3629 /// Given a constraint, return the type of constraint it is for this target.
3630 virtual ConstraintType
getConstraintType(StringRef Constraint
) const;
3632 /// Given a physical register constraint (e.g. {edx}), return the register
3633 /// number and the register class for the register.
3635 /// Given a register class constraint, like 'r', if this corresponds directly
3636 /// to an LLVM register class, return a register of 0 and the register class
3639 /// This should only be used for C_Register constraints. On error, this
3640 /// returns a register number of 0 and a null register class pointer.
3641 virtual std::pair
<unsigned, const TargetRegisterClass
*>
3642 getRegForInlineAsmConstraint(const TargetRegisterInfo
*TRI
,
3643 StringRef Constraint
, MVT VT
) const;
3645 virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode
) const {
3646 if (ConstraintCode
== "i")
3647 return InlineAsm::Constraint_i
;
3648 else if (ConstraintCode
== "m")
3649 return InlineAsm::Constraint_m
;
3650 return InlineAsm::Constraint_Unknown
;
3653 /// Try to replace an X constraint, which matches anything, with another that
3654 /// has more specific requirements based on the type of the corresponding
3655 /// operand. This returns null if there is no replacement to make.
3656 virtual const char *LowerXConstraint(EVT ConstraintVT
) const;
3658 /// Lower the specified operand into the Ops vector. If it is invalid, don't
3659 /// add anything to Ops.
3660 virtual void LowerAsmOperandForConstraint(SDValue Op
, std::string
&Constraint
,
3661 std::vector
<SDValue
> &Ops
,
3662 SelectionDAG
&DAG
) const;
3664 // Lower custom output constraints. If invalid, return SDValue().
3665 virtual SDValue
LowerAsmOutputForConstraint(SDValue
&Chain
, SDValue
&Flag
,
3667 const AsmOperandInfo
&OpInfo
,
3668 SelectionDAG
&DAG
) const;
3670 //===--------------------------------------------------------------------===//
3671 // Div utility functions
3673 SDValue
BuildSDIV(SDNode
*N
, SelectionDAG
&DAG
, bool IsAfterLegalization
,
3674 SmallVectorImpl
<SDNode
*> &Created
) const;
3675 SDValue
BuildUDIV(SDNode
*N
, SelectionDAG
&DAG
, bool IsAfterLegalization
,
3676 SmallVectorImpl
<SDNode
*> &Created
) const;
3678 /// Targets may override this function to provide custom SDIV lowering for
3679 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
3680 /// assumes SDIV is expensive and replaces it with a series of other integer
3682 virtual SDValue
BuildSDIVPow2(SDNode
*N
, const APInt
&Divisor
,
3684 SmallVectorImpl
<SDNode
*> &Created
) const;
3686 /// Indicate whether this target prefers to combine FDIVs with the same
3687 /// divisor. If the transform should never be done, return zero. If the
3688 /// transform should be done, return the minimum number of divisor uses
3689 /// that must exist.
3690 virtual unsigned combineRepeatedFPDivisors() const {
3694 /// Hooks for building estimates in place of slower divisions and square
3697 /// Return either a square root or its reciprocal estimate value for the input
3699 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3700 /// 'Enabled' as set by a potential default override attribute.
3701 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3702 /// refinement iterations required to generate a sufficient (though not
3703 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3704 /// The boolean UseOneConstNR output is used to select a Newton-Raphson
3705 /// algorithm implementation that uses either one or two constants.
3706 /// The boolean Reciprocal is used to select whether the estimate is for the
3707 /// square root of the input operand or the reciprocal of its square root.
3708 /// A target may choose to implement its own refinement within this function.
3709 /// If that's true, then return '0' as the number of RefinementSteps to avoid
3710 /// any further refinement of the estimate.
3711 /// An empty SDValue return means no estimate sequence can be created.
3712 virtual SDValue
getSqrtEstimate(SDValue Operand
, SelectionDAG
&DAG
,
3713 int Enabled
, int &RefinementSteps
,
3714 bool &UseOneConstNR
, bool Reciprocal
) const {
3718 /// Return a reciprocal estimate value for the input operand.
3719 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3720 /// 'Enabled' as set by a potential default override attribute.
3721 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3722 /// refinement iterations required to generate a sufficient (though not
3723 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3724 /// A target may choose to implement its own refinement within this function.
3725 /// If that's true, then return '0' as the number of RefinementSteps to avoid
3726 /// any further refinement of the estimate.
3727 /// An empty SDValue return means no estimate sequence can be created.
3728 virtual SDValue
getRecipEstimate(SDValue Operand
, SelectionDAG
&DAG
,
3729 int Enabled
, int &RefinementSteps
) const {
3733 //===--------------------------------------------------------------------===//
3734 // Legalization utility functions
3737 /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
3738 /// respectively, each computing an n/2-bit part of the result.
3739 /// \param Result A vector that will be filled with the parts of the result
3740 /// in little-endian order.
3741 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3742 /// if you want to control how low bits are extracted from the LHS.
3743 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3744 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3745 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3746 /// \returns true if the node has been expanded, false if it has not
3747 bool expandMUL_LOHI(unsigned Opcode
, EVT VT
, SDLoc dl
, SDValue LHS
,
3748 SDValue RHS
, SmallVectorImpl
<SDValue
> &Result
, EVT HiLoVT
,
3749 SelectionDAG
&DAG
, MulExpansionKind Kind
,
3750 SDValue LL
= SDValue(), SDValue LH
= SDValue(),
3751 SDValue RL
= SDValue(), SDValue RH
= SDValue()) const;
3753 /// Expand a MUL into two nodes. One that computes the high bits of
3754 /// the result and one that computes the low bits.
3755 /// \param HiLoVT The value type to use for the Lo and Hi nodes.
3756 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3757 /// if you want to control how low bits are extracted from the LHS.
3758 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3759 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3760 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3761 /// \returns true if the node has been expanded. false if it has not
3762 bool expandMUL(SDNode
*N
, SDValue
&Lo
, SDValue
&Hi
, EVT HiLoVT
,
3763 SelectionDAG
&DAG
, MulExpansionKind Kind
,
3764 SDValue LL
= SDValue(), SDValue LH
= SDValue(),
3765 SDValue RL
= SDValue(), SDValue RH
= SDValue()) const;
3767 /// Expand funnel shift.
3768 /// \param N Node to expand
3769 /// \param Result output after conversion
3770 /// \returns True, if the expansion was successful, false otherwise
3771 bool expandFunnelShift(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3773 /// Expand rotations.
3774 /// \param N Node to expand
3775 /// \param Result output after conversion
3776 /// \returns True, if the expansion was successful, false otherwise
3777 bool expandROT(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3779 /// Expand float(f32) to SINT(i64) conversion
3780 /// \param N Node to expand
3781 /// \param Result output after conversion
3782 /// \returns True, if the expansion was successful, false otherwise
3783 bool expandFP_TO_SINT(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3785 /// Expand float to UINT conversion
3786 /// \param N Node to expand
3787 /// \param Result output after conversion
3788 /// \returns True, if the expansion was successful, false otherwise
3789 bool expandFP_TO_UINT(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3791 /// Expand UINT(i64) to double(f64) conversion
3792 /// \param N Node to expand
3793 /// \param Result output after conversion
3794 /// \returns True, if the expansion was successful, false otherwise
3795 bool expandUINT_TO_FP(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3797 /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
3798 SDValue
expandFMINNUM_FMAXNUM(SDNode
*N
, SelectionDAG
&DAG
) const;
3800 /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
3801 /// vector nodes can only succeed if all operations are legal/custom.
3802 /// \param N Node to expand
3803 /// \param Result output after conversion
3804 /// \returns True, if the expansion was successful, false otherwise
3805 bool expandCTPOP(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3807 /// Expand CTLZ/CTLZ_ZERO_UNDEF nodes. Expands vector/scalar CTLZ nodes,
3808 /// vector nodes can only succeed if all operations are legal/custom.
3809 /// \param N Node to expand
3810 /// \param Result output after conversion
3811 /// \returns True, if the expansion was successful, false otherwise
3812 bool expandCTLZ(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3814 /// Expand CTTZ/CTTZ_ZERO_UNDEF nodes. Expands vector/scalar CTTZ nodes,
3815 /// vector nodes can only succeed if all operations are legal/custom.
3816 /// \param N Node to expand
3817 /// \param Result output after conversion
3818 /// \returns True, if the expansion was successful, false otherwise
3819 bool expandCTTZ(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3821 /// Expand ABS nodes. Expands vector/scalar ABS nodes,
3822 /// vector nodes can only succeed if all operations are legal/custom.
3823 /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
3824 /// \param N Node to expand
3825 /// \param Result output after conversion
3826 /// \returns True, if the expansion was successful, false otherwise
3827 bool expandABS(SDNode
*N
, SDValue
&Result
, SelectionDAG
&DAG
) const;
3829 /// Turn load of vector type into a load of the individual elements.
3830 /// \param LD load to expand
3831 /// \returns MERGE_VALUEs of the scalar loads with their chains.
3832 SDValue
scalarizeVectorLoad(LoadSDNode
*LD
, SelectionDAG
&DAG
) const;
3834 // Turn a store of a vector type into stores of the individual elements.
3835 /// \param ST Store with a vector value type
3836 /// \returns MERGE_VALUs of the individual store chains.
3837 SDValue
scalarizeVectorStore(StoreSDNode
*ST
, SelectionDAG
&DAG
) const;
3839 /// Expands an unaligned load to 2 half-size loads for an integer, and
3840 /// possibly more for vectors.
3841 std::pair
<SDValue
, SDValue
> expandUnalignedLoad(LoadSDNode
*LD
,
3842 SelectionDAG
&DAG
) const;
3844 /// Expands an unaligned store to 2 half-size stores for integer values, and
3845 /// possibly more for vectors.
3846 SDValue
expandUnalignedStore(StoreSDNode
*ST
, SelectionDAG
&DAG
) const;
3848 /// Increments memory address \p Addr according to the type of the value
3849 /// \p DataVT that should be stored. If the data is stored in compressed
3850 /// form, the memory address should be incremented according to the number of
3851 /// the stored elements. This number is equal to the number of '1's bits
3853 /// \p DataVT is a vector type. \p Mask is a vector value.
3854 /// \p DataVT and \p Mask have the same number of vector elements.
3855 SDValue
IncrementMemoryAddress(SDValue Addr
, SDValue Mask
, const SDLoc
&DL
,
3856 EVT DataVT
, SelectionDAG
&DAG
,
3857 bool IsCompressedMemory
) const;
3859 /// Get a pointer to vector element \p Idx located in memory for a vector of
3860 /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
3861 /// bounds the returned pointer is unspecified, but will be within the vector
3863 SDValue
getVectorElementPointer(SelectionDAG
&DAG
, SDValue VecPtr
, EVT VecVT
,
3864 SDValue Index
) const;
3866 /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
3867 /// method accepts integers as its arguments.
3868 SDValue
expandAddSubSat(SDNode
*Node
, SelectionDAG
&DAG
) const;
3870 /// Method for building the DAG expansion of ISD::SMULFIX. This method accepts
3871 /// integers as its arguments.
3872 SDValue
expandFixedPointMul(SDNode
*Node
, SelectionDAG
&DAG
) const;
3874 /// Method for building the DAG expansion of ISD::[US]MULO, returning the two
3875 /// result values as a pair.
3876 std::pair
<SDValue
, SDValue
> expandMULO(SDNode
*Node
, SelectionDAG
&DAG
) const;
3878 //===--------------------------------------------------------------------===//
3879 // Instruction Emitting Hooks
3882 /// This method should be implemented by targets that mark instructions with
3883 /// the 'usesCustomInserter' flag. These instructions are special in various
3884 /// ways, which require special support to insert. The specified MachineInstr
3885 /// is created but not inserted into any basic blocks, and this method is
3886 /// called to expand it into a sequence of instructions, potentially also
3887 /// creating new basic blocks and control flow.
3888 /// As long as the returned basic block is different (i.e., we created a new
3889 /// one), the custom inserter is free to modify the rest of \p MBB.
3890 virtual MachineBasicBlock
*
3891 EmitInstrWithCustomInserter(MachineInstr
&MI
, MachineBasicBlock
*MBB
) const;
3893 /// This method should be implemented by targets that mark instructions with
3894 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
3895 /// instruction selection by target hooks. e.g. To fill in optional defs for
3896 /// ARM 's' setting instructions.
3897 virtual void AdjustInstrPostInstrSelection(MachineInstr
&MI
,
3898 SDNode
*Node
) const;
3900 /// If this function returns true, SelectionDAGBuilder emits a
3901 /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
3902 virtual bool useLoadStackGuardNode() const {
3906 virtual SDValue
emitStackGuardXorFP(SelectionDAG
&DAG
, SDValue Val
,
3907 const SDLoc
&DL
) const {
3908 llvm_unreachable("not implemented for this target");
3911 /// Lower TLS global address SDNode for target independent emulated TLS model.
3912 virtual SDValue
LowerToTLSEmulatedModel(const GlobalAddressSDNode
*GA
,
3913 SelectionDAG
&DAG
) const;
3915 /// Expands target specific indirect branch for the case of JumpTable
3917 virtual SDValue
expandIndirectJTBranch(const SDLoc
& dl
, SDValue Value
, SDValue Addr
,
3918 SelectionDAG
&DAG
) const {
3919 return DAG
.getNode(ISD::BRIND
, dl
, MVT::Other
, Value
, Addr
);
3922 // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
3923 // If we're comparing for equality to zero and isCtlzFast is true, expose the
3924 // fact that this can be implemented as a ctlz/srl pair, so that the dag
3925 // combiner can fold the new nodes.
3926 SDValue
lowerCmpEqZeroToCtlzSrl(SDValue Op
, SelectionDAG
&DAG
) const;
3929 SDValue
foldSetCCWithAnd(EVT VT
, SDValue N0
, SDValue N1
, ISD::CondCode Cond
,
3930 const SDLoc
&DL
, DAGCombinerInfo
&DCI
) const;
3931 SDValue
foldSetCCWithBinOp(EVT VT
, SDValue N0
, SDValue N1
, ISD::CondCode Cond
,
3932 const SDLoc
&DL
, DAGCombinerInfo
&DCI
) const;
3934 SDValue
optimizeSetCCOfSignedTruncationCheck(EVT SCCVT
, SDValue N0
,
3935 SDValue N1
, ISD::CondCode Cond
,
3936 DAGCombinerInfo
&DCI
,
3937 const SDLoc
&DL
) const;
3940 /// Given an LLVM IR type and return type attributes, compute the return value
3941 /// EVTs and flags, and optionally also the offsets, if the return value is
3942 /// being lowered to memory.
3943 void GetReturnInfo(CallingConv::ID CC
, Type
*ReturnType
, AttributeList attr
,
3944 SmallVectorImpl
<ISD::OutputArg
> &Outs
,
3945 const TargetLowering
&TLI
, const DataLayout
&DL
);
3947 } // end namespace llvm
3949 #endif // LLVM_CODEGEN_TARGETLOWERING_H