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/DenseMap.h"
27 #include "llvm/CodeGen/DAGCombine.h"
28 #include "llvm/CodeGen/RuntimeLibcalls.h"
29 #include "llvm/CodeGen/SelectionDAGNodes.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/MC/MCRegisterInfo.h"
37 #include "llvm/Target/TargetCallingConv.h"
38 #include "llvm/Target/TargetMachine.h"
47 class FunctionLoweringInfo;
48 class ImmutableCallSite;
50 class MachineBasicBlock;
51 class MachineFunction;
53 class MachineJumpTableInfo;
58 template<typename T> class SmallVectorImpl;
60 class TargetRegisterClass;
61 class TargetLibraryInfo;
62 class TargetLoweringObjectFile;
67 None, // No preference
68 Source, // Follow source order.
69 RegPressure, // Scheduling for lowest register pressure.
70 Hybrid, // Scheduling for both latency and register pressure.
71 ILP, // Scheduling for ILP in low register pressure mode.
72 VLIW // Scheduling for VLIW targets.
76 /// This base class for TargetLowering contains the SelectionDAG-independent
77 /// parts that can be used from the rest of CodeGen.
78 class TargetLoweringBase {
79 TargetLoweringBase(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
80 void operator=(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
83 /// This enum indicates whether operations are valid for a target, and if not,
84 /// what action should be used to make them valid.
86 Legal, // The target natively supports this operation.
87 Promote, // This operation should be executed in a larger type.
88 Expand, // Try to expand this to other ops, otherwise use a libcall.
89 Custom // Use the LowerOperation hook to implement custom lowering.
92 /// This enum indicates whether a types are legal for a target, and if not,
93 /// what action should be used to make them valid.
94 enum LegalizeTypeAction {
95 TypeLegal, // The target natively supports this type.
96 TypePromoteInteger, // Replace this integer with a larger one.
97 TypeExpandInteger, // Split this integer into two of half the size.
98 TypeSoftenFloat, // Convert this float to a same size integer type.
99 TypeExpandFloat, // Split this float into two of half the size.
100 TypeScalarizeVector, // Replace this one-element vector with its element.
101 TypeSplitVector, // Split this vector into two of half the size.
102 TypeWidenVector // This vector should be widened into a larger vector.
105 /// LegalizeKind holds the legalization kind that needs to happen to EVT
106 /// in order to type-legalize it.
107 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
109 /// Enum that describes how the target represents true/false values.
110 enum BooleanContent {
111 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
112 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
113 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
116 /// Enum that describes what type of support for selects the target has.
117 enum SelectSupportKind {
118 ScalarValSelect, // The target supports scalar selects (ex: cmov).
119 ScalarCondVectorVal, // The target supports selects with a scalar condition
120 // and vector values (ex: cmov).
121 VectorMaskSelect // The target supports vector selects with a vector
122 // mask (ex: x86 blends).
125 static ISD::NodeType getExtendForContent(BooleanContent Content) {
127 case UndefinedBooleanContent:
128 // Extend by adding rubbish bits.
129 return ISD::ANY_EXTEND;
130 case ZeroOrOneBooleanContent:
131 // Extend by adding zero bits.
132 return ISD::ZERO_EXTEND;
133 case ZeroOrNegativeOneBooleanContent:
134 // Extend by copying the sign bit.
135 return ISD::SIGN_EXTEND;
137 llvm_unreachable("Invalid content kind");
140 /// NOTE: The TargetMachine owns TLOF.
141 explicit TargetLoweringBase(const TargetMachine &TM);
142 virtual ~TargetLoweringBase() {}
145 /// \brief Initialize all of the actions to default values.
149 const TargetMachine &getTargetMachine() const { return TM; }
150 const DataLayout *getDataLayout() const { return DL; }
151 const TargetLoweringObjectFile &getObjFileLowering() const {
152 return *TM.getObjFileLowering();
155 bool isBigEndian() const { return !IsLittleEndian; }
156 bool isLittleEndian() const { return IsLittleEndian; }
158 /// Return the pointer type for the given address space, defaults to
159 /// the pointer type from the data layout.
160 /// FIXME: The default needs to be removed once all the code is updated.
161 virtual MVT getPointerTy(uint32_t /*AS*/ = 0) const;
162 unsigned getPointerSizeInBits(uint32_t AS = 0) const;
163 unsigned getPointerTypeSizeInBits(Type *Ty) const;
164 virtual MVT getScalarShiftAmountTy(EVT LHSTy) const;
166 EVT getShiftAmountTy(EVT LHSTy) const;
168 /// Returns the type to be used for the index operand of:
169 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
170 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
171 virtual MVT getVectorIdxTy() const {
172 return getPointerTy();
175 /// Return true if the select operation is expensive for this target.
176 bool isSelectExpensive() const { return SelectIsExpensive; }
178 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
182 /// Return true if multiple condition registers are available.
183 bool hasMultipleConditionRegisters() const {
184 return HasMultipleConditionRegisters;
187 /// Return true if the target has BitExtract instructions.
188 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
190 /// Return the preferred vector type legalization action.
191 virtual TargetLoweringBase::LegalizeTypeAction
192 getPreferredVectorAction(EVT VT) const {
193 // The default action for one element vectors is to scalarize
194 if (VT.getVectorNumElements() == 1)
195 return TypeScalarizeVector;
196 // The default action for other vectors is to promote
197 return TypePromoteInteger;
200 // There are two general methods for expanding a BUILD_VECTOR node:
201 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
203 // 2. Build the vector on the stack and then load it.
204 // If this function returns true, then method (1) will be used, subject to
205 // the constraint that all of the necessary shuffles are legal (as determined
206 // by isShuffleMaskLegal). If this function returns false, then method (2) is
207 // always used. The vector type, and the number of defined values, are
210 shouldExpandBuildVectorWithShuffles(EVT /* VT */,
211 unsigned DefinedValues) const {
212 return DefinedValues < 3;
215 /// Return true if integer divide is usually cheaper than a sequence of
216 /// several shifts, adds, and multiplies for this target.
217 bool isIntDivCheap() const { return IntDivIsCheap; }
219 /// Returns true if target has indicated at least one type should be bypassed.
220 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
222 /// Returns map of slow types for division or remainder with corresponding
224 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
225 return BypassSlowDivWidths;
228 /// Return true if pow2 sdiv is cheaper than a chain of sra/srl/add/sra.
229 bool isPow2SDivCheap() const { return Pow2SDivIsCheap; }
231 /// Return true if Flow Control is an expensive operation that should be
233 bool isJumpExpensive() const { return JumpIsExpensive; }
235 /// Return true if selects are only cheaper than branches if the branch is
236 /// unlikely to be predicted right.
237 bool isPredictableSelectExpensive() const {
238 return PredictableSelectIsExpensive;
241 /// isLoadBitCastBeneficial() - Return true if the following transform
243 /// fold (conv (load x)) -> (load (conv*)x)
244 /// On architectures that don't natively support some vector loads efficiently,
245 /// casting the load to a smaller vector of larger types and loading
246 /// is more efficient, however, this can be undone by optimizations in
248 virtual bool isLoadBitCastBeneficial(EVT /* Load */, EVT /* Bitcast */) const {
252 /// \brief Return if the target supports combining a
255 /// %andResult = and %val1, #imm-with-one-bit-set;
256 /// %icmpResult = icmp %andResult, 0
257 /// br i1 %icmpResult, label %dest1, label %dest2
259 /// into a single machine instruction of a form like:
261 /// brOnBitSet %register, #bitNumber, dest
263 bool isMaskAndBranchFoldingLegal() const {
264 return MaskAndBranchFoldingIsLegal;
267 /// \brief Return true if the target wants to use the optimization that
268 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
269 /// promotedInst1(...(promotedInstN(ext(load)))).
270 bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
272 /// Return true if the target can combine store(extractelement VectorTy,
274 /// \p Cost[out] gives the cost of that transformation when this is true.
275 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
276 unsigned &Cost) const {
280 /// Return true if target supports floating point exceptions.
281 bool hasFloatingPointExceptions() const {
282 return HasFloatingPointExceptions;
285 /// Return true if target always beneficiates from combining into FMA for a
286 /// given value type. This must typically return false on targets where FMA
287 /// takes more cycles to execute than FADD.
288 virtual bool enableAggressiveFMAFusion(EVT VT) const {
292 /// Return the ValueType of the result of SETCC operations.
293 virtual EVT getSetCCResultType(LLVMContext &Context, EVT VT) const;
295 /// Return the ValueType for comparison libcalls. Comparions libcalls include
296 /// floating point comparion calls, and Ordered/Unordered check calls on
297 /// floating point numbers.
299 MVT::SimpleValueType getCmpLibcallReturnType() const;
301 /// For targets without i1 registers, this gives the nature of the high-bits
302 /// of boolean values held in types wider than i1.
304 /// "Boolean values" are special true/false values produced by nodes like
305 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
306 /// Not to be confused with general values promoted from i1. Some cpus
307 /// distinguish between vectors of boolean and scalars; the isVec parameter
308 /// selects between the two kinds. For example on X86 a scalar boolean should
309 /// be zero extended from i1, while the elements of a vector of booleans
310 /// should be sign extended from i1.
312 /// Some cpus also treat floating point types the same way as they treat
313 /// vectors instead of the way they treat scalars.
314 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
316 return BooleanVectorContents;
317 return isFloat ? BooleanFloatContents : BooleanContents;
320 BooleanContent getBooleanContents(EVT Type) const {
321 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
324 /// Return target scheduling preference.
325 Sched::Preference getSchedulingPreference() const {
326 return SchedPreferenceInfo;
329 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
330 /// for different nodes. This function returns the preference (or none) for
332 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
336 /// Return the register class that should be used for the specified value
338 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
339 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
340 assert(RC && "This value type is not natively supported!");
344 /// Return the 'representative' register class for the specified value
347 /// The 'representative' register class is the largest legal super-reg
348 /// register class for the register class of the value type. For example, on
349 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
350 /// register class is GR64 on x86_64.
351 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
352 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
356 /// Return the cost of the 'representative' register class for the specified
358 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
359 return RepRegClassCostForVT[VT.SimpleTy];
362 /// Return true if the target has native support for the specified value type.
363 /// This means that it has a register that directly holds it without
364 /// promotions or expansions.
365 bool isTypeLegal(EVT VT) const {
366 assert(!VT.isSimple() ||
367 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
368 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
371 class ValueTypeActionImpl {
372 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
373 /// that indicates how instruction selection should deal with the type.
374 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
377 ValueTypeActionImpl() {
378 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions), 0);
381 LegalizeTypeAction getTypeAction(MVT VT) const {
382 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
385 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
386 unsigned I = VT.SimpleTy;
387 ValueTypeActions[I] = Action;
391 const ValueTypeActionImpl &getValueTypeActions() const {
392 return ValueTypeActions;
395 /// Return how we should legalize values of this type, either it is already
396 /// legal (return 'Legal') or we need to promote it to a larger type (return
397 /// 'Promote'), or we need to expand it into multiple registers of smaller
398 /// integer type (return 'Expand'). 'Custom' is not an option.
399 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
400 return getTypeConversion(Context, VT).first;
402 LegalizeTypeAction getTypeAction(MVT VT) const {
403 return ValueTypeActions.getTypeAction(VT);
406 /// For types supported by the target, this is an identity function. For
407 /// types that must be promoted to larger types, this returns the larger type
408 /// to promote to. For integer types that are larger than the largest integer
409 /// register, this contains one step in the expansion to get to the smaller
410 /// register. For illegal floating point types, this returns the integer type
412 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
413 return getTypeConversion(Context, VT).second;
416 /// For types supported by the target, this is an identity function. For
417 /// types that must be expanded (i.e. integer types that are larger than the
418 /// largest integer register or illegal floating point types), this returns
419 /// the largest legal type it will be expanded to.
420 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
421 assert(!VT.isVector());
423 switch (getTypeAction(Context, VT)) {
426 case TypeExpandInteger:
427 VT = getTypeToTransformTo(Context, VT);
430 llvm_unreachable("Type is not legal nor is it to be expanded!");
435 /// Vector types are broken down into some number of legal first class types.
436 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
437 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
438 /// turns into 4 EVT::i32 values with both PPC and X86.
440 /// This method returns the number of registers needed, and the VT for each
441 /// register. It also returns the VT and quantity of the intermediate values
442 /// before they are promoted/expanded.
443 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
445 unsigned &NumIntermediates,
446 MVT &RegisterVT) const;
448 struct IntrinsicInfo {
449 unsigned opc; // target opcode
450 EVT memVT; // memory VT
451 const Value* ptrVal; // value representing memory location
452 int offset; // offset off of ptrVal
453 unsigned size; // the size of the memory location
454 // (taken from memVT if zero)
455 unsigned align; // alignment
456 bool vol; // is volatile?
457 bool readMem; // reads memory?
458 bool writeMem; // writes memory?
460 IntrinsicInfo() : opc(0), ptrVal(nullptr), offset(0), size(0), align(1),
461 vol(false), readMem(false), writeMem(false) {}
464 /// Given an intrinsic, checks if on the target the intrinsic will need to map
465 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
466 /// true and store the intrinsic information into the IntrinsicInfo that was
467 /// passed to the function.
468 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
469 unsigned /*Intrinsic*/) const {
473 /// Returns true if the target can instruction select the specified FP
474 /// immediate natively. If false, the legalizer will materialize the FP
475 /// immediate as a load from a constant pool.
476 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
480 /// Targets can use this to indicate that they only support *some*
481 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
482 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
484 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
489 /// Returns true if the operation can trap for the value type.
491 /// VT must be a legal type. By default, we optimistically assume most
492 /// operations don't trap except for divide and remainder.
493 virtual bool canOpTrap(unsigned Op, EVT VT) const;
495 /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
496 /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
497 /// a VAND with a constant pool entry.
498 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
503 /// Return how this operation should be treated: either it is legal, needs to
504 /// be promoted to a larger size, needs to be expanded to some other code
505 /// sequence, or the target has a custom expander for it.
506 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
507 if (VT.isExtended()) return Expand;
508 // If a target-specific SDNode requires legalization, require the target
509 // to provide custom legalization for it.
510 if (Op > array_lengthof(OpActions[0])) return Custom;
511 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
512 return (LegalizeAction)OpActions[I][Op];
515 /// Return true if the specified operation is legal on this target or can be
516 /// made legal with custom lowering. This is used to help guide high-level
517 /// lowering decisions.
518 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
519 return (VT == MVT::Other || isTypeLegal(VT)) &&
520 (getOperationAction(Op, VT) == Legal ||
521 getOperationAction(Op, VT) == Custom);
524 /// Return true if the specified operation is legal on this target or can be
525 /// made legal using promotion. This is used to help guide high-level lowering
527 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
528 return (VT == MVT::Other || isTypeLegal(VT)) &&
529 (getOperationAction(Op, VT) == Legal ||
530 getOperationAction(Op, VT) == Promote);
533 /// Return true if the specified operation is illegal on this target or
534 /// unlikely to be made legal with custom lowering. This is used to help guide
535 /// high-level lowering decisions.
536 bool isOperationExpand(unsigned Op, EVT VT) const {
537 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
540 /// Return true if the specified operation is legal on this target.
541 bool isOperationLegal(unsigned Op, EVT VT) const {
542 return (VT == MVT::Other || isTypeLegal(VT)) &&
543 getOperationAction(Op, VT) == Legal;
546 /// Return how this load with extension should be treated: either it is legal,
547 /// needs to be promoted to a larger size, needs to be expanded to some other
548 /// code sequence, or the target has a custom expander for it.
549 LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const {
550 if (VT.isExtended()) return Expand;
551 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
552 assert(ExtType < ISD::LAST_LOADEXT_TYPE && I < MVT::LAST_VALUETYPE &&
553 "Table isn't big enough!");
554 return (LegalizeAction)LoadExtActions[I][ExtType];
557 /// Return true if the specified load with extension is legal on this target.
558 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
559 return VT.isSimple() &&
560 getLoadExtAction(ExtType, VT.getSimpleVT()) == Legal;
563 /// Return how this store with truncation should be treated: either it is
564 /// legal, needs to be promoted to a larger size, needs to be expanded to some
565 /// other code sequence, or the target has a custom expander for it.
566 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
567 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
568 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
569 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
570 assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
571 "Table isn't big enough!");
572 return (LegalizeAction)TruncStoreActions[ValI][MemI];
575 /// Return true if the specified store with truncation is legal on this
577 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
578 return isTypeLegal(ValVT) && MemVT.isSimple() &&
579 getTruncStoreAction(ValVT.getSimpleVT(), MemVT.getSimpleVT()) == Legal;
582 /// Return how the indexed load should be treated: either it is legal, needs
583 /// to be promoted to a larger size, needs to be expanded to some other code
584 /// sequence, or the target has a custom expander for it.
586 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
587 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
588 "Table isn't big enough!");
589 unsigned Ty = (unsigned)VT.SimpleTy;
590 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
593 /// Return true if the specified indexed load is legal on this target.
594 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
595 return VT.isSimple() &&
596 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
597 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
600 /// Return how the indexed store should be treated: either it is legal, needs
601 /// to be promoted to a larger size, needs to be expanded to some other code
602 /// sequence, or the target has a custom expander for it.
604 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
605 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
606 "Table isn't big enough!");
607 unsigned Ty = (unsigned)VT.SimpleTy;
608 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
611 /// Return true if the specified indexed load is legal on this target.
612 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
613 return VT.isSimple() &&
614 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
615 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
618 /// Return how the condition code should be treated: either it is legal, needs
619 /// to be expanded to some other code sequence, or the target has a custom
622 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
623 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
624 ((unsigned)VT.SimpleTy >> 4) < array_lengthof(CondCodeActions[0]) &&
625 "Table isn't big enough!");
626 // See setCondCodeAction for how this is encoded.
627 uint32_t Shift = 2 * (VT.SimpleTy & 0xF);
628 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 4];
629 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0x3);
630 assert(Action != Promote && "Can't promote condition code!");
634 /// Return true if the specified condition code is legal on this target.
635 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
637 getCondCodeAction(CC, VT) == Legal ||
638 getCondCodeAction(CC, VT) == Custom;
642 /// If the action for this operation is to promote, this method returns the
643 /// ValueType to promote to.
644 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
645 assert(getOperationAction(Op, VT) == Promote &&
646 "This operation isn't promoted!");
648 // See if this has an explicit type specified.
649 std::map<std::pair<unsigned, MVT::SimpleValueType>,
650 MVT::SimpleValueType>::const_iterator PTTI =
651 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
652 if (PTTI != PromoteToType.end()) return PTTI->second;
654 assert((VT.isInteger() || VT.isFloatingPoint()) &&
655 "Cannot autopromote this type, add it with AddPromotedToType.");
659 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
660 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
661 "Didn't find type to promote to!");
662 } while (!isTypeLegal(NVT) ||
663 getOperationAction(Op, NVT) == Promote);
667 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
668 /// operations except for the pointer size. If AllowUnknown is true, this
669 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
670 /// otherwise it will assert.
671 EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
672 // Lower scalar pointers to native pointer types.
673 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
674 return getPointerTy(PTy->getAddressSpace());
676 if (Ty->isVectorTy()) {
677 VectorType *VTy = cast<VectorType>(Ty);
678 Type *Elm = VTy->getElementType();
679 // Lower vectors of pointers to native pointer types.
680 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
681 EVT PointerTy(getPointerTy(PT->getAddressSpace()));
682 Elm = PointerTy.getTypeForEVT(Ty->getContext());
685 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
686 VTy->getNumElements());
688 return EVT::getEVT(Ty, AllowUnknown);
691 /// Return the MVT corresponding to this LLVM type. See getValueType.
692 MVT getSimpleValueType(Type *Ty, bool AllowUnknown = false) const {
693 return getValueType(Ty, AllowUnknown).getSimpleVT();
696 /// Return the desired alignment for ByVal or InAlloca aggregate function
697 /// arguments in the caller parameter area. This is the actual alignment, not
699 virtual unsigned getByValTypeAlignment(Type *Ty) const;
701 /// Return the type of registers that this ValueType will eventually require.
702 MVT getRegisterType(MVT VT) const {
703 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
704 return RegisterTypeForVT[VT.SimpleTy];
707 /// Return the type of registers that this ValueType will eventually require.
708 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
710 assert((unsigned)VT.getSimpleVT().SimpleTy <
711 array_lengthof(RegisterTypeForVT));
712 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
717 unsigned NumIntermediates;
718 (void)getVectorTypeBreakdown(Context, VT, VT1,
719 NumIntermediates, RegisterVT);
722 if (VT.isInteger()) {
723 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
725 llvm_unreachable("Unsupported extended type!");
728 /// Return the number of registers that this ValueType will eventually
731 /// This is one for any types promoted to live in larger registers, but may be
732 /// more than one for types (like i64) that are split into pieces. For types
733 /// like i140, which are first promoted then expanded, it is the number of
734 /// registers needed to hold all the bits of the original type. For an i140
735 /// on a 32 bit machine this means 5 registers.
736 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
738 assert((unsigned)VT.getSimpleVT().SimpleTy <
739 array_lengthof(NumRegistersForVT));
740 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
745 unsigned NumIntermediates;
746 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
748 if (VT.isInteger()) {
749 unsigned BitWidth = VT.getSizeInBits();
750 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
751 return (BitWidth + RegWidth - 1) / RegWidth;
753 llvm_unreachable("Unsupported extended type!");
756 /// If true, then instruction selection should seek to shrink the FP constant
757 /// of the specified type to a smaller type in order to save space and / or
759 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
761 // Return true if it is profitable to reduce the given load node to a smaller
764 // e.g. (i16 (trunc (i32 (load x))) -> i16 load x should be performed
765 virtual bool shouldReduceLoadWidth(SDNode *Load,
766 ISD::LoadExtType ExtTy,
771 /// When splitting a value of the specified type into parts, does the Lo
772 /// or Hi part come first? This usually follows the endianness, except
773 /// for ppcf128, where the Hi part always comes first.
774 bool hasBigEndianPartOrdering(EVT VT) const {
775 return isBigEndian() || VT == MVT::ppcf128;
778 /// If true, the target has custom DAG combine transformations that it can
779 /// perform for the specified node.
780 bool hasTargetDAGCombine(ISD::NodeType NT) const {
781 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
782 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
785 /// \brief Get maximum # of store operations permitted for llvm.memset
787 /// This function returns the maximum number of store operations permitted
788 /// to replace a call to llvm.memset. The value is set by the target at the
789 /// performance threshold for such a replacement. If OptSize is true,
790 /// return the limit for functions that have OptSize attribute.
791 unsigned getMaxStoresPerMemset(bool OptSize) const {
792 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
795 /// \brief Get maximum # of store operations permitted for llvm.memcpy
797 /// This function returns the maximum number of store operations permitted
798 /// to replace a call to llvm.memcpy. The value is set by the target at the
799 /// performance threshold for such a replacement. If OptSize is true,
800 /// return the limit for functions that have OptSize attribute.
801 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
802 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
805 /// \brief Get maximum # of store operations permitted for llvm.memmove
807 /// This function returns the maximum number of store operations permitted
808 /// to replace a call to llvm.memmove. The value is set by the target at the
809 /// performance threshold for such a replacement. If OptSize is true,
810 /// return the limit for functions that have OptSize attribute.
811 unsigned getMaxStoresPerMemmove(bool OptSize) const {
812 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
815 /// \brief Determine if the target supports unaligned memory accesses.
817 /// This function returns true if the target allows unaligned memory accesses
818 /// of the specified type in the given address space. If true, it also returns
819 /// whether the unaligned memory access is "fast" in the last argument by
820 /// reference. This is used, for example, in situations where an array
821 /// copy/move/set is converted to a sequence of store operations. Its use
822 /// helps to ensure that such replacements don't generate code that causes an
823 /// alignment error (trap) on the target machine.
824 virtual bool allowsMisalignedMemoryAccesses(EVT,
825 unsigned AddrSpace = 0,
827 bool * /*Fast*/ = nullptr) const {
831 /// Returns the target specific optimal type for load and store operations as
832 /// a result of memset, memcpy, and memmove lowering.
834 /// If DstAlign is zero that means it's safe to destination alignment can
835 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
836 /// a need to check it against alignment requirement, probably because the
837 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
838 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
839 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
840 /// does not need to be loaded. It returns EVT::Other if the type should be
841 /// determined using generic target-independent logic.
842 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
843 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
846 bool /*MemcpyStrSrc*/,
847 MachineFunction &/*MF*/) const {
851 /// Returns true if it's safe to use load / store of the specified type to
852 /// expand memcpy / memset inline.
854 /// This is mostly true for all types except for some special cases. For
855 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
856 /// fstpl which also does type conversion. Note the specified type doesn't
857 /// have to be legal as the hook is used before type legalization.
858 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
860 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
861 bool usesUnderscoreSetJmp() const {
862 return UseUnderscoreSetJmp;
865 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
866 bool usesUnderscoreLongJmp() const {
867 return UseUnderscoreLongJmp;
870 /// Return integer threshold on number of blocks to use jump tables rather
871 /// than if sequence.
872 int getMinimumJumpTableEntries() const {
873 return MinimumJumpTableEntries;
876 /// If a physical register, this specifies the register that
877 /// llvm.savestack/llvm.restorestack should save and restore.
878 unsigned getStackPointerRegisterToSaveRestore() const {
879 return StackPointerRegisterToSaveRestore;
882 /// If a physical register, this returns the register that receives the
883 /// exception address on entry to a landing pad.
884 unsigned getExceptionPointerRegister() const {
885 return ExceptionPointerRegister;
888 /// If a physical register, this returns the register that receives the
889 /// exception typeid on entry to a landing pad.
890 unsigned getExceptionSelectorRegister() const {
891 return ExceptionSelectorRegister;
894 /// Returns the target's jmp_buf size in bytes (if never set, the default is
896 unsigned getJumpBufSize() const {
900 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
902 unsigned getJumpBufAlignment() const {
903 return JumpBufAlignment;
906 /// Return the minimum stack alignment of an argument.
907 unsigned getMinStackArgumentAlignment() const {
908 return MinStackArgumentAlignment;
911 /// Return the minimum function alignment.
912 unsigned getMinFunctionAlignment() const {
913 return MinFunctionAlignment;
916 /// Return the preferred function alignment.
917 unsigned getPrefFunctionAlignment() const {
918 return PrefFunctionAlignment;
921 /// Return the preferred loop alignment.
922 unsigned getPrefLoopAlignment() const {
923 return PrefLoopAlignment;
926 /// Return whether the DAG builder should automatically insert fences and
927 /// reduce ordering for atomics.
928 bool getInsertFencesForAtomic() const {
929 return InsertFencesForAtomic;
932 /// Return true if the target stores stack protector cookies at a fixed offset
933 /// in some non-standard address space, and populates the address space and
934 /// offset as appropriate.
935 virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
936 unsigned &/*Offset*/) const {
940 /// Returns the maximal possible offset which can be used for loads / stores
942 virtual unsigned getMaximalGlobalOffset() const {
946 /// Returns true if a cast between SrcAS and DestAS is a noop.
947 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
951 //===--------------------------------------------------------------------===//
952 /// \name Helpers for TargetTransformInfo implementations
955 /// Get the ISD node that corresponds to the Instruction class opcode.
956 int InstructionOpcodeToISD(unsigned Opcode) const;
958 /// Estimate the cost of type-legalization and the legalized type.
959 std::pair<unsigned, MVT> getTypeLegalizationCost(Type *Ty) const;
963 //===--------------------------------------------------------------------===//
964 /// \name Helpers for atomic expansion.
967 /// True if AtomicExpandPass should use emitLoadLinked/emitStoreConditional
968 /// and expand AtomicCmpXchgInst.
969 virtual bool hasLoadLinkedStoreConditional() const { return false; }
971 /// Perform a load-linked operation on Addr, returning a "Value *" with the
972 /// corresponding pointee type. This may entail some non-trivial operations to
973 /// truncate or reconstruct types that will be illegal in the backend. See
974 /// ARMISelLowering for an example implementation.
975 virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
976 AtomicOrdering Ord) const {
977 llvm_unreachable("Load linked unimplemented on this target");
980 /// Perform a store-conditional operation to Addr. Return the status of the
981 /// store. This should be 0 if the store succeeded, non-zero otherwise.
982 virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
983 Value *Addr, AtomicOrdering Ord) const {
984 llvm_unreachable("Store conditional unimplemented on this target");
987 /// Inserts in the IR a target-specific intrinsic specifying a fence.
988 /// It is called by AtomicExpandPass before expanding an
989 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad.
990 /// RMW and CmpXchg set both IsStore and IsLoad to true.
991 /// This function should either return a nullptr, or a pointer to an IR-level
992 /// Instruction*. Even complex fence sequences can be represented by a
993 /// single Instruction* through an intrinsic to be lowered later.
994 /// Backends with !getInsertFencesForAtomic() should keep a no-op here.
995 /// Backends should override this method to produce target-specific intrinsic
996 /// for their fences.
997 /// FIXME: Please note that the default implementation here in terms of
998 /// IR-level fences exists for historical/compatibility reasons and is
999 /// *unsound* ! Fences cannot, in general, be used to restore sequential
1000 /// consistency. For example, consider the following example:
1001 /// atomic<int> x = y = 0;
1002 /// int r1, r2, r3, r4;
1013 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1014 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1015 /// IR-level fences can prevent it.
1017 virtual Instruction* emitLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord,
1018 bool IsStore, bool IsLoad) const {
1019 if (!getInsertFencesForAtomic())
1022 if (isAtLeastRelease(Ord) && IsStore)
1023 return Builder.CreateFence(Ord);
1028 virtual Instruction* emitTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord,
1029 bool IsStore, bool IsLoad) const {
1030 if (!getInsertFencesForAtomic())
1033 if (isAtLeastAcquire(Ord))
1034 return Builder.CreateFence(Ord);
1040 /// Returns true if the given (atomic) store should be expanded by the
1041 /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1042 virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1046 /// Returns true if the given (atomic) load should be expanded by the
1047 /// IR-level AtomicExpand pass into a load-linked instruction
1048 /// (through emitLoadLinked()).
1049 virtual bool shouldExpandAtomicLoadInIR(LoadInst *LI) const { return false; }
1051 /// Returns true if the given AtomicRMW should be expanded by the
1052 /// IR-level AtomicExpand pass into a loop using LoadLinked/StoreConditional.
1053 virtual bool shouldExpandAtomicRMWInIR(AtomicRMWInst *RMWI) const {
1057 /// On some platforms, an AtomicRMW that never actually modifies the value
1058 /// (such as fetch_add of 0) can be turned into a fence followed by an
1059 /// atomic load. This may sound useless, but it makes it possible for the
1060 /// processor to keep the cacheline shared, dramatically improving
1061 /// performance. And such idempotent RMWs are useful for implementing some
1062 /// kinds of locks, see for example (justification + benchmarks):
1063 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1064 /// This method tries doing that transformation, returning the atomic load if
1065 /// it succeeds, and nullptr otherwise.
1066 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1067 /// another round of expansion.
1068 virtual LoadInst *lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1071 //===--------------------------------------------------------------------===//
1072 // TargetLowering Configuration Methods - These methods should be invoked by
1073 // the derived class constructor to configure this object for the target.
1076 /// \brief Reset the operation actions based on target options.
1077 virtual void resetOperationActions() {}
1080 /// Specify how the target extends the result of integer and floating point
1081 /// boolean values from i1 to a wider type. See getBooleanContents.
1082 void setBooleanContents(BooleanContent Ty) {
1083 BooleanContents = Ty;
1084 BooleanFloatContents = Ty;
1087 /// Specify how the target extends the result of integer and floating point
1088 /// boolean values from i1 to a wider type. See getBooleanContents.
1089 void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
1090 BooleanContents = IntTy;
1091 BooleanFloatContents = FloatTy;
1094 /// Specify how the target extends the result of a vector boolean value from a
1095 /// vector of i1 to a wider type. See getBooleanContents.
1096 void setBooleanVectorContents(BooleanContent Ty) {
1097 BooleanVectorContents = Ty;
1100 /// Specify the target scheduling preference.
1101 void setSchedulingPreference(Sched::Preference Pref) {
1102 SchedPreferenceInfo = Pref;
1105 /// Indicate whether this target prefers to use _setjmp to implement
1106 /// llvm.setjmp or the version without _. Defaults to false.
1107 void setUseUnderscoreSetJmp(bool Val) {
1108 UseUnderscoreSetJmp = Val;
1111 /// Indicate whether this target prefers to use _longjmp to implement
1112 /// llvm.longjmp or the version without _. Defaults to false.
1113 void setUseUnderscoreLongJmp(bool Val) {
1114 UseUnderscoreLongJmp = Val;
1117 /// Indicate the number of blocks to generate jump tables rather than if
1119 void setMinimumJumpTableEntries(int Val) {
1120 MinimumJumpTableEntries = Val;
1123 /// If set to a physical register, this specifies the register that
1124 /// llvm.savestack/llvm.restorestack should save and restore.
1125 void setStackPointerRegisterToSaveRestore(unsigned R) {
1126 StackPointerRegisterToSaveRestore = R;
1129 /// If set to a physical register, this sets the register that receives the
1130 /// exception address on entry to a landing pad.
1131 void setExceptionPointerRegister(unsigned R) {
1132 ExceptionPointerRegister = R;
1135 /// If set to a physical register, this sets the register that receives the
1136 /// exception typeid on entry to a landing pad.
1137 void setExceptionSelectorRegister(unsigned R) {
1138 ExceptionSelectorRegister = R;
1141 /// Tells the code generator not to expand operations into sequences that use
1142 /// the select operations if possible.
1143 void setSelectIsExpensive(bool isExpensive = true) {
1144 SelectIsExpensive = isExpensive;
1147 /// Tells the code generator that the target has multiple (allocatable)
1148 /// condition registers that can be used to store the results of comparisons
1149 /// for use by selects and conditional branches. With multiple condition
1150 /// registers, the code generator will not aggressively sink comparisons into
1151 /// the blocks of their users.
1152 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1153 HasMultipleConditionRegisters = hasManyRegs;
1156 /// Tells the code generator that the target has BitExtract instructions.
1157 /// The code generator will aggressively sink "shift"s into the blocks of
1158 /// their users if the users will generate "and" instructions which can be
1159 /// combined with "shift" to BitExtract instructions.
1160 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1161 HasExtractBitsInsn = hasExtractInsn;
1164 /// Tells the code generator not to expand sequence of operations into a
1165 /// separate sequences that increases the amount of flow control.
1166 void setJumpIsExpensive(bool isExpensive = true) {
1167 JumpIsExpensive = isExpensive;
1170 /// Tells the code generator that integer divide is expensive, and if
1171 /// possible, should be replaced by an alternate sequence of instructions not
1172 /// containing an integer divide.
1173 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
1175 /// Tells the code generator that this target supports floating point
1176 /// exceptions and cares about preserving floating point exception behavior.
1177 void setHasFloatingPointExceptions(bool FPExceptions = true) {
1178 HasFloatingPointExceptions = FPExceptions;
1181 /// Tells the code generator which bitwidths to bypass.
1182 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1183 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1186 /// Tells the code generator that it shouldn't generate sra/srl/add/sra for a
1187 /// signed divide by power of two; let the target handle it.
1188 void setPow2SDivIsCheap(bool isCheap = true) { Pow2SDivIsCheap = isCheap; }
1190 /// Add the specified register class as an available regclass for the
1191 /// specified value type. This indicates the selector can handle values of
1192 /// that class natively.
1193 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
1194 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
1195 AvailableRegClasses.push_back(std::make_pair(VT, RC));
1196 RegClassForVT[VT.SimpleTy] = RC;
1199 /// Remove all register classes.
1200 void clearRegisterClasses() {
1201 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE * sizeof(TargetRegisterClass*));
1203 AvailableRegClasses.clear();
1206 /// \brief Remove all operation actions.
1207 void clearOperationActions() {
1210 /// Return the largest legal super-reg register class of the register class
1211 /// for the specified type and its associated "cost".
1212 virtual std::pair<const TargetRegisterClass*, uint8_t>
1213 findRepresentativeClass(MVT VT) const;
1215 /// Once all of the register classes are added, this allows us to compute
1216 /// derived properties we expose.
1217 void computeRegisterProperties();
1219 /// Indicate that the specified operation does not work with the specified
1220 /// type and indicate what to do about it.
1221 void setOperationAction(unsigned Op, MVT VT,
1222 LegalizeAction Action) {
1223 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1224 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1227 /// Indicate that the specified load with extension does not work with the
1228 /// specified type and indicate what to do about it.
1229 void setLoadExtAction(unsigned ExtType, MVT VT,
1230 LegalizeAction Action) {
1231 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1232 "Table isn't big enough!");
1233 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1236 /// Indicate that the specified truncating store does not work with the
1237 /// specified type and indicate what to do about it.
1238 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1239 LegalizeAction Action) {
1240 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1241 "Table isn't big enough!");
1242 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1245 /// Indicate that the specified indexed load does or does not work with the
1246 /// specified type and indicate what to do abort it.
1248 /// NOTE: All indexed mode loads are initialized to Expand in
1249 /// TargetLowering.cpp
1250 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1251 LegalizeAction Action) {
1252 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1253 (unsigned)Action < 0xf && "Table isn't big enough!");
1254 // Load action are kept in the upper half.
1255 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1256 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1259 /// Indicate that the specified indexed store does or does not work with the
1260 /// specified type and indicate what to do about it.
1262 /// NOTE: All indexed mode stores are initialized to Expand in
1263 /// TargetLowering.cpp
1264 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1265 LegalizeAction Action) {
1266 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1267 (unsigned)Action < 0xf && "Table isn't big enough!");
1268 // Store action are kept in the lower half.
1269 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1270 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1273 /// Indicate that the specified condition code is or isn't supported on the
1274 /// target and indicate what to do about it.
1275 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1276 LegalizeAction Action) {
1277 assert(VT < MVT::LAST_VALUETYPE &&
1278 (unsigned)CC < array_lengthof(CondCodeActions) &&
1279 "Table isn't big enough!");
1280 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 32-bit
1281 /// value and the upper 27 bits index into the second dimension of the array
1282 /// to select what 32-bit value to use.
1283 uint32_t Shift = 2 * (VT.SimpleTy & 0xF);
1284 CondCodeActions[CC][VT.SimpleTy >> 4] &= ~((uint32_t)0x3 << Shift);
1285 CondCodeActions[CC][VT.SimpleTy >> 4] |= (uint32_t)Action << Shift;
1288 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1289 /// to trying a larger integer/fp until it can find one that works. If that
1290 /// default is insufficient, this method can be used by the target to override
1292 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1293 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1296 /// Targets should invoke this method for each target independent node that
1297 /// they want to provide a custom DAG combiner for by implementing the
1298 /// PerformDAGCombine virtual method.
1299 void setTargetDAGCombine(ISD::NodeType NT) {
1300 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1301 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1304 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1305 void setJumpBufSize(unsigned Size) {
1309 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1311 void setJumpBufAlignment(unsigned Align) {
1312 JumpBufAlignment = Align;
1315 /// Set the target's minimum function alignment (in log2(bytes))
1316 void setMinFunctionAlignment(unsigned Align) {
1317 MinFunctionAlignment = Align;
1320 /// Set the target's preferred function alignment. This should be set if
1321 /// there is a performance benefit to higher-than-minimum alignment (in
1323 void setPrefFunctionAlignment(unsigned Align) {
1324 PrefFunctionAlignment = Align;
1327 /// Set the target's preferred loop alignment. Default alignment is zero, it
1328 /// means the target does not care about loop alignment. The alignment is
1329 /// specified in log2(bytes).
1330 void setPrefLoopAlignment(unsigned Align) {
1331 PrefLoopAlignment = Align;
1334 /// Set the minimum stack alignment of an argument (in log2(bytes)).
1335 void setMinStackArgumentAlignment(unsigned Align) {
1336 MinStackArgumentAlignment = Align;
1339 /// Set if the DAG builder should automatically insert fences and reduce the
1340 /// order of atomic memory operations to Monotonic.
1341 void setInsertFencesForAtomic(bool fence) {
1342 InsertFencesForAtomic = fence;
1346 //===--------------------------------------------------------------------===//
1347 // Addressing mode description hooks (used by LSR etc).
1350 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1351 /// instructions reading the address. This allows as much computation as
1352 /// possible to be done in the address mode for that operand. This hook lets
1353 /// targets also pass back when this should be done on intrinsics which
1355 virtual bool GetAddrModeArguments(IntrinsicInst * /*I*/,
1356 SmallVectorImpl<Value*> &/*Ops*/,
1357 Type *&/*AccessTy*/) const {
1361 /// This represents an addressing mode of:
1362 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1363 /// If BaseGV is null, there is no BaseGV.
1364 /// If BaseOffs is zero, there is no base offset.
1365 /// If HasBaseReg is false, there is no base register.
1366 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1369 GlobalValue *BaseGV;
1373 AddrMode() : BaseGV(nullptr), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1376 /// Return true if the addressing mode represented by AM is legal for this
1377 /// target, for a load/store of the specified type.
1379 /// The type may be VoidTy, in which case only return true if the addressing
1380 /// mode is legal for a load/store of any legal type. TODO: Handle
1381 /// pre/postinc as well.
1382 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1384 /// \brief Return the cost of the scaling factor used in the addressing mode
1385 /// represented by AM for this target, for a load/store of the specified type.
1387 /// If the AM is supported, the return value must be >= 0.
1388 /// If the AM is not supported, it returns a negative value.
1389 /// TODO: Handle pre/postinc as well.
1390 virtual int getScalingFactorCost(const AddrMode &AM, Type *Ty) const {
1391 // Default: assume that any scaling factor used in a legal AM is free.
1392 if (isLegalAddressingMode(AM, Ty)) return 0;
1396 /// Return true if the specified immediate is legal icmp immediate, that is
1397 /// the target has icmp instructions which can compare a register against the
1398 /// immediate without having to materialize the immediate into a register.
1399 virtual bool isLegalICmpImmediate(int64_t) const {
1403 /// Return true if the specified immediate is legal add immediate, that is the
1404 /// target has add instructions which can add a register with the immediate
1405 /// without having to materialize the immediate into a register.
1406 virtual bool isLegalAddImmediate(int64_t) const {
1410 /// Return true if it's significantly cheaper to shift a vector by a uniform
1411 /// scalar than by an amount which will vary across each lane. On x86, for
1412 /// example, there is a "psllw" instruction for the former case, but no simple
1413 /// instruction for a general "a << b" operation on vectors.
1414 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
1418 /// Return true if it's free to truncate a value of type Ty1 to type
1419 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1420 /// by referencing its sub-register AX.
1421 virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1425 /// Return true if a truncation from Ty1 to Ty2 is permitted when deciding
1426 /// whether a call is in tail position. Typically this means that both results
1427 /// would be assigned to the same register or stack slot, but it could mean
1428 /// the target performs adequate checks of its own before proceeding with the
1430 virtual bool allowTruncateForTailCall(Type * /*Ty1*/, Type * /*Ty2*/) const {
1434 virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1438 /// Return true if any actual instruction that defines a value of type Ty1
1439 /// implicitly zero-extends the value to Ty2 in the result register.
1441 /// This does not necessarily include registers defined in unknown ways, such
1442 /// as incoming arguments, or copies from unknown virtual registers. Also, if
1443 /// isTruncateFree(Ty2, Ty1) is true, this does not necessarily apply to
1444 /// truncate instructions. e.g. on x86-64, all instructions that define 32-bit
1445 /// values implicit zero-extend the result out to 64 bits.
1446 virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1450 virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1454 /// Return true if the target supplies and combines to a paired load
1455 /// two loaded values of type LoadedType next to each other in memory.
1456 /// RequiredAlignment gives the minimal alignment constraints that must be met
1457 /// to be able to select this paired load.
1459 /// This information is *not* used to generate actual paired loads, but it is
1460 /// used to generate a sequence of loads that is easier to combine into a
1462 /// For instance, something like this:
1463 /// a = load i64* addr
1464 /// b = trunc i64 a to i32
1465 /// c = lshr i64 a, 32
1466 /// d = trunc i64 c to i32
1467 /// will be optimized into:
1468 /// b = load i32* addr1
1469 /// d = load i32* addr2
1470 /// Where addr1 = addr2 +/- sizeof(i32).
1472 /// In other words, unless the target performs a post-isel load combining,
1473 /// this information should not be provided because it will generate more
1475 virtual bool hasPairedLoad(Type * /*LoadedType*/,
1476 unsigned & /*RequiredAligment*/) const {
1480 virtual bool hasPairedLoad(EVT /*LoadedType*/,
1481 unsigned & /*RequiredAligment*/) const {
1485 /// Return true if zero-extending the specific node Val to type VT2 is free
1486 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
1487 /// because it's folded such as X86 zero-extending loads).
1488 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1489 return isZExtFree(Val.getValueType(), VT2);
1492 /// Return true if an fneg operation is free to the point where it is never
1493 /// worthwhile to replace it with a bitwise operation.
1494 virtual bool isFNegFree(EVT VT) const {
1495 assert(VT.isFloatingPoint());
1499 /// Return true if an fabs operation is free to the point where it is never
1500 /// worthwhile to replace it with a bitwise operation.
1501 virtual bool isFAbsFree(EVT VT) const {
1502 assert(VT.isFloatingPoint());
1506 /// Return true if an FMA operation is faster than a pair of fmul and fadd
1507 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
1508 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
1510 /// NOTE: This may be called before legalization on types for which FMAs are
1511 /// not legal, but should return true if those types will eventually legalize
1512 /// to types that support FMAs. After legalization, it will only be called on
1513 /// types that support FMAs (via Legal or Custom actions)
1514 virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
1518 /// Return true if it's profitable to narrow operations of type VT1 to
1519 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
1521 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1525 /// \brief Return true if it is beneficial to convert a load of a constant to
1526 /// just the constant itself.
1527 /// On some targets it might be more efficient to use a combination of
1528 /// arithmetic instructions to materialize the constant instead of loading it
1529 /// from a constant pool.
1530 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
1535 /// Return true if EXTRACT_SUBVECTOR is cheap for this result type
1536 /// with this index. This is needed because EXTRACT_SUBVECTOR usually
1537 /// has custom lowering that depends on the index of the first element,
1538 /// and only the target knows which lowering is cheap.
1539 virtual bool isExtractSubvectorCheap(EVT ResVT, unsigned Index) const {
1543 //===--------------------------------------------------------------------===//
1544 // Runtime Library hooks
1547 /// Rename the default libcall routine name for the specified libcall.
1548 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1549 LibcallRoutineNames[Call] = Name;
1552 /// Get the libcall routine name for the specified libcall.
1553 const char *getLibcallName(RTLIB::Libcall Call) const {
1554 return LibcallRoutineNames[Call];
1557 /// Override the default CondCode to be used to test the result of the
1558 /// comparison libcall against zero.
1559 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1560 CmpLibcallCCs[Call] = CC;
1563 /// Get the CondCode that's to be used to test the result of the comparison
1564 /// libcall against zero.
1565 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1566 return CmpLibcallCCs[Call];
1569 /// Set the CallingConv that should be used for the specified libcall.
1570 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1571 LibcallCallingConvs[Call] = CC;
1574 /// Get the CallingConv that should be used for the specified libcall.
1575 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1576 return LibcallCallingConvs[Call];
1580 const TargetMachine &TM;
1581 const DataLayout *DL;
1583 /// True if this is a little endian target.
1584 bool IsLittleEndian;
1586 /// Tells the code generator not to expand operations into sequences that use
1587 /// the select operations if possible.
1588 bool SelectIsExpensive;
1590 /// Tells the code generator that the target has multiple (allocatable)
1591 /// condition registers that can be used to store the results of comparisons
1592 /// for use by selects and conditional branches. With multiple condition
1593 /// registers, the code generator will not aggressively sink comparisons into
1594 /// the blocks of their users.
1595 bool HasMultipleConditionRegisters;
1597 /// Tells the code generator that the target has BitExtract instructions.
1598 /// The code generator will aggressively sink "shift"s into the blocks of
1599 /// their users if the users will generate "and" instructions which can be
1600 /// combined with "shift" to BitExtract instructions.
1601 bool HasExtractBitsInsn;
1603 /// Tells the code generator not to expand integer divides by constants into a
1604 /// sequence of muls, adds, and shifts. This is a hack until a real cost
1605 /// model is in place. If we ever optimize for size, this will be set to true
1606 /// unconditionally.
1609 /// Tells the code generator to bypass slow divide or remainder
1610 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
1611 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
1612 /// div/rem when the operands are positive and less than 256.
1613 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1615 /// Tells the code generator that it shouldn't generate sra/srl/add/sra for a
1616 /// signed divide by power of two; let the target handle it.
1617 bool Pow2SDivIsCheap;
1619 /// Tells the code generator that it shouldn't generate extra flow control
1620 /// instructions and should attempt to combine flow control instructions via
1622 bool JumpIsExpensive;
1624 /// Whether the target supports or cares about preserving floating point
1625 /// exception behavior.
1626 bool HasFloatingPointExceptions;
1628 /// This target prefers to use _setjmp to implement llvm.setjmp.
1630 /// Defaults to false.
1631 bool UseUnderscoreSetJmp;
1633 /// This target prefers to use _longjmp to implement llvm.longjmp.
1635 /// Defaults to false.
1636 bool UseUnderscoreLongJmp;
1638 /// Number of blocks threshold to use jump tables.
1639 int MinimumJumpTableEntries;
1641 /// Information about the contents of the high-bits in boolean values held in
1642 /// a type wider than i1. See getBooleanContents.
1643 BooleanContent BooleanContents;
1645 /// Information about the contents of the high-bits in boolean values held in
1646 /// a type wider than i1. See getBooleanContents.
1647 BooleanContent BooleanFloatContents;
1649 /// Information about the contents of the high-bits in boolean vector values
1650 /// when the element type is wider than i1. See getBooleanContents.
1651 BooleanContent BooleanVectorContents;
1653 /// The target scheduling preference: shortest possible total cycles or lowest
1655 Sched::Preference SchedPreferenceInfo;
1657 /// The size, in bytes, of the target's jmp_buf buffers
1658 unsigned JumpBufSize;
1660 /// The alignment, in bytes, of the target's jmp_buf buffers
1661 unsigned JumpBufAlignment;
1663 /// The minimum alignment that any argument on the stack needs to have.
1664 unsigned MinStackArgumentAlignment;
1666 /// The minimum function alignment (used when optimizing for size, and to
1667 /// prevent explicitly provided alignment from leading to incorrect code).
1668 unsigned MinFunctionAlignment;
1670 /// The preferred function alignment (used when alignment unspecified and
1671 /// optimizing for speed).
1672 unsigned PrefFunctionAlignment;
1674 /// The preferred loop alignment.
1675 unsigned PrefLoopAlignment;
1677 /// Whether the DAG builder should automatically insert fences and reduce
1678 /// ordering for atomics. (This will be set for for most architectures with
1679 /// weak memory ordering.)
1680 bool InsertFencesForAtomic;
1682 /// If set to a physical register, this specifies the register that
1683 /// llvm.savestack/llvm.restorestack should save and restore.
1684 unsigned StackPointerRegisterToSaveRestore;
1686 /// If set to a physical register, this specifies the register that receives
1687 /// the exception address on entry to a landing pad.
1688 unsigned ExceptionPointerRegister;
1690 /// If set to a physical register, this specifies the register that receives
1691 /// the exception typeid on entry to a landing pad.
1692 unsigned ExceptionSelectorRegister;
1694 /// This indicates the default register class to use for each ValueType the
1695 /// target supports natively.
1696 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1697 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1698 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1700 /// This indicates the "representative" register class to use for each
1701 /// ValueType the target supports natively. This information is used by the
1702 /// scheduler to track register pressure. By default, the representative
1703 /// register class is the largest legal super-reg register class of the
1704 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
1705 /// representative class would be GR32.
1706 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1708 /// This indicates the "cost" of the "representative" register class for each
1709 /// ValueType. The cost is used by the scheduler to approximate register
1711 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1713 /// For any value types we are promoting or expanding, this contains the value
1714 /// type that we are changing to. For Expanded types, this contains one step
1715 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
1716 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
1717 /// the same type (e.g. i32 -> i32).
1718 MVT TransformToType[MVT::LAST_VALUETYPE];
1720 /// For each operation and each value type, keep a LegalizeAction that
1721 /// indicates how instruction selection should deal with the operation. Most
1722 /// operations are Legal (aka, supported natively by the target), but
1723 /// operations that are not should be described. Note that operations on
1724 /// non-legal value types are not described here.
1725 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1727 /// For each load extension type and each value type, keep a LegalizeAction
1728 /// that indicates how instruction selection should deal with a load of a
1729 /// specific value type and extension type.
1730 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1732 /// For each value type pair keep a LegalizeAction that indicates whether a
1733 /// truncating store of a specific value type and truncating type is legal.
1734 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1736 /// For each indexed mode and each value type, keep a pair of LegalizeAction
1737 /// that indicates how instruction selection should deal with the load /
1740 /// The first dimension is the value_type for the reference. The second
1741 /// dimension represents the various modes for load store.
1742 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1744 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
1745 /// indicates how instruction selection should deal with the condition code.
1747 /// Because each CC action takes up 2 bits, we need to have the array size be
1748 /// large enough to fit all of the value types. This can be done by rounding
1749 /// up the MVT::LAST_VALUETYPE value to the next multiple of 16.
1750 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 15) / 16];
1752 ValueTypeActionImpl ValueTypeActions;
1756 getTypeConversion(LLVMContext &Context, EVT VT) const {
1757 // If this is a simple type, use the ComputeRegisterProp mechanism.
1758 if (VT.isSimple()) {
1759 MVT SVT = VT.getSimpleVT();
1760 assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
1761 MVT NVT = TransformToType[SVT.SimpleTy];
1762 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1765 (LA == TypeLegal || LA == TypeSoftenFloat ||
1766 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)
1767 && "Promote may not follow Expand or Promote");
1769 if (LA == TypeSplitVector)
1770 return LegalizeKind(LA, EVT::getVectorVT(Context,
1771 SVT.getVectorElementType(),
1772 SVT.getVectorNumElements()/2));
1773 if (LA == TypeScalarizeVector)
1774 return LegalizeKind(LA, SVT.getVectorElementType());
1775 return LegalizeKind(LA, NVT);
1778 // Handle Extended Scalar Types.
1779 if (!VT.isVector()) {
1780 assert(VT.isInteger() && "Float types must be simple");
1781 unsigned BitSize = VT.getSizeInBits();
1782 // First promote to a power-of-two size, then expand if necessary.
1783 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1784 EVT NVT = VT.getRoundIntegerType(Context);
1785 assert(NVT != VT && "Unable to round integer VT");
1786 LegalizeKind NextStep = getTypeConversion(Context, NVT);
1787 // Avoid multi-step promotion.
1788 if (NextStep.first == TypePromoteInteger) return NextStep;
1789 // Return rounded integer type.
1790 return LegalizeKind(TypePromoteInteger, NVT);
1793 return LegalizeKind(TypeExpandInteger,
1794 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1797 // Handle vector types.
1798 unsigned NumElts = VT.getVectorNumElements();
1799 EVT EltVT = VT.getVectorElementType();
1801 // Vectors with only one element are always scalarized.
1803 return LegalizeKind(TypeScalarizeVector, EltVT);
1805 // Try to widen vector elements until the element type is a power of two and
1806 // promote it to a legal type later on, for example:
1807 // <3 x i8> -> <4 x i8> -> <4 x i32>
1808 if (EltVT.isInteger()) {
1809 // Vectors with a number of elements that is not a power of two are always
1810 // widened, for example <3 x i8> -> <4 x i8>.
1811 if (!VT.isPow2VectorType()) {
1812 NumElts = (unsigned)NextPowerOf2(NumElts);
1813 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1814 return LegalizeKind(TypeWidenVector, NVT);
1817 // Examine the element type.
1818 LegalizeKind LK = getTypeConversion(Context, EltVT);
1820 // If type is to be expanded, split the vector.
1821 // <4 x i140> -> <2 x i140>
1822 if (LK.first == TypeExpandInteger)
1823 return LegalizeKind(TypeSplitVector,
1824 EVT::getVectorVT(Context, EltVT, NumElts / 2));
1826 // Promote the integer element types until a legal vector type is found
1827 // or until the element integer type is too big. If a legal type was not
1828 // found, fallback to the usual mechanism of widening/splitting the
1830 EVT OldEltVT = EltVT;
1832 // Increase the bitwidth of the element to the next pow-of-two
1833 // (which is greater than 8 bits).
1834 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1835 ).getRoundIntegerType(Context);
1837 // Stop trying when getting a non-simple element type.
1838 // Note that vector elements may be greater than legal vector element
1839 // types. Example: X86 XMM registers hold 64bit element on 32bit
1841 if (!EltVT.isSimple()) break;
1843 // Build a new vector type and check if it is legal.
1844 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1845 // Found a legal promoted vector type.
1846 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1847 return LegalizeKind(TypePromoteInteger,
1848 EVT::getVectorVT(Context, EltVT, NumElts));
1851 // Reset the type to the unexpanded type if we did not find a legal vector
1852 // type with a promoted vector element type.
1856 // Try to widen the vector until a legal type is found.
1857 // If there is no wider legal type, split the vector.
1859 // Round up to the next power of 2.
1860 NumElts = (unsigned)NextPowerOf2(NumElts);
1862 // If there is no simple vector type with this many elements then there
1863 // cannot be a larger legal vector type. Note that this assumes that
1864 // there are no skipped intermediate vector types in the simple types.
1865 if (!EltVT.isSimple()) break;
1866 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1867 if (LargerVector == MVT()) break;
1869 // If this type is legal then widen the vector.
1870 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1871 return LegalizeKind(TypeWidenVector, LargerVector);
1874 // Widen odd vectors to next power of two.
1875 if (!VT.isPow2VectorType()) {
1876 EVT NVT = VT.getPow2VectorType(Context);
1877 return LegalizeKind(TypeWidenVector, NVT);
1880 // Vectors with illegal element types are expanded.
1881 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1882 return LegalizeKind(TypeSplitVector, NVT);
1886 std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
1888 /// Targets can specify ISD nodes that they would like PerformDAGCombine
1889 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
1892 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1894 /// For operations that must be promoted to a specific type, this holds the
1895 /// destination type. This map should be sparse, so don't hold it as an
1898 /// Targets add entries to this map with AddPromotedToType(..), clients access
1899 /// this with getTypeToPromoteTo(..).
1900 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1903 /// Stores the name each libcall.
1904 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1906 /// The ISD::CondCode that should be used to test the result of each of the
1907 /// comparison libcall against zero.
1908 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1910 /// Stores the CallingConv that should be used for each libcall.
1911 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1914 /// \brief Specify maximum number of store instructions per memset call.
1916 /// When lowering \@llvm.memset this field specifies the maximum number of
1917 /// store operations that may be substituted for the call to memset. Targets
1918 /// must set this value based on the cost threshold for that target. Targets
1919 /// should assume that the memset will be done using as many of the largest
1920 /// store operations first, followed by smaller ones, if necessary, per
1921 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1922 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1923 /// store. This only applies to setting a constant array of a constant size.
1924 unsigned MaxStoresPerMemset;
1926 /// Maximum number of stores operations that may be substituted for the call
1927 /// to memset, used for functions with OptSize attribute.
1928 unsigned MaxStoresPerMemsetOptSize;
1930 /// \brief Specify maximum bytes of store instructions per memcpy call.
1932 /// When lowering \@llvm.memcpy this field specifies the maximum number of
1933 /// store operations that may be substituted for a call to memcpy. Targets
1934 /// must set this value based on the cost threshold for that target. Targets
1935 /// should assume that the memcpy will be done using as many of the largest
1936 /// store operations first, followed by smaller ones, if necessary, per
1937 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1938 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1939 /// and one 1-byte store. This only applies to copying a constant array of
1941 unsigned MaxStoresPerMemcpy;
1943 /// Maximum number of store operations that may be substituted for a call to
1944 /// memcpy, used for functions with OptSize attribute.
1945 unsigned MaxStoresPerMemcpyOptSize;
1947 /// \brief Specify maximum bytes of store instructions per memmove call.
1949 /// When lowering \@llvm.memmove this field specifies the maximum number of
1950 /// store instructions that may be substituted for a call to memmove. Targets
1951 /// must set this value based on the cost threshold for that target. Targets
1952 /// should assume that the memmove will be done using as many of the largest
1953 /// store operations first, followed by smaller ones, if necessary, per
1954 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1955 /// with 8-bit alignment would result in nine 1-byte stores. This only
1956 /// applies to copying a constant array of constant size.
1957 unsigned MaxStoresPerMemmove;
1959 /// Maximum number of store instructions that may be substituted for a call to
1960 /// memmove, used for functions with OpSize attribute.
1961 unsigned MaxStoresPerMemmoveOptSize;
1963 /// Tells the code generator that select is more expensive than a branch if
1964 /// the branch is usually predicted right.
1965 bool PredictableSelectIsExpensive;
1967 /// MaskAndBranchFoldingIsLegal - Indicates if the target supports folding
1968 /// a mask of a single bit, a compare, and a branch into a single instruction.
1969 bool MaskAndBranchFoldingIsLegal;
1971 /// \see enableExtLdPromotion.
1972 bool EnableExtLdPromotion;
1975 /// Return true if the value types that can be represented by the specified
1976 /// register class are all legal.
1977 bool isLegalRC(const TargetRegisterClass *RC) const;
1979 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1980 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1981 MachineBasicBlock *emitPatchPoint(MachineInstr *MI, MachineBasicBlock *MBB) const;
1984 /// This class defines information used to lower LLVM code to legal SelectionDAG
1985 /// operators that the target instruction selector can accept natively.
1987 /// This class also defines callbacks that targets must implement to lower
1988 /// target-specific constructs to SelectionDAG operators.
1989 class TargetLowering : public TargetLoweringBase {
1990 TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
1991 void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
1994 /// NOTE: The TargetMachine owns TLOF.
1995 explicit TargetLowering(const TargetMachine &TM);
1997 /// Returns true by value, base pointer and offset pointer and addressing mode
1998 /// by reference if the node's address can be legally represented as
1999 /// pre-indexed load / store address.
2000 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2001 SDValue &/*Offset*/,
2002 ISD::MemIndexedMode &/*AM*/,
2003 SelectionDAG &/*DAG*/) const {
2007 /// Returns true by value, base pointer and offset pointer and addressing mode
2008 /// by reference if this node can be combined with a load / store to form a
2009 /// post-indexed load / store.
2010 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2012 SDValue &/*Offset*/,
2013 ISD::MemIndexedMode &/*AM*/,
2014 SelectionDAG &/*DAG*/) const {
2018 /// Return the entry encoding for a jump table in the current function. The
2019 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2020 virtual unsigned getJumpTableEncoding() const;
2022 virtual const MCExpr *
2023 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
2024 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2025 MCContext &/*Ctx*/) const {
2026 llvm_unreachable("Need to implement this hook if target has custom JTIs");
2029 /// Returns relocation base for the given PIC jumptable.
2030 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2031 SelectionDAG &DAG) const;
2033 /// This returns the relocation base for the given PIC jumptable, the same as
2034 /// getPICJumpTableRelocBase, but as an MCExpr.
2035 virtual const MCExpr *
2036 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2037 unsigned JTI, MCContext &Ctx) const;
2039 /// Return true if folding a constant offset with the given GlobalAddress is
2040 /// legal. It is frequently not legal in PIC relocation models.
2041 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2043 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
2044 SDValue &Chain) const;
2046 void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
2047 SDValue &NewLHS, SDValue &NewRHS,
2048 ISD::CondCode &CCCode, SDLoc DL) const;
2050 /// Returns a pair of (return value, chain).
2051 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
2052 EVT RetVT, const SDValue *Ops,
2053 unsigned NumOps, bool isSigned,
2054 SDLoc dl, bool doesNotReturn = false,
2055 bool isReturnValueUsed = true) const;
2057 //===--------------------------------------------------------------------===//
2058 // TargetLowering Optimization Methods
2061 /// A convenience struct that encapsulates a DAG, and two SDValues for
2062 /// returning information from TargetLowering to its clients that want to
2064 struct TargetLoweringOpt {
2071 explicit TargetLoweringOpt(SelectionDAG &InDAG,
2073 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2075 bool LegalTypes() const { return LegalTys; }
2076 bool LegalOperations() const { return LegalOps; }
2078 bool CombineTo(SDValue O, SDValue N) {
2084 /// Check to see if the specified operand of the specified instruction is a
2085 /// constant integer. If so, check to see if there are any bits set in the
2086 /// constant that are not demanded. If so, shrink the constant and return
2088 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
2090 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
2091 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
2092 /// generalized for targets with other types of implicit widening casts.
2093 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
2097 /// Look at Op. At this point, we know that only the DemandedMask bits of the
2098 /// result of Op are ever used downstream. If we can use this information to
2099 /// simplify Op, create a new simplified DAG node and return true, returning
2100 /// the original and new nodes in Old and New. Otherwise, analyze the
2101 /// expression and return a mask of KnownOne and KnownZero bits for the
2102 /// expression (used to simplify the caller). The KnownZero/One bits may only
2103 /// be accurate for those bits in the DemandedMask.
2104 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
2105 APInt &KnownZero, APInt &KnownOne,
2106 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
2108 /// Determine which of the bits specified in Mask are known to be either zero
2109 /// or one and return them in the KnownZero/KnownOne bitsets.
2110 virtual void computeKnownBitsForTargetNode(const SDValue Op,
2113 const SelectionDAG &DAG,
2114 unsigned Depth = 0) const;
2116 /// This method can be implemented by targets that want to expose additional
2117 /// information about sign bits to the DAG Combiner.
2118 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
2119 const SelectionDAG &DAG,
2120 unsigned Depth = 0) const;
2122 struct DAGCombinerInfo {
2123 void *DC; // The DAG Combiner object.
2125 bool CalledByLegalizer;
2129 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
2130 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
2132 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
2133 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
2134 bool isAfterLegalizeVectorOps() const {
2135 return Level == AfterLegalizeDAG;
2137 CombineLevel getDAGCombineLevel() { return Level; }
2138 bool isCalledByLegalizer() const { return CalledByLegalizer; }
2140 void AddToWorklist(SDNode *N);
2141 void RemoveFromWorklist(SDNode *N);
2142 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
2144 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
2145 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
2147 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
2150 /// Return if the N is a constant or constant vector equal to the true value
2151 /// from getBooleanContents().
2152 bool isConstTrueVal(const SDNode *N) const;
2154 /// Return if the N is a constant or constant vector equal to the false value
2155 /// from getBooleanContents().
2156 bool isConstFalseVal(const SDNode *N) const;
2158 /// Try to simplify a setcc built with the specified operands and cc. If it is
2159 /// unable to simplify it, return a null SDValue.
2160 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
2161 ISD::CondCode Cond, bool foldBooleans,
2162 DAGCombinerInfo &DCI, SDLoc dl) const;
2164 /// Returns true (and the GlobalValue and the offset) if the node is a
2165 /// GlobalAddress + offset.
2167 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
2169 /// This method will be invoked for all target nodes and for any
2170 /// target-independent nodes that the target has registered with invoke it
2173 /// The semantics are as follows:
2175 /// SDValue.Val == 0 - No change was made
2176 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
2177 /// otherwise - N should be replaced by the returned Operand.
2179 /// In addition, methods provided by DAGCombinerInfo may be used to perform
2180 /// more complex transformations.
2182 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
2184 /// Return true if it is profitable to move a following shift through this
2185 // node, adjusting any immediate operands as necessary to preserve semantics.
2186 // This transformation may not be desirable if it disrupts a particularly
2187 // auspicious target-specific tree (e.g. bitfield extraction in AArch64).
2188 // By default, it returns true.
2189 virtual bool isDesirableToCommuteWithShift(const SDNode *N /*Op*/) const {
2193 /// Return true if the target has native support for the specified value type
2194 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
2195 /// i16 is legal, but undesirable since i16 instruction encodings are longer
2196 /// and some i16 instructions are slow.
2197 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
2198 // By default, assume all legal types are desirable.
2199 return isTypeLegal(VT);
2202 /// Return true if it is profitable for dag combiner to transform a floating
2203 /// point op of specified opcode to a equivalent op of an integer
2204 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
2205 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
2210 /// This method query the target whether it is beneficial for dag combiner to
2211 /// promote the specified node. If true, it should return the desired
2212 /// promotion type by reference.
2213 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
2217 //===--------------------------------------------------------------------===//
2218 // Lowering methods - These methods must be implemented by targets so that
2219 // the SelectionDAGBuilder code knows how to lower these.
2222 /// This hook must be implemented to lower the incoming (formal) arguments,
2223 /// described by the Ins array, into the specified DAG. The implementation
2224 /// should fill in the InVals array with legal-type argument values, and
2225 /// return the resulting token chain value.
2228 LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2230 const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
2231 SDLoc /*dl*/, SelectionDAG &/*DAG*/,
2232 SmallVectorImpl<SDValue> &/*InVals*/) const {
2233 llvm_unreachable("Not Implemented");
2236 struct ArgListEntry {
2245 bool isInAlloca : 1;
2246 bool isReturned : 1;
2249 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
2250 isSRet(false), isNest(false), isByVal(false), isInAlloca(false),
2251 isReturned(false), Alignment(0) { }
2253 void setAttributes(ImmutableCallSite *CS, unsigned AttrIdx);
2255 typedef std::vector<ArgListEntry> ArgListTy;
2257 /// This structure contains all information that is necessary for lowering
2258 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
2259 /// needs to lower a call, and targets will see this struct in their LowerCall
2261 struct CallLoweringInfo {
2268 bool DoesNotReturn : 1;
2269 bool IsReturnValueUsed : 1;
2271 // IsTailCall should be modified by implementations of
2272 // TargetLowering::LowerCall that perform tail call conversions.
2275 unsigned NumFixedArgs;
2276 CallingConv::ID CallConv;
2281 ImmutableCallSite *CS;
2282 SmallVector<ISD::OutputArg, 32> Outs;
2283 SmallVector<SDValue, 32> OutVals;
2284 SmallVector<ISD::InputArg, 32> Ins;
2286 CallLoweringInfo(SelectionDAG &DAG)
2287 : RetTy(nullptr), RetSExt(false), RetZExt(false), IsVarArg(false),
2288 IsInReg(false), DoesNotReturn(false), IsReturnValueUsed(true),
2289 IsTailCall(false), NumFixedArgs(-1), CallConv(CallingConv::C),
2290 DAG(DAG), CS(nullptr) {}
2292 CallLoweringInfo &setDebugLoc(SDLoc dl) {
2297 CallLoweringInfo &setChain(SDValue InChain) {
2302 CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
2303 SDValue Target, ArgListTy &&ArgsList,
2304 unsigned FixedArgs = -1) {
2309 (FixedArgs == static_cast<unsigned>(-1) ? Args.size() : FixedArgs);
2310 Args = std::move(ArgsList);
2314 CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
2315 SDValue Target, ArgListTy &&ArgsList,
2316 ImmutableCallSite &Call) {
2319 IsInReg = Call.paramHasAttr(0, Attribute::InReg);
2320 DoesNotReturn = Call.doesNotReturn();
2321 IsVarArg = FTy->isVarArg();
2322 IsReturnValueUsed = !Call.getInstruction()->use_empty();
2323 RetSExt = Call.paramHasAttr(0, Attribute::SExt);
2324 RetZExt = Call.paramHasAttr(0, Attribute::ZExt);
2328 CallConv = Call.getCallingConv();
2329 NumFixedArgs = FTy->getNumParams();
2330 Args = std::move(ArgsList);
2337 CallLoweringInfo &setInRegister(bool Value = true) {
2342 CallLoweringInfo &setNoReturn(bool Value = true) {
2343 DoesNotReturn = Value;
2347 CallLoweringInfo &setVarArg(bool Value = true) {
2352 CallLoweringInfo &setTailCall(bool Value = true) {
2357 CallLoweringInfo &setDiscardResult(bool Value = true) {
2358 IsReturnValueUsed = !Value;
2362 CallLoweringInfo &setSExtResult(bool Value = true) {
2367 CallLoweringInfo &setZExtResult(bool Value = true) {
2372 ArgListTy &getArgs() {
2377 /// This function lowers an abstract call to a function into an actual call.
2378 /// This returns a pair of operands. The first element is the return value
2379 /// for the function (if RetTy is not VoidTy). The second element is the
2380 /// outgoing token chain. It calls LowerCall to do the actual lowering.
2381 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
2383 /// This hook must be implemented to lower calls into the the specified
2384 /// DAG. The outgoing arguments to the call are described by the Outs array,
2385 /// and the values to be returned by the call are described by the Ins
2386 /// array. The implementation should fill in the InVals array with legal-type
2387 /// return values from the call, and return the resulting token chain value.
2389 LowerCall(CallLoweringInfo &/*CLI*/,
2390 SmallVectorImpl<SDValue> &/*InVals*/) const {
2391 llvm_unreachable("Not Implemented");
2394 /// Target-specific cleanup for formal ByVal parameters.
2395 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
2397 /// This hook should be implemented to check whether the return values
2398 /// described by the Outs array can fit into the return registers. If false
2399 /// is returned, an sret-demotion is performed.
2400 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
2401 MachineFunction &/*MF*/, bool /*isVarArg*/,
2402 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2403 LLVMContext &/*Context*/) const
2405 // Return true by default to get preexisting behavior.
2409 /// This hook must be implemented to lower outgoing return values, described
2410 /// by the Outs array, into the specified DAG. The implementation should
2411 /// return the resulting token chain value.
2413 LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2415 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2416 const SmallVectorImpl<SDValue> &/*OutVals*/,
2417 SDLoc /*dl*/, SelectionDAG &/*DAG*/) const {
2418 llvm_unreachable("Not Implemented");
2421 /// Return true if result of the specified node is used by a return node
2422 /// only. It also compute and return the input chain for the tail call.
2424 /// This is used to determine whether it is possible to codegen a libcall as
2425 /// tail call at legalization time.
2426 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
2430 /// Return true if the target may be able emit the call instruction as a tail
2431 /// call. This is used by optimization passes to determine if it's profitable
2432 /// to duplicate return instructions to enable tailcall optimization.
2433 virtual bool mayBeEmittedAsTailCall(CallInst *) const {
2437 /// Return the builtin name for the __builtin___clear_cache intrinsic
2438 /// Default is to invoke the clear cache library call
2439 virtual const char * getClearCacheBuiltinName() const {
2440 return "__clear_cache";
2443 /// Return the register ID of the name passed in. Used by named register
2444 /// global variables extension. There is no target-independent behaviour
2445 /// so the default action is to bail.
2446 virtual unsigned getRegisterByName(const char* RegName, EVT VT) const {
2447 report_fatal_error("Named registers not implemented for this target");
2450 /// Return the type that should be used to zero or sign extend a
2451 /// zeroext/signext integer argument or return value. FIXME: Most C calling
2452 /// convention requires the return type to be promoted, but this is not true
2453 /// all the time, e.g. i1 on x86-64. It is also not necessary for non-C
2454 /// calling conventions. The frontend should handle this and include all of
2455 /// the necessary information.
2456 virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2457 ISD::NodeType /*ExtendKind*/) const {
2458 EVT MinVT = getRegisterType(Context, MVT::i32);
2459 return VT.bitsLT(MinVT) ? MinVT : VT;
2462 /// For some targets, an LLVM struct type must be broken down into multiple
2463 /// simple types, but the calling convention specifies that the entire struct
2464 /// must be passed in a block of consecutive registers.
2466 functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
2467 bool isVarArg) const {
2471 /// Returns a 0 terminated array of registers that can be safely used as
2472 /// scratch registers.
2473 virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
2477 /// This callback is used to prepare for a volatile or atomic load.
2478 /// It takes a chain node as input and returns the chain for the load itself.
2480 /// Having a callback like this is necessary for targets like SystemZ,
2481 /// which allows a CPU to reuse the result of a previous load indefinitely,
2482 /// even if a cache-coherent store is performed by another CPU. The default
2483 /// implementation does nothing.
2484 virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL,
2485 SelectionDAG &DAG) const {
2489 /// This callback is invoked by the type legalizer to legalize nodes with an
2490 /// illegal operand type but legal result types. It replaces the
2491 /// LowerOperation callback in the type Legalizer. The reason we can not do
2492 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
2493 /// use this callback.
2495 /// TODO: Consider merging with ReplaceNodeResults.
2497 /// The target places new result values for the node in Results (their number
2498 /// and types must exactly match those of the original return values of
2499 /// the node), or leaves Results empty, which indicates that the node is not
2500 /// to be custom lowered after all.
2501 /// The default implementation calls LowerOperation.
2502 virtual void LowerOperationWrapper(SDNode *N,
2503 SmallVectorImpl<SDValue> &Results,
2504 SelectionDAG &DAG) const;
2506 /// This callback is invoked for operations that are unsupported by the
2507 /// target, which are registered to use 'custom' lowering, and whose defined
2508 /// values are all legal. If the target has no operations that require custom
2509 /// lowering, it need not implement this. The default implementation of this
2511 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2513 /// This callback is invoked when a node result type is illegal for the
2514 /// target, and the operation was registered to use 'custom' lowering for that
2515 /// result type. The target places new result values for the node in Results
2516 /// (their number and types must exactly match those of the original return
2517 /// values of the node), or leaves Results empty, which indicates that the
2518 /// node is not to be custom lowered after all.
2520 /// If the target has no operations that require custom lowering, it need not
2521 /// implement this. The default implementation aborts.
2522 virtual void ReplaceNodeResults(SDNode * /*N*/,
2523 SmallVectorImpl<SDValue> &/*Results*/,
2524 SelectionDAG &/*DAG*/) const {
2525 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
2528 /// This method returns the name of a target specific DAG node.
2529 virtual const char *getTargetNodeName(unsigned Opcode) const;
2531 /// This method returns a target specific FastISel object, or null if the
2532 /// target does not support "fast" ISel.
2533 virtual FastISel *createFastISel(FunctionLoweringInfo &,
2534 const TargetLibraryInfo *) const {
2539 bool verifyReturnAddressArgumentIsConstant(SDValue Op,
2540 SelectionDAG &DAG) const;
2542 //===--------------------------------------------------------------------===//
2543 // Inline Asm Support hooks
2546 /// This hook allows the target to expand an inline asm call to be explicit
2547 /// llvm code if it wants to. This is useful for turning simple inline asms
2548 /// into LLVM intrinsics, which gives the compiler more information about the
2549 /// behavior of the code.
2550 virtual bool ExpandInlineAsm(CallInst *) const {
2554 enum ConstraintType {
2555 C_Register, // Constraint represents specific register(s).
2556 C_RegisterClass, // Constraint represents any of register(s) in class.
2557 C_Memory, // Memory constraint.
2558 C_Other, // Something else.
2559 C_Unknown // Unsupported constraint.
2562 enum ConstraintWeight {
2564 CW_Invalid = -1, // No match.
2565 CW_Okay = 0, // Acceptable.
2566 CW_Good = 1, // Good weight.
2567 CW_Better = 2, // Better weight.
2568 CW_Best = 3, // Best weight.
2570 // Well-known weights.
2571 CW_SpecificReg = CW_Okay, // Specific register operands.
2572 CW_Register = CW_Good, // Register operands.
2573 CW_Memory = CW_Better, // Memory operands.
2574 CW_Constant = CW_Best, // Constant operand.
2575 CW_Default = CW_Okay // Default or don't know type.
2578 /// This contains information for each constraint that we are lowering.
2579 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2580 /// This contains the actual string for the code, like "m". TargetLowering
2581 /// picks the 'best' code from ConstraintInfo::Codes that most closely
2582 /// matches the operand.
2583 std::string ConstraintCode;
2585 /// Information about the constraint code, e.g. Register, RegisterClass,
2586 /// Memory, Other, Unknown.
2587 TargetLowering::ConstraintType ConstraintType;
2589 /// If this is the result output operand or a clobber, this is null,
2590 /// otherwise it is the incoming operand to the CallInst. This gets
2591 /// modified as the asm is processed.
2592 Value *CallOperandVal;
2594 /// The ValueType for the operand value.
2597 /// Return true of this is an input operand that is a matching constraint
2599 bool isMatchingInputConstraint() const;
2601 /// If this is an input matching constraint, this method returns the output
2602 /// operand it matches.
2603 unsigned getMatchedOperand() const;
2605 /// Copy constructor for copying from a ConstraintInfo.
2606 AsmOperandInfo(InlineAsm::ConstraintInfo Info)
2607 : InlineAsm::ConstraintInfo(std::move(Info)),
2608 ConstraintType(TargetLowering::C_Unknown), CallOperandVal(nullptr),
2609 ConstraintVT(MVT::Other) {}
2612 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
2614 /// Split up the constraint string from the inline assembly value into the
2615 /// specific constraints and their prefixes, and also tie in the associated
2616 /// operand values. If this returns an empty vector, and if the constraint
2617 /// string itself isn't empty, there was an error parsing.
2618 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
2620 /// Examine constraint type and operand type and determine a weight value.
2621 /// The operand object must already have been set up with the operand type.
2622 virtual ConstraintWeight getMultipleConstraintMatchWeight(
2623 AsmOperandInfo &info, int maIndex) const;
2625 /// Examine constraint string and operand type and determine a weight value.
2626 /// The operand object must already have been set up with the operand type.
2627 virtual ConstraintWeight getSingleConstraintMatchWeight(
2628 AsmOperandInfo &info, const char *constraint) const;
2630 /// Determines the constraint code and constraint type to use for the specific
2631 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2632 /// If the actual operand being passed in is available, it can be passed in as
2633 /// Op, otherwise an empty SDValue can be passed.
2634 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2636 SelectionDAG *DAG = nullptr) const;
2638 /// Given a constraint, return the type of constraint it is for this target.
2639 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
2641 /// Given a physical register constraint (e.g. {edx}), return the register
2642 /// number and the register class for the register.
2644 /// Given a register class constraint, like 'r', if this corresponds directly
2645 /// to an LLVM register class, return a register of 0 and the register class
2648 /// This should only be used for C_Register constraints. On error, this
2649 /// returns a register number of 0 and a null register class pointer..
2650 virtual std::pair<unsigned, const TargetRegisterClass*>
2651 getRegForInlineAsmConstraint(const std::string &Constraint,
2654 /// Try to replace an X constraint, which matches anything, with another that
2655 /// has more specific requirements based on the type of the corresponding
2656 /// operand. This returns null if there is no replacement to make.
2657 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
2659 /// Lower the specified operand into the Ops vector. If it is invalid, don't
2660 /// add anything to Ops.
2661 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
2662 std::vector<SDValue> &Ops,
2663 SelectionDAG &DAG) const;
2665 //===--------------------------------------------------------------------===//
2666 // Div utility functions
2668 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2669 SelectionDAG &DAG) const;
2670 SDValue BuildSDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
2671 bool IsAfterLegalization,
2672 std::vector<SDNode *> *Created) const;
2673 SDValue BuildUDIV(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
2674 bool IsAfterLegalization,
2675 std::vector<SDNode *> *Created) const;
2676 virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2678 std::vector<SDNode *> *Created) const {
2682 /// Indicate whether this target prefers to combine the given number of FDIVs
2683 /// with the same divisor.
2684 virtual bool combineRepeatedFPDivisors(unsigned NumUsers) const {
2688 /// Hooks for building estimates in place of slower divisions and square
2691 /// Return a reciprocal square root estimate value for the input operand.
2692 /// The RefinementSteps output is the number of Newton-Raphson refinement
2693 /// iterations required to generate a sufficient (though not necessarily
2694 /// IEEE-754 compliant) estimate for the value type.
2695 /// The boolean UseOneConstNR output is used to select a Newton-Raphson
2696 /// algorithm implementation that uses one constant or two constants.
2697 /// A target may choose to implement its own refinement within this function.
2698 /// If that's true, then return '0' as the number of RefinementSteps to avoid
2699 /// any further refinement of the estimate.
2700 /// An empty SDValue return means no estimate sequence can be created.
2701 virtual SDValue getRsqrtEstimate(SDValue Operand,
2702 DAGCombinerInfo &DCI,
2703 unsigned &RefinementSteps,
2704 bool &UseOneConstNR) const {
2708 /// Return a reciprocal estimate value for the input operand.
2709 /// The RefinementSteps output is the number of Newton-Raphson refinement
2710 /// iterations required to generate a sufficient (though not necessarily
2711 /// IEEE-754 compliant) estimate for the value type.
2712 /// A target may choose to implement its own refinement within this function.
2713 /// If that's true, then return '0' as the number of RefinementSteps to avoid
2714 /// any further refinement of the estimate.
2715 /// An empty SDValue return means no estimate sequence can be created.
2716 virtual SDValue getRecipEstimate(SDValue Operand,
2717 DAGCombinerInfo &DCI,
2718 unsigned &RefinementSteps) const {
2722 //===--------------------------------------------------------------------===//
2723 // Legalization utility functions
2726 /// Expand a MUL into two nodes. One that computes the high bits of
2727 /// the result and one that computes the low bits.
2728 /// \param HiLoVT The value type to use for the Lo and Hi nodes.
2729 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
2730 /// if you want to control how low bits are extracted from the LHS.
2731 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
2732 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
2733 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
2734 /// \returns true if the node has been expanded. false if it has not
2735 bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
2736 SelectionDAG &DAG, SDValue LL = SDValue(),
2737 SDValue LH = SDValue(), SDValue RL = SDValue(),
2738 SDValue RH = SDValue()) const;
2740 /// Expand float(f32) to SINT(i64) conversion
2741 /// \param N Node to expand
2742 /// \param Result output after conversion
2743 /// \returns True, if the expansion was successful, false otherwise
2744 bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
2746 //===--------------------------------------------------------------------===//
2747 // Instruction Emitting Hooks
2750 /// This method should be implemented by targets that mark instructions with
2751 /// the 'usesCustomInserter' flag. These instructions are special in various
2752 /// ways, which require special support to insert. The specified MachineInstr
2753 /// is created but not inserted into any basic blocks, and this method is
2754 /// called to expand it into a sequence of instructions, potentially also
2755 /// creating new basic blocks and control flow.
2756 virtual MachineBasicBlock *
2757 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
2759 /// This method should be implemented by targets that mark instructions with
2760 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
2761 /// instruction selection by target hooks. e.g. To fill in optional defs for
2762 /// ARM 's' setting instructions.
2764 AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
2766 /// If this function returns true, SelectionDAGBuilder emits a
2767 /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
2768 virtual bool useLoadStackGuardNode() const {
2773 /// Given an LLVM IR type and return type attributes, compute the return value
2774 /// EVTs and flags, and optionally also the offsets, if the return value is
2775 /// being lowered to memory.
2776 void GetReturnInfo(Type* ReturnType, AttributeSet attr,
2777 SmallVectorImpl<ISD::OutputArg> &Outs,
2778 const TargetLowering &TLI);
2780 } // end llvm namespace