1 //===- llvm/Target/TargetLowering.h - Target Lowering Info ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file describes how to lower LLVM code to machine code. This has two
14 /// 1. Which ValueTypes are natively supported by the target.
15 /// 2. Which operations are supported for supported ValueTypes.
16 /// 3. Cost thresholds for alternative implementations of certain operations.
18 /// In addition it has a few other components, like information about FP
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_TARGET_TARGETLOWERING_H
24 #define LLVM_TARGET_TARGETLOWERING_H
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/CodeGen/DAGCombine.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineValueType.h"
35 #include "llvm/CodeGen/RuntimeLibcalls.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/CodeGen/SelectionDAGNodes.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/Target/TargetCallingConv.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.
167 /// Enum that specifies when a multiplication should be expanded.
168 enum class MulExpansionKind {
169 Always, // Always expand the instruction.
170 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
176 Value *Val = nullptr;
177 SDValue Node = SDValue();
187 bool IsSwiftSelf : 1;
188 bool IsSwiftError : 1;
189 uint16_t Alignment = 0;
192 : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
193 IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
194 IsSwiftSelf(false), IsSwiftError(false) {}
196 void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx);
198 using ArgListTy = std::vector<ArgListEntry>;
200 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
201 ArgListTy &Args) const {};
203 static ISD::NodeType getExtendForContent(BooleanContent Content) {
205 case UndefinedBooleanContent:
206 // Extend by adding rubbish bits.
207 return ISD::ANY_EXTEND;
208 case ZeroOrOneBooleanContent:
209 // Extend by adding zero bits.
210 return ISD::ZERO_EXTEND;
211 case ZeroOrNegativeOneBooleanContent:
212 // Extend by copying the sign bit.
213 return ISD::SIGN_EXTEND;
215 llvm_unreachable("Invalid content kind");
218 /// NOTE: The TargetMachine owns TLOF.
219 explicit TargetLoweringBase(const TargetMachine &TM);
220 TargetLoweringBase(const TargetLoweringBase &) = delete;
221 TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
222 virtual ~TargetLoweringBase() = default;
225 /// \brief Initialize all of the actions to default values.
229 const TargetMachine &getTargetMachine() const { return TM; }
231 virtual bool useSoftFloat() const { return false; }
233 /// Return the pointer type for the given address space, defaults to
234 /// the pointer type from the data layout.
235 /// FIXME: The default needs to be removed once all the code is updated.
236 MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
237 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
240 /// Return the type for frame index, which is determined by
241 /// the alloca address space specified through the data layout.
242 MVT getFrameIndexTy(const DataLayout &DL) const {
243 return getPointerTy(DL, DL.getAllocaAddrSpace());
246 /// Return the type for operands of fence.
247 /// TODO: Let fence operands be of i32 type and remove this.
248 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
249 return getPointerTy(DL);
252 /// EVT is not used in-tree, but is used by out-of-tree target.
253 /// A documentation for this function would be nice...
254 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
256 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const;
258 /// Returns the type to be used for the index operand of:
259 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
260 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
261 virtual MVT getVectorIdxTy(const DataLayout &DL) const {
262 return getPointerTy(DL);
265 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
269 /// Return true if multiple condition registers are available.
270 bool hasMultipleConditionRegisters() const {
271 return HasMultipleConditionRegisters;
274 /// Return true if the target has BitExtract instructions.
275 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
277 /// Return the preferred vector type legalization action.
278 virtual TargetLoweringBase::LegalizeTypeAction
279 getPreferredVectorAction(EVT VT) const {
280 // The default action for one element vectors is to scalarize
281 if (VT.getVectorNumElements() == 1)
282 return TypeScalarizeVector;
283 // The default action for other vectors is to promote
284 return TypePromoteInteger;
287 // There are two general methods for expanding a BUILD_VECTOR node:
288 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
290 // 2. Build the vector on the stack and then load it.
291 // If this function returns true, then method (1) will be used, subject to
292 // the constraint that all of the necessary shuffles are legal (as determined
293 // by isShuffleMaskLegal). If this function returns false, then method (2) is
294 // always used. The vector type, and the number of defined values, are
297 shouldExpandBuildVectorWithShuffles(EVT /* VT */,
298 unsigned DefinedValues) const {
299 return DefinedValues < 3;
302 /// Return true if integer divide is usually cheaper than a sequence of
303 /// several shifts, adds, and multiplies for this target.
304 /// The definition of "cheaper" may depend on whether we're optimizing
305 /// for speed or for size.
306 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
308 /// Return true if the target can handle a standalone remainder operation.
309 virtual bool hasStandaloneRem(EVT VT) const {
313 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
314 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
315 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
319 /// Reciprocal estimate status values used by the functions below.
320 enum ReciprocalEstimate : int {
326 /// Return a ReciprocalEstimate enum value for a square root of the given type
327 /// based on the function's attributes. If the operation is not overridden by
328 /// the function's attributes, "Unspecified" is returned and target defaults
329 /// are expected to be used for instruction selection.
330 int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
332 /// Return a ReciprocalEstimate enum value for a division of the given type
333 /// based on the function's attributes. If the operation is not overridden by
334 /// the function's attributes, "Unspecified" is returned and target defaults
335 /// are expected to be used for instruction selection.
336 int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
338 /// Return the refinement step count for a square root of the given type based
339 /// on the function's attributes. If the operation is not overridden by
340 /// the function's attributes, "Unspecified" is returned and target defaults
341 /// are expected to be used for instruction selection.
342 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
344 /// Return the refinement step count for a division of the given type based
345 /// on the function's attributes. If the operation is not overridden by
346 /// the function's attributes, "Unspecified" is returned and target defaults
347 /// are expected to be used for instruction selection.
348 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
350 /// Returns true if target has indicated at least one type should be bypassed.
351 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
353 /// Returns map of slow types for division or remainder with corresponding
355 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
356 return BypassSlowDivWidths;
359 /// Return true if Flow Control is an expensive operation that should be
361 bool isJumpExpensive() const { return JumpIsExpensive; }
363 /// Return true if selects are only cheaper than branches if the branch is
364 /// unlikely to be predicted right.
365 bool isPredictableSelectExpensive() const {
366 return PredictableSelectIsExpensive;
369 /// If a branch or a select condition is skewed in one direction by more than
370 /// this factor, it is very likely to be predicted correctly.
371 virtual BranchProbability getPredictableBranchThreshold() const;
373 /// Return true if the following transform is beneficial:
374 /// fold (conv (load x)) -> (load (conv*)x)
375 /// On architectures that don't natively support some vector loads
376 /// efficiently, casting the load to a smaller vector of larger types and
377 /// loading is more efficient, however, this can be undone by optimizations in
379 virtual bool isLoadBitCastBeneficial(EVT LoadVT,
380 EVT BitcastVT) const {
381 // Don't do if we could do an indexed load on the original type, but not on
383 if (!LoadVT.isSimple() || !BitcastVT.isSimple())
386 MVT LoadMVT = LoadVT.getSimpleVT();
388 // Don't bother doing this if it's just going to be promoted again later, as
389 // doing so might interfere with other combines.
390 if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
391 getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
397 /// Return true if the following transform is beneficial:
398 /// (store (y (conv x)), y*)) -> (store x, (x*))
399 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT) const {
400 // Default to the same logic as loads.
401 return isLoadBitCastBeneficial(StoreVT, BitcastVT);
404 /// Return true if it is expected to be cheaper to do a store of a non-zero
405 /// vector constant with the given size and type for the address space than to
406 /// store the individual scalar element constants.
407 virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
409 unsigned AddrSpace) const {
413 /// Should we merge stores after Legalization (generally
414 /// better quality) or before (simpler)
415 virtual bool mergeStoresAfterLegalization() const { return false; }
417 /// Returns if it's reasonable to merge stores to MemVT size.
418 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
419 const SelectionDAG &DAG) const {
423 /// \brief Return true if it is cheap to speculate a call to intrinsic cttz.
424 virtual bool isCheapToSpeculateCttz() const {
428 /// \brief Return true if it is cheap to speculate a call to intrinsic ctlz.
429 virtual bool isCheapToSpeculateCtlz() const {
433 /// \brief Return true if ctlz instruction is fast.
434 virtual bool isCtlzFast() const {
438 /// Return true if it is safe to transform an integer-domain bitwise operation
439 /// into the equivalent floating-point operation. This should be set to true
440 /// if the target has IEEE-754-compliant fabs/fneg operations for the input
442 virtual bool hasBitPreservingFPLogic(EVT VT) const {
446 /// \brief Return true if it is cheaper to split the store of a merged int val
447 /// from a pair of smaller values into multiple stores.
448 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
452 /// \brief Return if the target supports combining a
455 /// %andResult = and %val1, #mask
456 /// %icmpResult = icmp %andResult, 0
458 /// into a single machine instruction of a form like:
460 /// cc = test %register, #mask
462 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
466 /// Use bitwise logic to make pairs of compares more efficient. For example:
467 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
468 /// This should be true when it takes more than one instruction to lower
469 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
470 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
471 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
475 /// Return the preferred operand type if the target has a quick way to compare
476 /// integer values of the given size. Assume that any legal integer type can
477 /// be compared efficiently. Targets may override this to allow illegal wide
478 /// types to return a vector type if there is support to compare that type.
479 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
480 MVT VT = MVT::getIntegerVT(NumBits);
481 return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
484 /// Return true if the target should transform:
485 /// (X & Y) == Y ---> (~X & Y) == 0
486 /// (X & Y) != Y ---> (~X & Y) != 0
488 /// This may be profitable if the target has a bitwise and-not operation that
489 /// sets comparison flags. A target may want to limit the transformation based
490 /// on the type of Y or if Y is a constant.
492 /// Note that the transform will not occur if Y is known to be a power-of-2
493 /// because a mask and compare of a single bit can be handled by inverting the
494 /// predicate, for example:
495 /// (X & 8) == 8 ---> (X & 8) != 0
496 virtual bool hasAndNotCompare(SDValue Y) const {
500 /// Return true if the target has a bitwise and-not operation:
502 /// This can be used to simplify select or other instructions.
503 virtual bool hasAndNot(SDValue X) const {
504 // If the target has the more complex version of this operation, assume that
505 // it has this operation too.
506 return hasAndNotCompare(X);
509 /// \brief Return true if the target wants to use the optimization that
510 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
511 /// promotedInst1(...(promotedInstN(ext(load)))).
512 bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
514 /// Return true if the target can combine store(extractelement VectorTy,
516 /// \p Cost[out] gives the cost of that transformation when this is true.
517 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
518 unsigned &Cost) const {
522 /// Return true if target supports floating point exceptions.
523 bool hasFloatingPointExceptions() const {
524 return HasFloatingPointExceptions;
527 /// Return true if target always beneficiates from combining into FMA for a
528 /// given value type. This must typically return false on targets where FMA
529 /// takes more cycles to execute than FADD.
530 virtual bool enableAggressiveFMAFusion(EVT VT) const {
534 /// Return the ValueType of the result of SETCC operations.
535 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
538 /// Return the ValueType for comparison libcalls. Comparions libcalls include
539 /// floating point comparion calls, and Ordered/Unordered check calls on
540 /// floating point numbers.
542 MVT::SimpleValueType getCmpLibcallReturnType() const;
544 /// For targets without i1 registers, this gives the nature of the high-bits
545 /// of boolean values held in types wider than i1.
547 /// "Boolean values" are special true/false values produced by nodes like
548 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
549 /// Not to be confused with general values promoted from i1. Some cpus
550 /// distinguish between vectors of boolean and scalars; the isVec parameter
551 /// selects between the two kinds. For example on X86 a scalar boolean should
552 /// be zero extended from i1, while the elements of a vector of booleans
553 /// should be sign extended from i1.
555 /// Some cpus also treat floating point types the same way as they treat
556 /// vectors instead of the way they treat scalars.
557 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
559 return BooleanVectorContents;
560 return isFloat ? BooleanFloatContents : BooleanContents;
563 BooleanContent getBooleanContents(EVT Type) const {
564 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
567 /// Return target scheduling preference.
568 Sched::Preference getSchedulingPreference() const {
569 return SchedPreferenceInfo;
572 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
573 /// for different nodes. This function returns the preference (or none) for
575 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
579 /// Return the register class that should be used for the specified value
581 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
582 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
583 assert(RC && "This value type is not natively supported!");
587 /// Return the 'representative' register class for the specified value
590 /// The 'representative' register class is the largest legal super-reg
591 /// register class for the register class of the value type. For example, on
592 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
593 /// register class is GR64 on x86_64.
594 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
595 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
599 /// Return the cost of the 'representative' register class for the specified
601 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
602 return RepRegClassCostForVT[VT.SimpleTy];
605 /// Return true if the target has native support for the specified value type.
606 /// This means that it has a register that directly holds it without
607 /// promotions or expansions.
608 bool isTypeLegal(EVT VT) const {
609 assert(!VT.isSimple() ||
610 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
611 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
614 class ValueTypeActionImpl {
615 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
616 /// that indicates how instruction selection should deal with the type.
617 LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
620 ValueTypeActionImpl() {
621 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
625 LegalizeTypeAction getTypeAction(MVT VT) const {
626 return ValueTypeActions[VT.SimpleTy];
629 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
630 ValueTypeActions[VT.SimpleTy] = Action;
634 const ValueTypeActionImpl &getValueTypeActions() const {
635 return ValueTypeActions;
638 /// Return how we should legalize values of this type, either it is already
639 /// legal (return 'Legal') or we need to promote it to a larger type (return
640 /// 'Promote'), or we need to expand it into multiple registers of smaller
641 /// integer type (return 'Expand'). 'Custom' is not an option.
642 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
643 return getTypeConversion(Context, VT).first;
645 LegalizeTypeAction getTypeAction(MVT VT) const {
646 return ValueTypeActions.getTypeAction(VT);
649 /// For types supported by the target, this is an identity function. For
650 /// types that must be promoted to larger types, this returns the larger type
651 /// to promote to. For integer types that are larger than the largest integer
652 /// register, this contains one step in the expansion to get to the smaller
653 /// register. For illegal floating point types, this returns the integer type
655 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
656 return getTypeConversion(Context, VT).second;
659 /// For types supported by the target, this is an identity function. For
660 /// types that must be expanded (i.e. integer types that are larger than the
661 /// largest integer register or illegal floating point types), this returns
662 /// the largest legal type it will be expanded to.
663 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
664 assert(!VT.isVector());
666 switch (getTypeAction(Context, VT)) {
669 case TypeExpandInteger:
670 VT = getTypeToTransformTo(Context, VT);
673 llvm_unreachable("Type is not legal nor is it to be expanded!");
678 /// Vector types are broken down into some number of legal first class types.
679 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
680 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
681 /// turns into 4 EVT::i32 values with both PPC and X86.
683 /// This method returns the number of registers needed, and the VT for each
684 /// register. It also returns the VT and quantity of the intermediate values
685 /// before they are promoted/expanded.
686 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
688 unsigned &NumIntermediates,
689 MVT &RegisterVT) const;
691 /// Certain targets such as MIPS require that some types such as vectors are
692 /// always broken down into scalars in some contexts. This occurs even if the
693 /// vector type is legal.
694 virtual unsigned getVectorTypeBreakdownForCallingConv(
695 LLVMContext &Context, EVT VT, EVT &IntermediateVT,
696 unsigned &NumIntermediates, MVT &RegisterVT) const {
697 return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
701 struct IntrinsicInfo {
702 unsigned opc = 0; // target opcode
703 EVT memVT; // memory VT
704 const Value* ptrVal = nullptr; // value representing memory location
705 int offset = 0; // offset off of ptrVal
706 unsigned size = 0; // the size of the memory location
707 // (taken from memVT if zero)
708 unsigned align = 1; // alignment
709 bool vol = false; // is volatile?
710 bool readMem = false; // reads memory?
711 bool writeMem = false; // writes memory?
713 IntrinsicInfo() = default;
716 /// Given an intrinsic, checks if on the target the intrinsic will need to map
717 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
718 /// true and store the intrinsic information into the IntrinsicInfo that was
719 /// passed to the function.
720 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
721 unsigned /*Intrinsic*/) const {
725 /// Returns true if the target can instruction select the specified FP
726 /// immediate natively. If false, the legalizer will materialize the FP
727 /// immediate as a load from a constant pool.
728 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
732 /// Targets can use this to indicate that they only support *some*
733 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
734 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
736 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
741 /// Returns true if the operation can trap for the value type.
743 /// VT must be a legal type. By default, we optimistically assume most
744 /// operations don't trap except for integer divide and remainder.
745 virtual bool canOpTrap(unsigned Op, EVT VT) const;
747 /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
748 /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
749 /// a VAND with a constant pool entry.
750 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
755 /// Return how this operation should be treated: either it is legal, needs to
756 /// be promoted to a larger size, needs to be expanded to some other code
757 /// sequence, or the target has a custom expander for it.
758 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
759 if (VT.isExtended()) return Expand;
760 // If a target-specific SDNode requires legalization, require the target
761 // to provide custom legalization for it.
762 if (Op >= array_lengthof(OpActions[0])) return Custom;
763 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
766 /// Return true if the specified operation is legal on this target or can be
767 /// made legal with custom lowering. This is used to help guide high-level
768 /// lowering decisions.
769 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
770 return (VT == MVT::Other || isTypeLegal(VT)) &&
771 (getOperationAction(Op, VT) == Legal ||
772 getOperationAction(Op, VT) == Custom);
775 /// Return true if the specified operation is legal on this target or can be
776 /// made legal using promotion. This is used to help guide high-level lowering
778 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
779 return (VT == MVT::Other || isTypeLegal(VT)) &&
780 (getOperationAction(Op, VT) == Legal ||
781 getOperationAction(Op, VT) == Promote);
784 /// Return true if the specified operation is legal on this target or can be
785 /// made legal with custom lowering or using promotion. This is used to help
786 /// guide high-level lowering decisions.
787 bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const {
788 return (VT == MVT::Other || isTypeLegal(VT)) &&
789 (getOperationAction(Op, VT) == Legal ||
790 getOperationAction(Op, VT) == Custom ||
791 getOperationAction(Op, VT) == Promote);
794 /// Return true if the specified operation is illegal but has a custom lowering
795 /// on that type. This is used to help guide high-level lowering
797 bool isOperationCustom(unsigned Op, EVT VT) const {
798 return (!isTypeLegal(VT) && getOperationAction(Op, VT) == Custom);
801 /// Return true if lowering to a jump table is allowed.
802 bool areJTsAllowed(const Function *Fn) const {
803 if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
806 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
807 isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
810 /// Check whether the range [Low,High] fits in a machine word.
811 bool rangeFitsInWord(const APInt &Low, const APInt &High,
812 const DataLayout &DL) const {
813 // FIXME: Using the pointer type doesn't seem ideal.
814 uint64_t BW = DL.getPointerSizeInBits();
815 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
819 /// Return true if lowering to a jump table is suitable for a set of case
820 /// clusters which may contain \p NumCases cases, \p Range range of values.
821 /// FIXME: This function check the maximum table size and density, but the
822 /// minimum size is not checked. It would be nice if the the minimum size is
823 /// also combined within this function. Currently, the minimum size check is
824 /// performed in findJumpTable() in SelectionDAGBuiler and
825 /// getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
826 bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
827 uint64_t Range) const {
828 const bool OptForSize = SI->getParent()->getParent()->optForSize();
829 const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
830 const unsigned MaxJumpTableSize =
831 OptForSize || getMaximumJumpTableSize() == 0
833 : getMaximumJumpTableSize();
834 // Check whether a range of clusters is dense enough for a jump table.
835 if (Range <= MaxJumpTableSize &&
836 (NumCases * 100 >= Range * MinDensity)) {
842 /// Return true if lowering to a bit test is suitable for a set of case
843 /// clusters which contains \p NumDests unique destinations, \p Low and
844 /// \p High as its lowest and highest case values, and expects \p NumCmps
845 /// case value comparisons. Check if the number of destinations, comparison
846 /// metric, and range are all suitable.
847 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
848 const APInt &Low, const APInt &High,
849 const DataLayout &DL) const {
850 // FIXME: I don't think NumCmps is the correct metric: a single case and a
851 // range of cases both require only one branch to lower. Just looking at the
852 // number of clusters and destinations should be enough to decide whether to
855 // To lower a range with bit tests, the range must fit the bitwidth of a
857 if (!rangeFitsInWord(Low, High, DL))
860 // Decide whether it's profitable to lower this range with bit tests. Each
861 // destination requires a bit test and branch, and there is an overall range
862 // check branch. For a small number of clusters, separate comparisons might
863 // be cheaper, and for many destinations, splitting the range might be
865 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
866 (NumDests == 3 && NumCmps >= 6);
869 /// Return true if the specified operation is illegal on this target or
870 /// unlikely to be made legal with custom lowering. This is used to help guide
871 /// high-level lowering decisions.
872 bool isOperationExpand(unsigned Op, EVT VT) const {
873 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
876 /// Return true if the specified operation is legal on this target.
877 bool isOperationLegal(unsigned Op, EVT VT) const {
878 return (VT == MVT::Other || isTypeLegal(VT)) &&
879 getOperationAction(Op, VT) == Legal;
882 /// Return how this load with extension should be treated: either it is legal,
883 /// needs to be promoted to a larger size, needs to be expanded to some other
884 /// code sequence, or the target has a custom expander for it.
885 LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
887 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
888 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
889 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
890 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&
891 MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!");
892 unsigned Shift = 4 * ExtType;
893 return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
896 /// Return true if the specified load with extension is legal on this target.
897 bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
898 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
901 /// Return true if the specified load with extension is legal or custom
903 bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
904 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
905 getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
908 /// Return how this store with truncation should be treated: either it is
909 /// legal, needs to be promoted to a larger size, needs to be expanded to some
910 /// other code sequence, or the target has a custom expander for it.
911 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
912 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
913 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
914 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
915 assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
916 "Table isn't big enough!");
917 return TruncStoreActions[ValI][MemI];
920 /// Return true if the specified store with truncation is legal on this
922 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
923 return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
926 /// Return true if the specified store with truncation has solution on this
928 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
929 return isTypeLegal(ValVT) &&
930 (getTruncStoreAction(ValVT, MemVT) == Legal ||
931 getTruncStoreAction(ValVT, MemVT) == Custom);
934 /// Return how the indexed load should be treated: either it is legal, needs
935 /// to be promoted to a larger size, needs to be expanded to some other code
936 /// sequence, or the target has a custom expander for it.
938 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
939 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
940 "Table isn't big enough!");
941 unsigned Ty = (unsigned)VT.SimpleTy;
942 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
945 /// Return true if the specified indexed load is legal on this target.
946 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
947 return VT.isSimple() &&
948 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
949 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
952 /// Return how the indexed store should be treated: either it is legal, needs
953 /// to be promoted to a larger size, needs to be expanded to some other code
954 /// sequence, or the target has a custom expander for it.
956 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
957 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
958 "Table isn't big enough!");
959 unsigned Ty = (unsigned)VT.SimpleTy;
960 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
963 /// Return true if the specified indexed load is legal on this target.
964 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
965 return VT.isSimple() &&
966 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
967 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
970 /// Return how the condition code should be treated: either it is legal, needs
971 /// to be expanded to some other code sequence, or the target has a custom
974 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
975 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
976 ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
977 "Table isn't big enough!");
978 // See setCondCodeAction for how this is encoded.
979 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
980 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
981 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
982 assert(Action != Promote && "Can't promote condition code!");
986 /// Return true if the specified condition code is legal on this target.
987 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
989 getCondCodeAction(CC, VT) == Legal ||
990 getCondCodeAction(CC, VT) == Custom;
993 /// If the action for this operation is to promote, this method returns the
994 /// ValueType to promote to.
995 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
996 assert(getOperationAction(Op, VT) == Promote &&
997 "This operation isn't promoted!");
999 // See if this has an explicit type specified.
1000 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1001 MVT::SimpleValueType>::const_iterator PTTI =
1002 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1003 if (PTTI != PromoteToType.end()) return PTTI->second;
1005 assert((VT.isInteger() || VT.isFloatingPoint()) &&
1006 "Cannot autopromote this type, add it with AddPromotedToType.");
1010 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1011 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1012 "Didn't find type to promote to!");
1013 } while (!isTypeLegal(NVT) ||
1014 getOperationAction(Op, NVT) == Promote);
1018 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1019 /// operations except for the pointer size. If AllowUnknown is true, this
1020 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1021 /// otherwise it will assert.
1022 EVT getValueType(const DataLayout &DL, Type *Ty,
1023 bool AllowUnknown = false) const {
1024 // Lower scalar pointers to native pointer types.
1025 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1026 return getPointerTy(DL, PTy->getAddressSpace());
1028 if (Ty->isVectorTy()) {
1029 VectorType *VTy = cast<VectorType>(Ty);
1030 Type *Elm = VTy->getElementType();
1031 // Lower vectors of pointers to native pointer types.
1032 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1033 EVT PointerTy(getPointerTy(DL, PT->getAddressSpace()));
1034 Elm = PointerTy.getTypeForEVT(Ty->getContext());
1037 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1038 VTy->getNumElements());
1040 return EVT::getEVT(Ty, AllowUnknown);
1043 /// Return the MVT corresponding to this LLVM type. See getValueType.
1044 MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
1045 bool AllowUnknown = false) const {
1046 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1049 /// Return the desired alignment for ByVal or InAlloca aggregate function
1050 /// arguments in the caller parameter area. This is the actual alignment, not
1052 virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1054 /// Return the type of registers that this ValueType will eventually require.
1055 MVT getRegisterType(MVT VT) const {
1056 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
1057 return RegisterTypeForVT[VT.SimpleTy];
1060 /// Return the type of registers that this ValueType will eventually require.
1061 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1062 if (VT.isSimple()) {
1063 assert((unsigned)VT.getSimpleVT().SimpleTy <
1064 array_lengthof(RegisterTypeForVT));
1065 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1067 if (VT.isVector()) {
1070 unsigned NumIntermediates;
1071 (void)getVectorTypeBreakdown(Context, VT, VT1,
1072 NumIntermediates, RegisterVT);
1075 if (VT.isInteger()) {
1076 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1078 llvm_unreachable("Unsupported extended type!");
1081 /// Return the number of registers that this ValueType will eventually
1084 /// This is one for any types promoted to live in larger registers, but may be
1085 /// more than one for types (like i64) that are split into pieces. For types
1086 /// like i140, which are first promoted then expanded, it is the number of
1087 /// registers needed to hold all the bits of the original type. For an i140
1088 /// on a 32 bit machine this means 5 registers.
1089 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1090 if (VT.isSimple()) {
1091 assert((unsigned)VT.getSimpleVT().SimpleTy <
1092 array_lengthof(NumRegistersForVT));
1093 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1095 if (VT.isVector()) {
1098 unsigned NumIntermediates;
1099 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1101 if (VT.isInteger()) {
1102 unsigned BitWidth = VT.getSizeInBits();
1103 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1104 return (BitWidth + RegWidth - 1) / RegWidth;
1106 llvm_unreachable("Unsupported extended type!");
1109 /// Certain combinations of ABIs, Targets and features require that types
1110 /// are legal for some operations and not for other operations.
1111 /// For MIPS all vector types must be passed through the integer register set.
1112 virtual MVT getRegisterTypeForCallingConv(MVT VT) const {
1113 return getRegisterType(VT);
1116 virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
1118 return getRegisterType(Context, VT);
1121 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1122 /// this occurs when a vector type is used, as vector are passed through the
1123 /// integer register set.
1124 virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1126 return getNumRegisters(Context, VT);
1129 /// Certain targets have context senstive alignment requirements, where one
1130 /// type has the alignment requirement of another type.
1131 virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy,
1132 DataLayout DL) const {
1133 return DL.getABITypeAlignment(ArgTy);
1136 /// If true, then instruction selection should seek to shrink the FP constant
1137 /// of the specified type to a smaller type in order to save space and / or
1139 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1141 // Return true if it is profitable to reduce the given load node to a smaller
1144 // e.g. (i16 (trunc (i32 (load x))) -> i16 load x should be performed
1145 virtual bool shouldReduceLoadWidth(SDNode *Load,
1146 ISD::LoadExtType ExtTy,
1151 /// When splitting a value of the specified type into parts, does the Lo
1152 /// or Hi part come first? This usually follows the endianness, except
1153 /// for ppcf128, where the Hi part always comes first.
1154 bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1155 return DL.isBigEndian() || VT == MVT::ppcf128;
1158 /// If true, the target has custom DAG combine transformations that it can
1159 /// perform for the specified node.
1160 bool hasTargetDAGCombine(ISD::NodeType NT) const {
1161 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1162 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1165 unsigned getGatherAllAliasesMaxDepth() const {
1166 return GatherAllAliasesMaxDepth;
1169 /// Returns the size of the platform's va_list object.
1170 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1171 return getPointerTy(DL).getSizeInBits();
1174 /// \brief Get maximum # of store operations permitted for llvm.memset
1176 /// This function returns the maximum number of store operations permitted
1177 /// to replace a call to llvm.memset. The value is set by the target at the
1178 /// performance threshold for such a replacement. If OptSize is true,
1179 /// return the limit for functions that have OptSize attribute.
1180 unsigned getMaxStoresPerMemset(bool OptSize) const {
1181 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1184 /// \brief Get maximum # of store operations permitted for llvm.memcpy
1186 /// This function returns the maximum number of store operations permitted
1187 /// to replace a call to llvm.memcpy. The value is set by the target at the
1188 /// performance threshold for such a replacement. If OptSize is true,
1189 /// return the limit for functions that have OptSize attribute.
1190 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1191 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1194 /// Get maximum # of load operations permitted for memcmp
1196 /// This function returns the maximum number of load operations permitted
1197 /// to replace a call to memcmp. The value is set by the target at the
1198 /// performance threshold for such a replacement. If OptSize is true,
1199 /// return the limit for functions that have OptSize attribute.
1200 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1201 return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1204 /// \brief Get maximum # of store operations permitted for llvm.memmove
1206 /// This function returns the maximum number of store operations permitted
1207 /// to replace a call to llvm.memmove. The value is set by the target at the
1208 /// performance threshold for such a replacement. If OptSize is true,
1209 /// return the limit for functions that have OptSize attribute.
1210 unsigned getMaxStoresPerMemmove(bool OptSize) const {
1211 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1214 /// \brief Determine if the target supports unaligned memory accesses.
1216 /// This function returns true if the target allows unaligned memory accesses
1217 /// of the specified type in the given address space. If true, it also returns
1218 /// whether the unaligned memory access is "fast" in the last argument by
1219 /// reference. This is used, for example, in situations where an array
1220 /// copy/move/set is converted to a sequence of store operations. Its use
1221 /// helps to ensure that such replacements don't generate code that causes an
1222 /// alignment error (trap) on the target machine.
1223 virtual bool allowsMisalignedMemoryAccesses(EVT,
1224 unsigned AddrSpace = 0,
1226 bool * /*Fast*/ = nullptr) const {
1230 /// Return true if the target supports a memory access of this type for the
1231 /// given address space and alignment. If the access is allowed, the optional
1232 /// final parameter returns if the access is also fast (as defined by the
1234 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1235 unsigned AddrSpace = 0, unsigned Alignment = 1,
1236 bool *Fast = nullptr) const;
1238 /// Returns the target specific optimal type for load and store operations as
1239 /// a result of memset, memcpy, and memmove lowering.
1241 /// If DstAlign is zero that means it's safe to destination alignment can
1242 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1243 /// a need to check it against alignment requirement, probably because the
1244 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1245 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1246 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1247 /// does not need to be loaded. It returns EVT::Other if the type should be
1248 /// determined using generic target-independent logic.
1249 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
1250 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
1252 bool /*ZeroMemset*/,
1253 bool /*MemcpyStrSrc*/,
1254 MachineFunction &/*MF*/) const {
1258 /// Returns true if it's safe to use load / store of the specified type to
1259 /// expand memcpy / memset inline.
1261 /// This is mostly true for all types except for some special cases. For
1262 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1263 /// fstpl which also does type conversion. Note the specified type doesn't
1264 /// have to be legal as the hook is used before type legalization.
1265 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1267 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1268 bool usesUnderscoreSetJmp() const {
1269 return UseUnderscoreSetJmp;
1272 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1273 bool usesUnderscoreLongJmp() const {
1274 return UseUnderscoreLongJmp;
1277 /// Return lower limit for number of blocks in a jump table.
1278 unsigned getMinimumJumpTableEntries() const;
1280 /// Return lower limit of the density in a jump table.
1281 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1283 /// Return upper limit for number of entries in a jump table.
1284 /// Zero if no limit.
1285 unsigned getMaximumJumpTableSize() const;
1287 virtual bool isJumpTableRelative() const {
1288 return TM.isPositionIndependent();
1291 /// If a physical register, this specifies the register that
1292 /// llvm.savestack/llvm.restorestack should save and restore.
1293 unsigned getStackPointerRegisterToSaveRestore() const {
1294 return StackPointerRegisterToSaveRestore;
1297 /// If a physical register, this returns the register that receives the
1298 /// exception address on entry to an EH pad.
1300 getExceptionPointerRegister(const Constant *PersonalityFn) const {
1301 // 0 is guaranteed to be the NoRegister value on all targets
1305 /// If a physical register, this returns the register that receives the
1306 /// exception typeid on entry to a landing pad.
1308 getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1309 // 0 is guaranteed to be the NoRegister value on all targets
1313 virtual bool needsFixedCatchObjects() const {
1314 report_fatal_error("Funclet EH is not implemented for this target");
1317 /// Returns the target's jmp_buf size in bytes (if never set, the default is
1319 unsigned getJumpBufSize() const {
1323 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1325 unsigned getJumpBufAlignment() const {
1326 return JumpBufAlignment;
1329 /// Return the minimum stack alignment of an argument.
1330 unsigned getMinStackArgumentAlignment() const {
1331 return MinStackArgumentAlignment;
1334 /// Return the minimum function alignment.
1335 unsigned getMinFunctionAlignment() const {
1336 return MinFunctionAlignment;
1339 /// Return the preferred function alignment.
1340 unsigned getPrefFunctionAlignment() const {
1341 return PrefFunctionAlignment;
1344 /// Return the preferred loop alignment.
1345 virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1346 return PrefLoopAlignment;
1349 /// If the target has a standard location for the stack protector guard,
1350 /// returns the address of that location. Otherwise, returns nullptr.
1351 /// DEPRECATED: please override useLoadStackGuardNode and customize
1352 /// LOAD_STACK_GUARD, or customize @llvm.stackguard().
1353 virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1355 /// Inserts necessary declarations for SSP (stack protection) purpose.
1356 /// Should be used only when getIRStackGuard returns nullptr.
1357 virtual void insertSSPDeclarations(Module &M) const;
1359 /// Return the variable that's previously inserted by insertSSPDeclarations,
1360 /// if any, otherwise return nullptr. Should be used only when
1361 /// getIRStackGuard returns nullptr.
1362 virtual Value *getSDagStackGuard(const Module &M) const;
1364 /// If the target has a standard stack protection check function that
1365 /// performs validation and error handling, returns the function. Otherwise,
1366 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1367 /// Should be used only when getIRStackGuard returns nullptr.
1368 virtual Value *getSSPStackGuardCheck(const Module &M) const;
1371 Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1375 /// Returns the target-specific address of the unsafe stack pointer.
1376 virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1378 /// Returns the name of the symbol used to emit stack probes or the empty
1379 /// string if not applicable.
1380 virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const {
1384 /// Returns true if a cast between SrcAS and DestAS is a noop.
1385 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1389 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1390 /// are happy to sink it into basic blocks.
1391 virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1392 return isNoopAddrSpaceCast(SrcAS, DestAS);
1395 /// Return true if the pointer arguments to CI should be aligned by aligning
1396 /// the object whose address is being passed. If so then MinSize is set to the
1397 /// minimum size the object must be to be aligned and PrefAlign is set to the
1398 /// preferred alignment.
1399 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1400 unsigned & /*PrefAlign*/) const {
1404 //===--------------------------------------------------------------------===//
1405 /// \name Helpers for TargetTransformInfo implementations
1408 /// Get the ISD node that corresponds to the Instruction class opcode.
1409 int InstructionOpcodeToISD(unsigned Opcode) const;
1411 /// Estimate the cost of type-legalization and the legalized type.
1412 std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1417 //===--------------------------------------------------------------------===//
1418 /// \name Helpers for atomic expansion.
1421 /// Returns the maximum atomic operation size (in bits) supported by
1422 /// the backend. Atomic operations greater than this size (as well
1423 /// as ones that are not naturally aligned), will be expanded by
1424 /// AtomicExpandPass into an __atomic_* library call.
1425 unsigned getMaxAtomicSizeInBitsSupported() const {
1426 return MaxAtomicSizeInBitsSupported;
1429 /// Returns the size of the smallest cmpxchg or ll/sc instruction
1430 /// the backend supports. Any smaller operations are widened in
1431 /// AtomicExpandPass.
1433 /// Note that *unlike* operations above the maximum size, atomic ops
1434 /// are still natively supported below the minimum; they just
1435 /// require a more complex expansion.
1436 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1438 /// Whether AtomicExpandPass should automatically insert fences and reduce
1439 /// ordering for this atomic. This should be true for most architectures with
1440 /// weak memory ordering. Defaults to false.
1441 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1445 /// Perform a load-linked operation on Addr, returning a "Value *" with the
1446 /// corresponding pointee type. This may entail some non-trivial operations to
1447 /// truncate or reconstruct types that will be illegal in the backend. See
1448 /// ARMISelLowering for an example implementation.
1449 virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1450 AtomicOrdering Ord) const {
1451 llvm_unreachable("Load linked unimplemented on this target");
1454 /// Perform a store-conditional operation to Addr. Return the status of the
1455 /// store. This should be 0 if the store succeeded, non-zero otherwise.
1456 virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1457 Value *Addr, AtomicOrdering Ord) const {
1458 llvm_unreachable("Store conditional unimplemented on this target");
1461 /// Inserts in the IR a target-specific intrinsic specifying a fence.
1462 /// It is called by AtomicExpandPass before expanding an
1463 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1464 /// if shouldInsertFencesForAtomic returns true.
1466 /// Inst is the original atomic instruction, prior to other expansions that
1467 /// may be performed.
1469 /// This function should either return a nullptr, or a pointer to an IR-level
1470 /// Instruction*. Even complex fence sequences can be represented by a
1471 /// single Instruction* through an intrinsic to be lowered later.
1472 /// Backends should override this method to produce target-specific intrinsic
1473 /// for their fences.
1474 /// FIXME: Please note that the default implementation here in terms of
1475 /// IR-level fences exists for historical/compatibility reasons and is
1476 /// *unsound* ! Fences cannot, in general, be used to restore sequential
1477 /// consistency. For example, consider the following example:
1478 /// atomic<int> x = y = 0;
1479 /// int r1, r2, r3, r4;
1490 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1491 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1492 /// IR-level fences can prevent it.
1494 virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
1495 AtomicOrdering Ord) const {
1496 if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1497 return Builder.CreateFence(Ord);
1502 virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
1504 AtomicOrdering Ord) const {
1505 if (isAcquireOrStronger(Ord))
1506 return Builder.CreateFence(Ord);
1512 // Emits code that executes when the comparison result in the ll/sc
1513 // expansion of a cmpxchg instruction is such that the store-conditional will
1514 // not execute. This makes it possible to balance out the load-linked with
1515 // a dedicated instruction, if desired.
1516 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1517 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1518 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1520 /// Returns true if the given (atomic) store should be expanded by the
1521 /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1522 virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1526 /// Returns true if arguments should be sign-extended in lib calls.
1527 virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1531 /// Returns how the given (atomic) load should be expanded by the
1532 /// IR-level AtomicExpand pass.
1533 virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
1534 return AtomicExpansionKind::None;
1537 /// Returns true if the given atomic cmpxchg should be expanded by the
1538 /// IR-level AtomicExpand pass into a load-linked/store-conditional sequence
1539 /// (through emitLoadLinked() and emitStoreConditional()).
1540 virtual bool shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
1544 /// Returns how the IR-level AtomicExpand pass should expand the given
1545 /// AtomicRMW, if at all. Default is to never expand.
1546 virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *) const {
1547 return AtomicExpansionKind::None;
1550 /// On some platforms, an AtomicRMW that never actually modifies the value
1551 /// (such as fetch_add of 0) can be turned into a fence followed by an
1552 /// atomic load. This may sound useless, but it makes it possible for the
1553 /// processor to keep the cacheline shared, dramatically improving
1554 /// performance. And such idempotent RMWs are useful for implementing some
1555 /// kinds of locks, see for example (justification + benchmarks):
1556 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1557 /// This method tries doing that transformation, returning the atomic load if
1558 /// it succeeds, and nullptr otherwise.
1559 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1560 /// another round of expansion.
1562 lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1566 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1567 /// SIGN_EXTEND, or ANY_EXTEND).
1568 virtual ISD::NodeType getExtendForAtomicOps() const {
1569 return ISD::ZERO_EXTEND;
1574 /// Returns true if we should normalize
1575 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1576 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1577 /// that it saves us from materializing N0 and N1 in an integer register.
1578 /// Targets that are able to perform and/or on flags should return false here.
1579 virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
1581 // If a target has multiple condition registers, then it likely has logical
1582 // operations on those registers.
1583 if (hasMultipleConditionRegisters())
1585 // Only do the transform if the value won't be split into multiple
1587 LegalizeTypeAction Action = getTypeAction(Context, VT);
1588 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
1589 Action != TypeSplitVector;
1592 /// Return true if a select of constants (select Cond, C1, C2) should be
1593 /// transformed into simple math ops with the condition value. For example:
1594 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1595 virtual bool convertSelectOfConstantsToMath() const {
1599 //===--------------------------------------------------------------------===//
1600 // TargetLowering Configuration Methods - These methods should be invoked by
1601 // the derived class constructor to configure this object for the target.
1604 /// Specify how the target extends the result of integer and floating point
1605 /// boolean values from i1 to a wider type. See getBooleanContents.
1606 void setBooleanContents(BooleanContent Ty) {
1607 BooleanContents = Ty;
1608 BooleanFloatContents = Ty;
1611 /// Specify how the target extends the result of integer and floating point
1612 /// boolean values from i1 to a wider type. See getBooleanContents.
1613 void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
1614 BooleanContents = IntTy;
1615 BooleanFloatContents = FloatTy;
1618 /// Specify how the target extends the result of a vector boolean value from a
1619 /// vector of i1 to a wider type. See getBooleanContents.
1620 void setBooleanVectorContents(BooleanContent Ty) {
1621 BooleanVectorContents = Ty;
1624 /// Specify the target scheduling preference.
1625 void setSchedulingPreference(Sched::Preference Pref) {
1626 SchedPreferenceInfo = Pref;
1629 /// Indicate whether this target prefers to use _setjmp to implement
1630 /// llvm.setjmp or the version without _. Defaults to false.
1631 void setUseUnderscoreSetJmp(bool Val) {
1632 UseUnderscoreSetJmp = Val;
1635 /// Indicate whether this target prefers to use _longjmp to implement
1636 /// llvm.longjmp or the version without _. Defaults to false.
1637 void setUseUnderscoreLongJmp(bool Val) {
1638 UseUnderscoreLongJmp = Val;
1641 /// Indicate the minimum number of blocks to generate jump tables.
1642 void setMinimumJumpTableEntries(unsigned Val);
1644 /// Indicate the maximum number of entries in jump tables.
1645 /// Set to zero to generate unlimited jump tables.
1646 void setMaximumJumpTableSize(unsigned);
1648 /// If set to a physical register, this specifies the register that
1649 /// llvm.savestack/llvm.restorestack should save and restore.
1650 void setStackPointerRegisterToSaveRestore(unsigned R) {
1651 StackPointerRegisterToSaveRestore = R;
1654 /// Tells the code generator that the target has multiple (allocatable)
1655 /// condition registers that can be used to store the results of comparisons
1656 /// for use by selects and conditional branches. With multiple condition
1657 /// registers, the code generator will not aggressively sink comparisons into
1658 /// the blocks of their users.
1659 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1660 HasMultipleConditionRegisters = hasManyRegs;
1663 /// Tells the code generator that the target has BitExtract instructions.
1664 /// The code generator will aggressively sink "shift"s into the blocks of
1665 /// their users if the users will generate "and" instructions which can be
1666 /// combined with "shift" to BitExtract instructions.
1667 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1668 HasExtractBitsInsn = hasExtractInsn;
1671 /// Tells the code generator not to expand logic operations on comparison
1672 /// predicates into separate sequences that increase the amount of flow
1674 void setJumpIsExpensive(bool isExpensive = true);
1676 /// Tells the code generator that this target supports floating point
1677 /// exceptions and cares about preserving floating point exception behavior.
1678 void setHasFloatingPointExceptions(bool FPExceptions = true) {
1679 HasFloatingPointExceptions = FPExceptions;
1682 /// Tells the code generator which bitwidths to bypass.
1683 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1684 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1687 /// Add the specified register class as an available regclass for the
1688 /// specified value type. This indicates the selector can handle values of
1689 /// that class natively.
1690 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
1691 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
1692 RegClassForVT[VT.SimpleTy] = RC;
1695 /// Return the largest legal super-reg register class of the register class
1696 /// for the specified type and its associated "cost".
1697 virtual std::pair<const TargetRegisterClass *, uint8_t>
1698 findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
1700 /// Once all of the register classes are added, this allows us to compute
1701 /// derived properties we expose.
1702 void computeRegisterProperties(const TargetRegisterInfo *TRI);
1704 /// Indicate that the specified operation does not work with the specified
1705 /// type and indicate what to do about it. Note that VT may refer to either
1706 /// the type of a result or that of an operand of Op.
1707 void setOperationAction(unsigned Op, MVT VT,
1708 LegalizeAction Action) {
1709 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1710 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
1713 /// Indicate that the specified load with extension does not work with the
1714 /// specified type and indicate what to do about it.
1715 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
1716 LegalizeAction Action) {
1717 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
1718 MemVT.isValid() && "Table isn't big enough!");
1719 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
1720 unsigned Shift = 4 * ExtType;
1721 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
1722 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
1725 /// Indicate that the specified truncating store does not work with the
1726 /// specified type and indicate what to do about it.
1727 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1728 LegalizeAction Action) {
1729 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
1730 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
1733 /// Indicate that the specified indexed load does or does not work with the
1734 /// specified type and indicate what to do abort it.
1736 /// NOTE: All indexed mode loads are initialized to Expand in
1737 /// TargetLowering.cpp
1738 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1739 LegalizeAction Action) {
1740 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
1741 (unsigned)Action < 0xf && "Table isn't big enough!");
1742 // Load action are kept in the upper half.
1743 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1744 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1747 /// Indicate that the specified indexed store does or does not work with the
1748 /// specified type and indicate what to do about it.
1750 /// NOTE: All indexed mode stores are initialized to Expand in
1751 /// TargetLowering.cpp
1752 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1753 LegalizeAction Action) {
1754 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
1755 (unsigned)Action < 0xf && "Table isn't big enough!");
1756 // Store action are kept in the lower half.
1757 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1758 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1761 /// Indicate that the specified condition code is or isn't supported on the
1762 /// target and indicate what to do about it.
1763 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1764 LegalizeAction Action) {
1765 assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
1766 "Table isn't big enough!");
1767 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
1768 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
1769 /// value and the upper 29 bits index into the second dimension of the array
1770 /// to select what 32-bit value to use.
1771 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1772 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
1773 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
1776 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1777 /// to trying a larger integer/fp until it can find one that works. If that
1778 /// default is insufficient, this method can be used by the target to override
1780 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1781 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1784 /// Convenience method to set an operation to Promote and specify the type
1785 /// in a single call.
1786 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1787 setOperationAction(Opc, OrigVT, Promote);
1788 AddPromotedToType(Opc, OrigVT, DestVT);
1791 /// Targets should invoke this method for each target independent node that
1792 /// they want to provide a custom DAG combiner for by implementing the
1793 /// PerformDAGCombine virtual method.
1794 void setTargetDAGCombine(ISD::NodeType NT) {
1795 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1796 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1799 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1800 void setJumpBufSize(unsigned Size) {
1804 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1806 void setJumpBufAlignment(unsigned Align) {
1807 JumpBufAlignment = Align;
1810 /// Set the target's minimum function alignment (in log2(bytes))
1811 void setMinFunctionAlignment(unsigned Align) {
1812 MinFunctionAlignment = Align;
1815 /// Set the target's preferred function alignment. This should be set if
1816 /// there is a performance benefit to higher-than-minimum alignment (in
1818 void setPrefFunctionAlignment(unsigned Align) {
1819 PrefFunctionAlignment = Align;
1822 /// Set the target's preferred loop alignment. Default alignment is zero, it
1823 /// means the target does not care about loop alignment. The alignment is
1824 /// specified in log2(bytes). The target may also override
1825 /// getPrefLoopAlignment to provide per-loop values.
1826 void setPrefLoopAlignment(unsigned Align) {
1827 PrefLoopAlignment = Align;
1830 /// Set the minimum stack alignment of an argument (in log2(bytes)).
1831 void setMinStackArgumentAlignment(unsigned Align) {
1832 MinStackArgumentAlignment = Align;
1835 /// Set the maximum atomic operation size supported by the
1836 /// backend. Atomic operations greater than this size (as well as
1837 /// ones that are not naturally aligned), will be expanded by
1838 /// AtomicExpandPass into an __atomic_* library call.
1839 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
1840 MaxAtomicSizeInBitsSupported = SizeInBits;
1843 // Sets the minimum cmpxchg or ll/sc size supported by the backend.
1844 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
1845 MinCmpXchgSizeInBits = SizeInBits;
1849 //===--------------------------------------------------------------------===//
1850 // Addressing mode description hooks (used by LSR etc).
1853 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1854 /// instructions reading the address. This allows as much computation as
1855 /// possible to be done in the address mode for that operand. This hook lets
1856 /// targets also pass back when this should be done on intrinsics which
1858 virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
1859 SmallVectorImpl<Value*> &/*Ops*/,
1860 Type *&/*AccessTy*/) const {
1864 /// This represents an addressing mode of:
1865 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1866 /// If BaseGV is null, there is no BaseGV.
1867 /// If BaseOffs is zero, there is no base offset.
1868 /// If HasBaseReg is false, there is no base register.
1869 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1872 GlobalValue *BaseGV = nullptr;
1873 int64_t BaseOffs = 0;
1874 bool HasBaseReg = false;
1876 AddrMode() = default;
1879 /// Return true if the addressing mode represented by AM is legal for this
1880 /// target, for a load/store of the specified type.
1882 /// The type may be VoidTy, in which case only return true if the addressing
1883 /// mode is legal for a load/store of any legal type. TODO: Handle
1884 /// pre/postinc as well.
1886 /// If the address space cannot be determined, it will be -1.
1888 /// TODO: Remove default argument
1889 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
1890 Type *Ty, unsigned AddrSpace) const;
1892 /// \brief Return the cost of the scaling factor used in the addressing mode
1893 /// represented by AM for this target, for a load/store of the specified type.
1895 /// If the AM is supported, the return value must be >= 0.
1896 /// If the AM is not supported, it returns a negative value.
1897 /// TODO: Handle pre/postinc as well.
1898 /// TODO: Remove default argument
1899 virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
1900 Type *Ty, unsigned AS = 0) const {
1901 // Default: assume that any scaling factor used in a legal AM is free.
1902 if (isLegalAddressingMode(DL, AM, Ty, AS))
1907 virtual bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) const {
1911 /// Return true if the specified immediate is legal icmp immediate, that is
1912 /// the target has icmp instructions which can compare a register against the
1913 /// immediate without having to materialize the immediate into a register.
1914 virtual bool isLegalICmpImmediate(int64_t) const {
1918 /// Return true if the specified immediate is legal add immediate, that is the
1919 /// target has add instructions which can add a register with the immediate
1920 /// without having to materialize the immediate into a register.
1921 virtual bool isLegalAddImmediate(int64_t) const {
1925 /// Return true if it's significantly cheaper to shift a vector by a uniform
1926 /// scalar than by an amount which will vary across each lane. On x86, for
1927 /// example, there is a "psllw" instruction for the former case, but no simple
1928 /// instruction for a general "a << b" operation on vectors.
1929 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
1933 /// Returns true if the opcode is a commutative binary operation.
1934 virtual bool isCommutativeBinOp(unsigned Opcode) const {
1935 // FIXME: This should get its info from the td file.
1945 case ISD::SMUL_LOHI:
1946 case ISD::UMUL_LOHI:
1961 default: return false;
1965 /// Return true if it's free to truncate a value of type FromTy to type
1966 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1967 /// by referencing its sub-register AX.
1968 /// Targets must return false when FromTy <= ToTy.
1969 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
1973 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
1974 /// whether a call is in tail position. Typically this means that both results
1975 /// would be assigned to the same register or stack slot, but it could mean
1976 /// the target performs adequate checks of its own before proceeding with the
1977 /// tail call. Targets must return false when FromTy <= ToTy.
1978 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
1982 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
1986 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
1988 /// Return true if the extension represented by \p I is free.
1989 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
1990 /// this method can use the context provided by \p I to decide
1991 /// whether or not \p I is free.
1992 /// This method extends the behavior of the is[Z|FP]ExtFree family.
1993 /// In other words, if is[Z|FP]Free returns true, then this method
1994 /// returns true as well. The converse is not true.
1995 /// The target can perform the adequate checks by overriding isExtFreeImpl.
1996 /// \pre \p I must be a sign, zero, or fp extension.
1997 bool isExtFree(const Instruction *I) const {
1998 switch (I->getOpcode()) {
1999 case Instruction::FPExt:
2000 if (isFPExtFree(EVT::getEVT(I->getType())))
2003 case Instruction::ZExt:
2004 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2007 case Instruction::SExt:
2010 llvm_unreachable("Instruction is not an extension");
2012 return isExtFreeImpl(I);
2015 /// Return true if \p Load and \p Ext can form an ExtLoad.
2016 /// For example, in AArch64
2017 /// %L = load i8, i8* %ptr
2018 /// %E = zext i8 %L to i32
2019 /// can be lowered into one load instruction
2021 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2022 const DataLayout &DL) const {
2023 EVT VT = getValueType(DL, Ext->getType());
2024 EVT LoadVT = getValueType(DL, Load->getType());
2026 // If the load has other users and the truncate is not free, the ext
2027 // probably isn't free.
2028 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2029 !isTruncateFree(Ext->getType(), Load->getType()))
2032 // Check whether the target supports casts folded into loads.
2034 if (isa<ZExtInst>(Ext))
2035 LType = ISD::ZEXTLOAD;
2037 assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2038 LType = ISD::SEXTLOAD;
2041 return isLoadExtLegal(LType, VT, LoadVT);
2044 /// Return true if any actual instruction that defines a value of type FromTy
2045 /// implicitly zero-extends the value to ToTy in the result register.
2047 /// The function should return true when it is likely that the truncate can
2048 /// be freely folded with an instruction defining a value of FromTy. If
2049 /// the defining instruction is unknown (because you're looking at a
2050 /// function argument, PHI, etc.) then the target may require an
2051 /// explicit truncate, which is not necessarily free, but this function
2052 /// does not deal with those cases.
2053 /// Targets must return false when FromTy >= ToTy.
2054 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2058 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2062 /// Return true if the target supplies and combines to a paired load
2063 /// two loaded values of type LoadedType next to each other in memory.
2064 /// RequiredAlignment gives the minimal alignment constraints that must be met
2065 /// to be able to select this paired load.
2067 /// This information is *not* used to generate actual paired loads, but it is
2068 /// used to generate a sequence of loads that is easier to combine into a
2070 /// For instance, something like this:
2071 /// a = load i64* addr
2072 /// b = trunc i64 a to i32
2073 /// c = lshr i64 a, 32
2074 /// d = trunc i64 c to i32
2075 /// will be optimized into:
2076 /// b = load i32* addr1
2077 /// d = load i32* addr2
2078 /// Where addr1 = addr2 +/- sizeof(i32).
2080 /// In other words, unless the target performs a post-isel load combining,
2081 /// this information should not be provided because it will generate more
2083 virtual bool hasPairedLoad(EVT /*LoadedType*/,
2084 unsigned & /*RequiredAlignment*/) const {
2088 /// \brief Get the maximum supported factor for interleaved memory accesses.
2089 /// Default to be the minimum interleave factor: 2.
2090 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2092 /// \brief Lower an interleaved load to target specific intrinsics. Return
2093 /// true on success.
2095 /// \p LI is the vector load instruction.
2096 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2097 /// \p Indices is the corresponding indices for each shufflevector.
2098 /// \p Factor is the interleave factor.
2099 virtual bool lowerInterleavedLoad(LoadInst *LI,
2100 ArrayRef<ShuffleVectorInst *> Shuffles,
2101 ArrayRef<unsigned> Indices,
2102 unsigned Factor) const {
2106 /// \brief Lower an interleaved store to target specific intrinsics. Return
2107 /// true on success.
2109 /// \p SI is the vector store instruction.
2110 /// \p SVI is the shufflevector to RE-interleave the stored vector.
2111 /// \p Factor is the interleave factor.
2112 virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
2113 unsigned Factor) const {
2117 /// Return true if zero-extending the specific node Val to type VT2 is free
2118 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2119 /// because it's folded such as X86 zero-extending loads).
2120 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2121 return isZExtFree(Val.getValueType(), VT2);
2124 /// Return true if an fpext operation is free (for instance, because
2125 /// single-precision floating-point numbers are implicitly extended to
2126 /// double-precision).
2127 virtual bool isFPExtFree(EVT VT) const {
2128 assert(VT.isFloatingPoint());
2132 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2133 /// extend node) is profitable.
2134 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2136 /// Return true if an fneg operation is free to the point where it is never
2137 /// worthwhile to replace it with a bitwise operation.
2138 virtual bool isFNegFree(EVT VT) const {
2139 assert(VT.isFloatingPoint());
2143 /// Return true if an fabs operation is free to the point where it is never
2144 /// worthwhile to replace it with a bitwise operation.
2145 virtual bool isFAbsFree(EVT VT) const {
2146 assert(VT.isFloatingPoint());
2150 /// Return true if an FMA operation is faster than a pair of fmul and fadd
2151 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2152 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2154 /// NOTE: This may be called before legalization on types for which FMAs are
2155 /// not legal, but should return true if those types will eventually legalize
2156 /// to types that support FMAs. After legalization, it will only be called on
2157 /// types that support FMAs (via Legal or Custom actions)
2158 virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
2162 /// Return true if it's profitable to narrow operations of type VT1 to
2163 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2165 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2169 /// \brief Return true if it is beneficial to convert a load of a constant to
2170 /// just the constant itself.
2171 /// On some targets it might be more efficient to use a combination of
2172 /// arithmetic instructions to materialize the constant instead of loading it
2173 /// from a constant pool.
2174 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2179 /// Return true if EXTRACT_SUBVECTOR is cheap for this result type
2180 /// with this index. This is needed because EXTRACT_SUBVECTOR usually
2181 /// has custom lowering that depends on the index of the first element,
2182 /// and only the target knows which lowering is cheap.
2183 virtual bool isExtractSubvectorCheap(EVT ResVT, unsigned Index) const {
2187 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2188 // even if the vector itself has multiple uses.
2189 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2193 //===--------------------------------------------------------------------===//
2194 // Runtime Library hooks
2197 /// Rename the default libcall routine name for the specified libcall.
2198 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2199 LibcallRoutineNames[Call] = Name;
2202 /// Get the libcall routine name for the specified libcall.
2203 const char *getLibcallName(RTLIB::Libcall Call) const {
2204 return LibcallRoutineNames[Call];
2207 /// Override the default CondCode to be used to test the result of the
2208 /// comparison libcall against zero.
2209 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
2210 CmpLibcallCCs[Call] = CC;
2213 /// Get the CondCode that's to be used to test the result of the comparison
2214 /// libcall against zero.
2215 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
2216 return CmpLibcallCCs[Call];
2219 /// Set the CallingConv that should be used for the specified libcall.
2220 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
2221 LibcallCallingConvs[Call] = CC;
2224 /// Get the CallingConv that should be used for the specified libcall.
2225 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
2226 return LibcallCallingConvs[Call];
2229 /// Execute target specific actions to finalize target lowering.
2230 /// This is used to set extra flags in MachineFrameInformation and freezing
2231 /// the set of reserved registers.
2232 /// The default implementation just freezes the set of reserved registers.
2233 virtual void finalizeLowering(MachineFunction &MF) const;
2236 const TargetMachine &TM;
2238 /// Tells the code generator that the target has multiple (allocatable)
2239 /// condition registers that can be used to store the results of comparisons
2240 /// for use by selects and conditional branches. With multiple condition
2241 /// registers, the code generator will not aggressively sink comparisons into
2242 /// the blocks of their users.
2243 bool HasMultipleConditionRegisters;
2245 /// Tells the code generator that the target has BitExtract instructions.
2246 /// The code generator will aggressively sink "shift"s into the blocks of
2247 /// their users if the users will generate "and" instructions which can be
2248 /// combined with "shift" to BitExtract instructions.
2249 bool HasExtractBitsInsn;
2251 /// Tells the code generator to bypass slow divide or remainder
2252 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2253 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2254 /// div/rem when the operands are positive and less than 256.
2255 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2257 /// Tells the code generator that it shouldn't generate extra flow control
2258 /// instructions and should attempt to combine flow control instructions via
2260 bool JumpIsExpensive;
2262 /// Whether the target supports or cares about preserving floating point
2263 /// exception behavior.
2264 bool HasFloatingPointExceptions;
2266 /// This target prefers to use _setjmp to implement llvm.setjmp.
2268 /// Defaults to false.
2269 bool UseUnderscoreSetJmp;
2271 /// This target prefers to use _longjmp to implement llvm.longjmp.
2273 /// Defaults to false.
2274 bool UseUnderscoreLongJmp;
2276 /// Information about the contents of the high-bits in boolean values held in
2277 /// a type wider than i1. See getBooleanContents.
2278 BooleanContent BooleanContents;
2280 /// Information about the contents of the high-bits in boolean values held in
2281 /// a type wider than i1. See getBooleanContents.
2282 BooleanContent BooleanFloatContents;
2284 /// Information about the contents of the high-bits in boolean vector values
2285 /// when the element type is wider than i1. See getBooleanContents.
2286 BooleanContent BooleanVectorContents;
2288 /// The target scheduling preference: shortest possible total cycles or lowest
2290 Sched::Preference SchedPreferenceInfo;
2292 /// The size, in bytes, of the target's jmp_buf buffers
2293 unsigned JumpBufSize;
2295 /// The alignment, in bytes, of the target's jmp_buf buffers
2296 unsigned JumpBufAlignment;
2298 /// The minimum alignment that any argument on the stack needs to have.
2299 unsigned MinStackArgumentAlignment;
2301 /// The minimum function alignment (used when optimizing for size, and to
2302 /// prevent explicitly provided alignment from leading to incorrect code).
2303 unsigned MinFunctionAlignment;
2305 /// The preferred function alignment (used when alignment unspecified and
2306 /// optimizing for speed).
2307 unsigned PrefFunctionAlignment;
2309 /// The preferred loop alignment.
2310 unsigned PrefLoopAlignment;
2312 /// Size in bits of the maximum atomics size the backend supports.
2313 /// Accesses larger than this will be expanded by AtomicExpandPass.
2314 unsigned MaxAtomicSizeInBitsSupported;
2316 /// Size in bits of the minimum cmpxchg or ll/sc operation the
2317 /// backend supports.
2318 unsigned MinCmpXchgSizeInBits;
2320 /// If set to a physical register, this specifies the register that
2321 /// llvm.savestack/llvm.restorestack should save and restore.
2322 unsigned StackPointerRegisterToSaveRestore;
2324 /// This indicates the default register class to use for each ValueType the
2325 /// target supports natively.
2326 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2327 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
2328 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2330 /// This indicates the "representative" register class to use for each
2331 /// ValueType the target supports natively. This information is used by the
2332 /// scheduler to track register pressure. By default, the representative
2333 /// register class is the largest legal super-reg register class of the
2334 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2335 /// representative class would be GR32.
2336 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2338 /// This indicates the "cost" of the "representative" register class for each
2339 /// ValueType. The cost is used by the scheduler to approximate register
2341 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2343 /// For any value types we are promoting or expanding, this contains the value
2344 /// type that we are changing to. For Expanded types, this contains one step
2345 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2346 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2347 /// the same type (e.g. i32 -> i32).
2348 MVT TransformToType[MVT::LAST_VALUETYPE];
2350 /// For each operation and each value type, keep a LegalizeAction that
2351 /// indicates how instruction selection should deal with the operation. Most
2352 /// operations are Legal (aka, supported natively by the target), but
2353 /// operations that are not should be described. Note that operations on
2354 /// non-legal value types are not described here.
2355 LegalizeAction OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
2357 /// For each load extension type and each value type, keep a LegalizeAction
2358 /// that indicates how instruction selection should deal with a load of a
2359 /// specific value type and extension type. Uses 4-bits to store the action
2360 /// for each of the 4 load ext types.
2361 uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2363 /// For each value type pair keep a LegalizeAction that indicates whether a
2364 /// truncating store of a specific value type and truncating type is legal.
2365 LegalizeAction TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2367 /// For each indexed mode and each value type, keep a pair of LegalizeAction
2368 /// that indicates how instruction selection should deal with the load /
2371 /// The first dimension is the value_type for the reference. The second
2372 /// dimension represents the various modes for load store.
2373 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2375 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2376 /// indicates how instruction selection should deal with the condition code.
2378 /// Because each CC action takes up 4 bits, we need to have the array size be
2379 /// large enough to fit all of the value types. This can be done by rounding
2380 /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2381 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2384 ValueTypeActionImpl ValueTypeActions;
2387 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2389 /// Targets can specify ISD nodes that they would like PerformDAGCombine
2390 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2393 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2395 /// For operations that must be promoted to a specific type, this holds the
2396 /// destination type. This map should be sparse, so don't hold it as an
2399 /// Targets add entries to this map with AddPromotedToType(..), clients access
2400 /// this with getTypeToPromoteTo(..).
2401 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2404 /// Stores the name each libcall.
2405 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
2407 /// The ISD::CondCode that should be used to test the result of each of the
2408 /// comparison libcall against zero.
2409 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2411 /// Stores the CallingConv that should be used for each libcall.
2412 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2415 /// Return true if the extension represented by \p I is free.
2416 /// \pre \p I is a sign, zero, or fp extension and
2417 /// is[Z|FP]ExtFree of the related types is not true.
2418 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
2420 /// Depth that GatherAllAliases should should continue looking for chain
2421 /// dependencies when trying to find a more preferable chain. As an
2422 /// approximation, this should be more than the number of consecutive stores
2423 /// expected to be merged.
2424 unsigned GatherAllAliasesMaxDepth;
2426 /// \brief Specify maximum number of store instructions per memset call.
2428 /// When lowering \@llvm.memset this field specifies the maximum number of
2429 /// store operations that may be substituted for the call to memset. Targets
2430 /// must set this value based on the cost threshold for that target. Targets
2431 /// should assume that the memset will be done using as many of the largest
2432 /// store operations first, followed by smaller ones, if necessary, per
2433 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2434 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2435 /// store. This only applies to setting a constant array of a constant size.
2436 unsigned MaxStoresPerMemset;
2438 /// Maximum number of stores operations that may be substituted for the call
2439 /// to memset, used for functions with OptSize attribute.
2440 unsigned MaxStoresPerMemsetOptSize;
2442 /// \brief Specify maximum bytes of store instructions per memcpy call.
2444 /// When lowering \@llvm.memcpy this field specifies the maximum number of
2445 /// store operations that may be substituted for a call to memcpy. Targets
2446 /// must set this value based on the cost threshold for that target. Targets
2447 /// should assume that the memcpy will be done using as many of the largest
2448 /// store operations first, followed by smaller ones, if necessary, per
2449 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2450 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2451 /// and one 1-byte store. This only applies to copying a constant array of
2453 unsigned MaxStoresPerMemcpy;
2455 /// Maximum number of store operations that may be substituted for a call to
2456 /// memcpy, used for functions with OptSize attribute.
2457 unsigned MaxStoresPerMemcpyOptSize;
2458 unsigned MaxLoadsPerMemcmp;
2459 unsigned MaxLoadsPerMemcmpOptSize;
2461 /// \brief Specify maximum bytes of store instructions per memmove call.
2463 /// When lowering \@llvm.memmove this field specifies the maximum number of
2464 /// store instructions that may be substituted for a call to memmove. Targets
2465 /// must set this value based on the cost threshold for that target. Targets
2466 /// should assume that the memmove will be done using as many of the largest
2467 /// store operations first, followed by smaller ones, if necessary, per
2468 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2469 /// with 8-bit alignment would result in nine 1-byte stores. This only
2470 /// applies to copying a constant array of constant size.
2471 unsigned MaxStoresPerMemmove;
2473 /// Maximum number of store instructions that may be substituted for a call to
2474 /// memmove, used for functions with OptSize attribute.
2475 unsigned MaxStoresPerMemmoveOptSize;
2477 /// Tells the code generator that select is more expensive than a branch if
2478 /// the branch is usually predicted right.
2479 bool PredictableSelectIsExpensive;
2481 /// \see enableExtLdPromotion.
2482 bool EnableExtLdPromotion;
2484 /// Return true if the value types that can be represented by the specified
2485 /// register class are all legal.
2486 bool isLegalRC(const TargetRegisterInfo &TRI,
2487 const TargetRegisterClass &RC) const;
2489 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2490 /// sequence of memory operands that is recognized by PrologEpilogInserter.
2491 MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
2492 MachineBasicBlock *MBB) const;
2495 /// This class defines information used to lower LLVM code to legal SelectionDAG
2496 /// operators that the target instruction selector can accept natively.
2498 /// This class also defines callbacks that targets must implement to lower
2499 /// target-specific constructs to SelectionDAG operators.
2500 class TargetLowering : public TargetLoweringBase {
2502 struct DAGCombinerInfo;
2504 TargetLowering(const TargetLowering &) = delete;
2505 TargetLowering &operator=(const TargetLowering &) = delete;
2507 /// NOTE: The TargetMachine owns TLOF.
2508 explicit TargetLowering(const TargetMachine &TM);
2510 bool isPositionIndependent() const;
2512 /// Returns true by value, base pointer and offset pointer and addressing mode
2513 /// by reference if the node's address can be legally represented as
2514 /// pre-indexed load / store address.
2515 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2516 SDValue &/*Offset*/,
2517 ISD::MemIndexedMode &/*AM*/,
2518 SelectionDAG &/*DAG*/) const {
2522 /// Returns true by value, base pointer and offset pointer and addressing mode
2523 /// by reference if this node can be combined with a load / store to form a
2524 /// post-indexed load / store.
2525 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2527 SDValue &/*Offset*/,
2528 ISD::MemIndexedMode &/*AM*/,
2529 SelectionDAG &/*DAG*/) const {
2533 /// Return the entry encoding for a jump table in the current function. The
2534 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2535 virtual unsigned getJumpTableEncoding() const;
2537 virtual const MCExpr *
2538 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
2539 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2540 MCContext &/*Ctx*/) const {
2541 llvm_unreachable("Need to implement this hook if target has custom JTIs");
2544 /// Returns relocation base for the given PIC jumptable.
2545 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2546 SelectionDAG &DAG) const;
2548 /// This returns the relocation base for the given PIC jumptable, the same as
2549 /// getPICJumpTableRelocBase, but as an MCExpr.
2550 virtual const MCExpr *
2551 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2552 unsigned JTI, MCContext &Ctx) const;
2554 /// Return true if folding a constant offset with the given GlobalAddress is
2555 /// legal. It is frequently not legal in PIC relocation models.
2556 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2558 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
2559 SDValue &Chain) const;
2561 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
2562 SDValue &NewRHS, ISD::CondCode &CCCode,
2563 const SDLoc &DL) const;
2565 /// Returns a pair of (return value, chain).
2566 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2567 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
2568 EVT RetVT, ArrayRef<SDValue> Ops,
2569 bool isSigned, const SDLoc &dl,
2570 bool doesNotReturn = false,
2571 bool isReturnValueUsed = true) const;
2573 /// Check whether parameters to a call that are passed in callee saved
2574 /// registers are the same as from the calling function. This needs to be
2575 /// checked for tail call eligibility.
2576 bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
2577 const uint32_t *CallerPreservedMask,
2578 const SmallVectorImpl<CCValAssign> &ArgLocs,
2579 const SmallVectorImpl<SDValue> &OutVals) const;
2581 //===--------------------------------------------------------------------===//
2582 // TargetLowering Optimization Methods
2585 /// A convenience struct that encapsulates a DAG, and two SDValues for
2586 /// returning information from TargetLowering to its clients that want to
2588 struct TargetLoweringOpt {
2595 explicit TargetLoweringOpt(SelectionDAG &InDAG,
2597 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2599 bool LegalTypes() const { return LegalTys; }
2600 bool LegalOperations() const { return LegalOps; }
2602 bool CombineTo(SDValue O, SDValue N) {
2609 /// Check to see if the specified operand of the specified instruction is a
2610 /// constant integer. If so, check to see if there are any bits set in the
2611 /// constant that are not demanded. If so, shrink the constant and return
2613 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2614 TargetLoweringOpt &TLO) const;
2616 // Target hook to do target-specific const optimization, which is called by
2617 // ShrinkDemandedConstant. This function should return true if the target
2618 // doesn't want ShrinkDemandedConstant to further optimize the constant.
2619 virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
2620 TargetLoweringOpt &TLO) const {
2624 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
2625 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
2626 /// generalized for targets with other types of implicit widening casts.
2627 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
2628 TargetLoweringOpt &TLO) const;
2630 /// Helper for SimplifyDemandedBits that can simplify an operation with
2631 /// multiple uses. This function simplifies operand \p OpIdx of \p User and
2632 /// then updates \p User with the simplified version. No other uses of
2633 /// \p OpIdx are updated. If \p User is the only user of \p OpIdx, this
2634 /// function behaves exactly like function SimplifyDemandedBits declared
2635 /// below except that it also updates the DAG by calling
2636 /// DCI.CommitTargetLoweringOpt.
2637 bool SimplifyDemandedBits(SDNode *User, unsigned OpIdx, const APInt &Demanded,
2638 DAGCombinerInfo &DCI, TargetLoweringOpt &TLO) const;
2640 /// Look at Op. At this point, we know that only the DemandedMask bits of the
2641 /// result of Op are ever used downstream. If we can use this information to
2642 /// simplify Op, create a new simplified DAG node and return true, returning
2643 /// the original and new nodes in Old and New. Otherwise, analyze the
2644 /// expression and return a mask of KnownOne and KnownZero bits for the
2645 /// expression (used to simplify the caller). The KnownZero/One bits may only
2646 /// be accurate for those bits in the DemandedMask.
2647 /// \p AssumeSingleUse When this parameter is true, this function will
2648 /// attempt to simplify \p Op even if there are multiple uses.
2649 /// Callers are responsible for correctly updating the DAG based on the
2650 /// results of this function, because simply replacing replacing TLO.Old
2651 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
2652 /// has multiple uses.
2653 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2655 TargetLoweringOpt &TLO,
2657 bool AssumeSingleUse = false) const;
2659 /// Helper wrapper around SimplifyDemandedBits
2660 bool SimplifyDemandedBits(SDValue Op, APInt &DemandedMask,
2661 DAGCombinerInfo &DCI) const;
2663 /// Determine which of the bits specified in Mask are known to be either zero
2664 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
2665 /// argument allows us to only collect the known bits that are shared by the
2666 /// requested vector elements.
2667 virtual void computeKnownBitsForTargetNode(const SDValue Op,
2669 const APInt &DemandedElts,
2670 const SelectionDAG &DAG,
2671 unsigned Depth = 0) const;
2673 /// This method can be implemented by targets that want to expose additional
2674 /// information about sign bits to the DAG Combiner. The DemandedElts
2675 /// argument allows us to only collect the minimum sign bits that are shared
2676 /// by the requested vector elements.
2677 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
2678 const APInt &DemandedElts,
2679 const SelectionDAG &DAG,
2680 unsigned Depth = 0) const;
2682 struct DAGCombinerInfo {
2683 void *DC; // The DAG Combiner object.
2685 bool CalledByLegalizer;
2690 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
2691 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
2693 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
2694 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
2695 bool isAfterLegalizeVectorOps() const {
2696 return Level == AfterLegalizeDAG;
2698 CombineLevel getDAGCombineLevel() { return Level; }
2699 bool isCalledByLegalizer() const { return CalledByLegalizer; }
2701 void AddToWorklist(SDNode *N);
2702 SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
2703 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
2704 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
2706 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
2709 /// Return if the N is a constant or constant vector equal to the true value
2710 /// from getBooleanContents().
2711 bool isConstTrueVal(const SDNode *N) const;
2713 /// Return if the N is a constant or constant vector equal to the false value
2714 /// from getBooleanContents().
2715 bool isConstFalseVal(const SDNode *N) const;
2717 /// Return a constant of type VT that contains a true value that respects
2718 /// getBooleanContents()
2719 SDValue getConstTrueVal(SelectionDAG &DAG, EVT VT, const SDLoc &DL) const;
2721 /// Return if \p N is a True value when extended to \p VT.
2722 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool Signed) const;
2724 /// Try to simplify a setcc built with the specified operands and cc. If it is
2725 /// unable to simplify it, return a null SDValue.
2726 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
2727 bool foldBooleans, DAGCombinerInfo &DCI,
2728 const SDLoc &dl) const;
2730 /// Returns true (and the GlobalValue and the offset) if the node is a
2731 /// GlobalAddress + offset.
2733 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
2735 /// This method will be invoked for all target nodes and for any
2736 /// target-independent nodes that the target has registered with invoke it
2739 /// The semantics are as follows:
2741 /// SDValue.Val == 0 - No change was made
2742 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
2743 /// otherwise - N should be replaced by the returned Operand.
2745 /// In addition, methods provided by DAGCombinerInfo may be used to perform
2746 /// more complex transformations.
2748 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
2750 /// Return true if it is profitable to move a following shift through this
2751 // node, adjusting any immediate operands as necessary to preserve semantics.
2752 // This transformation may not be desirable if it disrupts a particularly
2753 // auspicious target-specific tree (e.g. bitfield extraction in AArch64).
2754 // By default, it returns true.
2755 virtual bool isDesirableToCommuteWithShift(const SDNode *N) const {
2759 // Return true if it is profitable to combine a BUILD_VECTOR to a TRUNCATE.
2760 // Example of such a combine:
2761 // v4i32 build_vector((extract_elt V, 0),
2762 // (extract_elt V, 2),
2763 // (extract_elt V, 4),
2764 // (extract_elt V, 6))
2766 // v4i32 truncate (bitcast V to v4i64)
2767 virtual bool isDesirableToCombineBuildVectorToTruncate() const {
2771 /// Return true if the target has native support for the specified value type
2772 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
2773 /// i16 is legal, but undesirable since i16 instruction encodings are longer
2774 /// and some i16 instructions are slow.
2775 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
2776 // By default, assume all legal types are desirable.
2777 return isTypeLegal(VT);
2780 /// Return true if it is profitable for dag combiner to transform a floating
2781 /// point op of specified opcode to a equivalent op of an integer
2782 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
2783 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
2788 /// This method query the target whether it is beneficial for dag combiner to
2789 /// promote the specified node. If true, it should return the desired
2790 /// promotion type by reference.
2791 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
2795 /// Return true if the target supports swifterror attribute. It optimizes
2796 /// loads and stores to reading and writing a specific register.
2797 virtual bool supportSwiftError() const {
2801 /// Return true if the target supports that a subset of CSRs for the given
2802 /// machine function is handled explicitly via copies.
2803 virtual bool supportSplitCSR(MachineFunction *MF) const {
2807 /// Perform necessary initialization to handle a subset of CSRs explicitly
2808 /// via copies. This function is called at the beginning of instruction
2810 virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
2811 llvm_unreachable("Not Implemented");
2814 /// Insert explicit copies in entry and exit blocks. We copy a subset of
2815 /// CSRs to virtual registers in the entry block, and copy them back to
2816 /// physical registers in the exit blocks. This function is called at the end
2817 /// of instruction selection.
2818 virtual void insertCopiesSplitCSR(
2819 MachineBasicBlock *Entry,
2820 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2821 llvm_unreachable("Not Implemented");
2824 //===--------------------------------------------------------------------===//
2825 // Lowering methods - These methods must be implemented by targets so that
2826 // the SelectionDAGBuilder code knows how to lower these.
2829 /// This hook must be implemented to lower the incoming (formal) arguments,
2830 /// described by the Ins array, into the specified DAG. The implementation
2831 /// should fill in the InVals array with legal-type argument values, and
2832 /// return the resulting token chain value.
2833 virtual SDValue LowerFormalArguments(
2834 SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
2835 const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
2836 SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
2837 llvm_unreachable("Not Implemented");
2840 /// This structure contains all information that is necessary for lowering
2841 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
2842 /// needs to lower a call, and targets will see this struct in their LowerCall
2844 struct CallLoweringInfo {
2846 Type *RetTy = nullptr;
2851 bool DoesNotReturn : 1;
2852 bool IsReturnValueUsed : 1;
2853 bool IsConvergent : 1;
2854 bool IsPatchPoint : 1;
2856 // IsTailCall should be modified by implementations of
2857 // TargetLowering::LowerCall that perform tail call conversions.
2858 bool IsTailCall = false;
2860 // Is Call lowering done post SelectionDAG type legalization.
2861 bool IsPostTypeLegalization = false;
2863 unsigned NumFixedArgs = -1;
2864 CallingConv::ID CallConv = CallingConv::C;
2869 ImmutableCallSite *CS = nullptr;
2870 SmallVector<ISD::OutputArg, 32> Outs;
2871 SmallVector<SDValue, 32> OutVals;
2872 SmallVector<ISD::InputArg, 32> Ins;
2873 SmallVector<SDValue, 4> InVals;
2875 CallLoweringInfo(SelectionDAG &DAG)
2876 : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
2877 DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
2878 IsPatchPoint(false), DAG(DAG) {}
2880 CallLoweringInfo &setDebugLoc(const SDLoc &dl) {
2885 CallLoweringInfo &setChain(SDValue InChain) {
2890 // setCallee with target/module-specific attributes
2891 CallLoweringInfo &setLibCallee(CallingConv::ID CC, Type *ResultType,
2892 SDValue Target, ArgListTy &&ArgsList) {
2896 NumFixedArgs = Args.size();
2897 Args = std::move(ArgsList);
2899 DAG.getTargetLoweringInfo().markLibCallAttributes(
2900 &(DAG.getMachineFunction()), CC, Args);
2904 CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
2905 SDValue Target, ArgListTy &&ArgsList) {
2909 NumFixedArgs = Args.size();
2910 Args = std::move(ArgsList);
2914 CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
2915 SDValue Target, ArgListTy &&ArgsList,
2916 ImmutableCallSite &Call) {
2919 IsInReg = Call.hasRetAttr(Attribute::InReg);
2921 Call.doesNotReturn() ||
2922 (!Call.isInvoke() &&
2923 isa<UnreachableInst>(Call.getInstruction()->getNextNode()));
2924 IsVarArg = FTy->isVarArg();
2925 IsReturnValueUsed = !Call.getInstruction()->use_empty();
2926 RetSExt = Call.hasRetAttr(Attribute::SExt);
2927 RetZExt = Call.hasRetAttr(Attribute::ZExt);
2931 CallConv = Call.getCallingConv();
2932 NumFixedArgs = FTy->getNumParams();
2933 Args = std::move(ArgsList);
2940 CallLoweringInfo &setInRegister(bool Value = true) {
2945 CallLoweringInfo &setNoReturn(bool Value = true) {
2946 DoesNotReturn = Value;
2950 CallLoweringInfo &setVarArg(bool Value = true) {
2955 CallLoweringInfo &setTailCall(bool Value = true) {
2960 CallLoweringInfo &setDiscardResult(bool Value = true) {
2961 IsReturnValueUsed = !Value;
2965 CallLoweringInfo &setConvergent(bool Value = true) {
2966 IsConvergent = Value;
2970 CallLoweringInfo &setSExtResult(bool Value = true) {
2975 CallLoweringInfo &setZExtResult(bool Value = true) {
2980 CallLoweringInfo &setIsPatchPoint(bool Value = true) {
2981 IsPatchPoint = Value;
2985 CallLoweringInfo &setIsPostTypeLegalization(bool Value=true) {
2986 IsPostTypeLegalization = Value;
2990 ArgListTy &getArgs() {
2995 /// This function lowers an abstract call to a function into an actual call.
2996 /// This returns a pair of operands. The first element is the return value
2997 /// for the function (if RetTy is not VoidTy). The second element is the
2998 /// outgoing token chain. It calls LowerCall to do the actual lowering.
2999 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
3001 /// This hook must be implemented to lower calls into the specified
3002 /// DAG. The outgoing arguments to the call are described by the Outs array,
3003 /// and the values to be returned by the call are described by the Ins
3004 /// array. The implementation should fill in the InVals array with legal-type
3005 /// return values from the call, and return the resulting token chain value.
3007 LowerCall(CallLoweringInfo &/*CLI*/,
3008 SmallVectorImpl<SDValue> &/*InVals*/) const {
3009 llvm_unreachable("Not Implemented");
3012 /// Target-specific cleanup for formal ByVal parameters.
3013 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
3015 /// This hook should be implemented to check whether the return values
3016 /// described by the Outs array can fit into the return registers. If false
3017 /// is returned, an sret-demotion is performed.
3018 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
3019 MachineFunction &/*MF*/, bool /*isVarArg*/,
3020 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
3021 LLVMContext &/*Context*/) const
3023 // Return true by default to get preexisting behavior.
3027 /// This hook must be implemented to lower outgoing return values, described
3028 /// by the Outs array, into the specified DAG. The implementation should
3029 /// return the resulting token chain value.
3030 virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
3032 const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
3033 const SmallVectorImpl<SDValue> & /*OutVals*/,
3034 const SDLoc & /*dl*/,
3035 SelectionDAG & /*DAG*/) const {
3036 llvm_unreachable("Not Implemented");
3039 /// Return true if result of the specified node is used by a return node
3040 /// only. It also compute and return the input chain for the tail call.
3042 /// This is used to determine whether it is possible to codegen a libcall as
3043 /// tail call at legalization time.
3044 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
3048 /// Return true if the target may be able emit the call instruction as a tail
3049 /// call. This is used by optimization passes to determine if it's profitable
3050 /// to duplicate return instructions to enable tailcall optimization.
3051 virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
3055 /// Return the builtin name for the __builtin___clear_cache intrinsic
3056 /// Default is to invoke the clear cache library call
3057 virtual const char * getClearCacheBuiltinName() const {
3058 return "__clear_cache";
3061 /// Return the register ID of the name passed in. Used by named register
3062 /// global variables extension. There is no target-independent behaviour
3063 /// so the default action is to bail.
3064 virtual unsigned getRegisterByName(const char* RegName, EVT VT,
3065 SelectionDAG &DAG) const {
3066 report_fatal_error("Named registers not implemented for this target");
3069 /// Return the type that should be used to zero or sign extend a
3070 /// zeroext/signext integer return value. FIXME: Some C calling conventions
3071 /// require the return type to be promoted, but this is not true all the time,
3072 /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
3073 /// conventions. The frontend should handle this and include all of the
3074 /// necessary information.
3075 virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT,
3076 ISD::NodeType /*ExtendKind*/) const {
3077 EVT MinVT = getRegisterType(Context, MVT::i32);
3078 return VT.bitsLT(MinVT) ? MinVT : VT;
3081 /// For some targets, an LLVM struct type must be broken down into multiple
3082 /// simple types, but the calling convention specifies that the entire struct
3083 /// must be passed in a block of consecutive registers.
3085 functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
3086 bool isVarArg) const {
3090 /// Returns a 0 terminated array of registers that can be safely used as
3091 /// scratch registers.
3092 virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
3096 /// This callback is used to prepare for a volatile or atomic load.
3097 /// It takes a chain node as input and returns the chain for the load itself.
3099 /// Having a callback like this is necessary for targets like SystemZ,
3100 /// which allows a CPU to reuse the result of a previous load indefinitely,
3101 /// even if a cache-coherent store is performed by another CPU. The default
3102 /// implementation does nothing.
3103 virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL,
3104 SelectionDAG &DAG) const {
3108 /// This callback is used to inspect load/store instructions and add
3109 /// target-specific MachineMemOperand flags to them. The default
3110 /// implementation does nothing.
3111 virtual MachineMemOperand::Flags getMMOFlags(const Instruction &I) const {
3112 return MachineMemOperand::MONone;
3115 /// This callback is invoked by the type legalizer to legalize nodes with an
3116 /// illegal operand type but legal result types. It replaces the
3117 /// LowerOperation callback in the type Legalizer. The reason we can not do
3118 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
3119 /// use this callback.
3121 /// TODO: Consider merging with ReplaceNodeResults.
3123 /// The target places new result values for the node in Results (their number
3124 /// and types must exactly match those of the original return values of
3125 /// the node), or leaves Results empty, which indicates that the node is not
3126 /// to be custom lowered after all.
3127 /// The default implementation calls LowerOperation.
3128 virtual void LowerOperationWrapper(SDNode *N,
3129 SmallVectorImpl<SDValue> &Results,
3130 SelectionDAG &DAG) const;
3132 /// This callback is invoked for operations that are unsupported by the
3133 /// target, which are registered to use 'custom' lowering, and whose defined
3134 /// values are all legal. If the target has no operations that require custom
3135 /// lowering, it need not implement this. The default implementation of this
3137 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
3139 /// This callback is invoked when a node result type is illegal for the
3140 /// target, and the operation was registered to use 'custom' lowering for that
3141 /// result type. The target places new result values for the node in Results
3142 /// (their number and types must exactly match those of the original return
3143 /// values of the node), or leaves Results empty, which indicates that the
3144 /// node is not to be custom lowered after all.
3146 /// If the target has no operations that require custom lowering, it need not
3147 /// implement this. The default implementation aborts.
3148 virtual void ReplaceNodeResults(SDNode * /*N*/,
3149 SmallVectorImpl<SDValue> &/*Results*/,
3150 SelectionDAG &/*DAG*/) const {
3151 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
3154 /// This method returns the name of a target specific DAG node.
3155 virtual const char *getTargetNodeName(unsigned Opcode) const;
3157 /// This method returns a target specific FastISel object, or null if the
3158 /// target does not support "fast" ISel.
3159 virtual FastISel *createFastISel(FunctionLoweringInfo &,
3160 const TargetLibraryInfo *) const {
3164 bool verifyReturnAddressArgumentIsConstant(SDValue Op,
3165 SelectionDAG &DAG) const;
3167 //===--------------------------------------------------------------------===//
3168 // Inline Asm Support hooks
3171 /// This hook allows the target to expand an inline asm call to be explicit
3172 /// llvm code if it wants to. This is useful for turning simple inline asms
3173 /// into LLVM intrinsics, which gives the compiler more information about the
3174 /// behavior of the code.
3175 virtual bool ExpandInlineAsm(CallInst *) const {
3179 enum ConstraintType {
3180 C_Register, // Constraint represents specific register(s).
3181 C_RegisterClass, // Constraint represents any of register(s) in class.
3182 C_Memory, // Memory constraint.
3183 C_Other, // Something else.
3184 C_Unknown // Unsupported constraint.
3187 enum ConstraintWeight {
3189 CW_Invalid = -1, // No match.
3190 CW_Okay = 0, // Acceptable.
3191 CW_Good = 1, // Good weight.
3192 CW_Better = 2, // Better weight.
3193 CW_Best = 3, // Best weight.
3195 // Well-known weights.
3196 CW_SpecificReg = CW_Okay, // Specific register operands.
3197 CW_Register = CW_Good, // Register operands.
3198 CW_Memory = CW_Better, // Memory operands.
3199 CW_Constant = CW_Best, // Constant operand.
3200 CW_Default = CW_Okay // Default or don't know type.
3203 /// This contains information for each constraint that we are lowering.
3204 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3205 /// This contains the actual string for the code, like "m". TargetLowering
3206 /// picks the 'best' code from ConstraintInfo::Codes that most closely
3207 /// matches the operand.
3208 std::string ConstraintCode;
3210 /// Information about the constraint code, e.g. Register, RegisterClass,
3211 /// Memory, Other, Unknown.
3212 TargetLowering::ConstraintType ConstraintType = TargetLowering::C_Unknown;
3214 /// If this is the result output operand or a clobber, this is null,
3215 /// otherwise it is the incoming operand to the CallInst. This gets
3216 /// modified as the asm is processed.
3217 Value *CallOperandVal = nullptr;
3219 /// The ValueType for the operand value.
3220 MVT ConstraintVT = MVT::Other;
3222 /// Copy constructor for copying from a ConstraintInfo.
3223 AsmOperandInfo(InlineAsm::ConstraintInfo Info)
3224 : InlineAsm::ConstraintInfo(std::move(Info)) {}
3226 /// Return true of this is an input operand that is a matching constraint
3228 bool isMatchingInputConstraint() const;
3230 /// If this is an input matching constraint, this method returns the output
3231 /// operand it matches.
3232 unsigned getMatchedOperand() const;
3235 using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
3237 /// Split up the constraint string from the inline assembly value into the
3238 /// specific constraints and their prefixes, and also tie in the associated
3239 /// operand values. If this returns an empty vector, and if the constraint
3240 /// string itself isn't empty, there was an error parsing.
3241 virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
3242 const TargetRegisterInfo *TRI,
3243 ImmutableCallSite CS) const;
3245 /// Examine constraint type and operand type and determine a weight value.
3246 /// The operand object must already have been set up with the operand type.
3247 virtual ConstraintWeight getMultipleConstraintMatchWeight(
3248 AsmOperandInfo &info, int maIndex) const;
3250 /// Examine constraint string and operand type and determine a weight value.
3251 /// The operand object must already have been set up with the operand type.
3252 virtual ConstraintWeight getSingleConstraintMatchWeight(
3253 AsmOperandInfo &info, const char *constraint) const;
3255 /// Determines the constraint code and constraint type to use for the specific
3256 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3257 /// If the actual operand being passed in is available, it can be passed in as
3258 /// Op, otherwise an empty SDValue can be passed.
3259 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3261 SelectionDAG *DAG = nullptr) const;
3263 /// Given a constraint, return the type of constraint it is for this target.
3264 virtual ConstraintType getConstraintType(StringRef Constraint) const;
3266 /// Given a physical register constraint (e.g. {edx}), return the register
3267 /// number and the register class for the register.
3269 /// Given a register class constraint, like 'r', if this corresponds directly
3270 /// to an LLVM register class, return a register of 0 and the register class
3273 /// This should only be used for C_Register constraints. On error, this
3274 /// returns a register number of 0 and a null register class pointer.
3275 virtual std::pair<unsigned, const TargetRegisterClass *>
3276 getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3277 StringRef Constraint, MVT VT) const;
3279 virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3280 if (ConstraintCode == "i")
3281 return InlineAsm::Constraint_i;
3282 else if (ConstraintCode == "m")
3283 return InlineAsm::Constraint_m;
3284 return InlineAsm::Constraint_Unknown;
3287 /// Try to replace an X constraint, which matches anything, with another that
3288 /// has more specific requirements based on the type of the corresponding
3289 /// operand. This returns null if there is no replacement to make.
3290 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
3292 /// Lower the specified operand into the Ops vector. If it is invalid, don't
3293 /// add anything to Ops.
3294 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
3295 std::vector<SDValue> &Ops,
3296 SelectionDAG &DAG) const;
3298 //===--------------------------------------------------------------------===//
3299 // Div utility functions
3301 SDValue BuildSDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
3302 bool IsAfterLegalization,
3303 std::vector<SDNode *> *Created) const;
3304 SDValue BuildUDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
3305 bool IsAfterLegalization,
3306 std::vector<SDNode *> *Created) const;
3308 /// Targets may override this function to provide custom SDIV lowering for
3309 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
3310 /// assumes SDIV is expensive and replaces it with a series of other integer
3312 virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3314 std::vector<SDNode *> *Created) const;
3316 /// Indicate whether this target prefers to combine FDIVs with the same
3317 /// divisor. If the transform should never be done, return zero. If the
3318 /// transform should be done, return the minimum number of divisor uses
3319 /// that must exist.
3320 virtual unsigned combineRepeatedFPDivisors() const {
3324 /// Hooks for building estimates in place of slower divisions and square
3327 /// Return either a square root or its reciprocal estimate value for the input
3329 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3330 /// 'Enabled' as set by a potential default override attribute.
3331 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3332 /// refinement iterations required to generate a sufficient (though not
3333 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3334 /// The boolean UseOneConstNR output is used to select a Newton-Raphson
3335 /// algorithm implementation that uses either one or two constants.
3336 /// The boolean Reciprocal is used to select whether the estimate is for the
3337 /// square root of the input operand or the reciprocal of its square root.
3338 /// A target may choose to implement its own refinement within this function.
3339 /// If that's true, then return '0' as the number of RefinementSteps to avoid
3340 /// any further refinement of the estimate.
3341 /// An empty SDValue return means no estimate sequence can be created.
3342 virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
3343 int Enabled, int &RefinementSteps,
3344 bool &UseOneConstNR, bool Reciprocal) const {
3348 /// Return a reciprocal estimate value for the input operand.
3349 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3350 /// 'Enabled' as set by a potential default override attribute.
3351 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3352 /// refinement iterations required to generate a sufficient (though not
3353 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3354 /// A target may choose to implement its own refinement within this function.
3355 /// If that's true, then return '0' as the number of RefinementSteps to avoid
3356 /// any further refinement of the estimate.
3357 /// An empty SDValue return means no estimate sequence can be created.
3358 virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
3359 int Enabled, int &RefinementSteps) const {
3363 //===--------------------------------------------------------------------===//
3364 // Legalization utility functions
3367 /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
3368 /// respectively, each computing an n/2-bit part of the result.
3369 /// \param Result A vector that will be filled with the parts of the result
3370 /// in little-endian order.
3371 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3372 /// if you want to control how low bits are extracted from the LHS.
3373 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3374 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3375 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3376 /// \returns true if the node has been expanded, false if it has not
3377 bool expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, SDValue LHS,
3378 SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
3379 SelectionDAG &DAG, MulExpansionKind Kind,
3380 SDValue LL = SDValue(), SDValue LH = SDValue(),
3381 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3383 /// Expand a MUL into two nodes. One that computes the high bits of
3384 /// the result and one that computes the low bits.
3385 /// \param HiLoVT The value type to use for the Lo and Hi nodes.
3386 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
3387 /// if you want to control how low bits are extracted from the LHS.
3388 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
3389 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
3390 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
3391 /// \returns true if the node has been expanded. false if it has not
3392 bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3393 SelectionDAG &DAG, MulExpansionKind Kind,
3394 SDValue LL = SDValue(), SDValue LH = SDValue(),
3395 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3397 /// Expand float(f32) to SINT(i64) conversion
3398 /// \param N Node to expand
3399 /// \param Result output after conversion
3400 /// \returns True, if the expansion was successful, false otherwise
3401 bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3403 /// Turn load of vector type into a load of the individual elements.
3404 /// \param LD load to expand
3405 /// \returns MERGE_VALUEs of the scalar loads with their chains.
3406 SDValue scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const;
3408 // Turn a store of a vector type into stores of the individual elements.
3409 /// \param ST Store with a vector value type
3410 /// \returns MERGE_VALUs of the individual store chains.
3411 SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3413 /// Expands an unaligned load to 2 half-size loads for an integer, and
3414 /// possibly more for vectors.
3415 std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
3416 SelectionDAG &DAG) const;
3418 /// Expands an unaligned store to 2 half-size stores for integer values, and
3419 /// possibly more for vectors.
3420 SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3422 /// Increments memory address \p Addr according to the type of the value
3423 /// \p DataVT that should be stored. If the data is stored in compressed
3424 /// form, the memory address should be incremented according to the number of
3425 /// the stored elements. This number is equal to the number of '1's bits
3427 /// \p DataVT is a vector type. \p Mask is a vector value.
3428 /// \p DataVT and \p Mask have the same number of vector elements.
3429 SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
3430 EVT DataVT, SelectionDAG &DAG,
3431 bool IsCompressedMemory) const;
3433 /// Get a pointer to vector element \p Idx located in memory for a vector of
3434 /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
3435 /// bounds the returned pointer is unspecified, but will be within the vector
3437 SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
3440 //===--------------------------------------------------------------------===//
3441 // Instruction Emitting Hooks
3444 /// This method should be implemented by targets that mark instructions with
3445 /// the 'usesCustomInserter' flag. These instructions are special in various
3446 /// ways, which require special support to insert. The specified MachineInstr
3447 /// is created but not inserted into any basic blocks, and this method is
3448 /// called to expand it into a sequence of instructions, potentially also
3449 /// creating new basic blocks and control flow.
3450 /// As long as the returned basic block is different (i.e., we created a new
3451 /// one), the custom inserter is free to modify the rest of \p MBB.
3452 virtual MachineBasicBlock *
3453 EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
3455 /// This method should be implemented by targets that mark instructions with
3456 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
3457 /// instruction selection by target hooks. e.g. To fill in optional defs for
3458 /// ARM 's' setting instructions.
3459 virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
3460 SDNode *Node) const;
3462 /// If this function returns true, SelectionDAGBuilder emits a
3463 /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
3464 virtual bool useLoadStackGuardNode() const {
3468 /// Lower TLS global address SDNode for target independent emulated TLS model.
3469 virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3470 SelectionDAG &DAG) const;
3472 // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
3473 // If we're comparing for equality to zero and isCtlzFast is true, expose the
3474 // fact that this can be implemented as a ctlz/srl pair, so that the dag
3475 // combiner can fold the new nodes.
3476 SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
3479 SDValue simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3480 ISD::CondCode Cond, DAGCombinerInfo &DCI,
3481 const SDLoc &DL) const;
3484 /// Given an LLVM IR type and return type attributes, compute the return value
3485 /// EVTs and flags, and optionally also the offsets, if the return value is
3486 /// being lowered to memory.
3487 void GetReturnInfo(Type *ReturnType, AttributeList attr,
3488 SmallVectorImpl<ISD::OutputArg> &Outs,
3489 const TargetLowering &TLI, const DataLayout &DL);
3491 } // end namespace llvm
3493 #endif // LLVM_TARGET_TARGETLOWERING_H