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/MC/MCRegisterInfo.h"
35 #include "llvm/Target/TargetCallingConv.h"
36 #include "llvm/Target/TargetMachine.h"
45 class FunctionLoweringInfo;
46 class ImmutableCallSite;
48 class MachineBasicBlock;
49 class MachineFunction;
51 class MachineJumpTableInfo;
56 template<typename T> class SmallVectorImpl;
58 class TargetRegisterClass;
59 class TargetLibraryInfo;
60 class TargetLoweringObjectFile;
65 None, // No preference
66 Source, // Follow source order.
67 RegPressure, // Scheduling for lowest register pressure.
68 Hybrid, // Scheduling for both latency and register pressure.
69 ILP, // Scheduling for ILP in low register pressure mode.
70 VLIW // Scheduling for VLIW targets.
74 /// This base class for TargetLowering contains the SelectionDAG-independent
75 /// parts that can be used from the rest of CodeGen.
76 class TargetLoweringBase {
77 TargetLoweringBase(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
78 void operator=(const TargetLoweringBase&) LLVM_DELETED_FUNCTION;
81 /// This enum indicates whether operations are valid for a target, and if not,
82 /// what action should be used to make them valid.
84 Legal, // The target natively supports this operation.
85 Promote, // This operation should be executed in a larger type.
86 Expand, // Try to expand this to other ops, otherwise use a libcall.
87 Custom // Use the LowerOperation hook to implement custom lowering.
90 /// This enum indicates whether a types are legal for a target, and if not,
91 /// what action should be used to make them valid.
92 enum LegalizeTypeAction {
93 TypeLegal, // The target natively supports this type.
94 TypePromoteInteger, // Replace this integer with a larger one.
95 TypeExpandInteger, // Split this integer into two of half the size.
96 TypeSoftenFloat, // Convert this float to a same size integer type.
97 TypeExpandFloat, // Split this float into two of half the size.
98 TypeScalarizeVector, // Replace this one-element vector with its element.
99 TypeSplitVector, // Split this vector into two of half the size.
100 TypeWidenVector // This vector should be widened into a larger vector.
103 /// LegalizeKind holds the legalization kind that needs to happen to EVT
104 /// in order to type-legalize it.
105 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind;
107 /// Enum that describes how the target represents true/false values.
108 enum BooleanContent {
109 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
110 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
111 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
114 /// Enum that describes what type of support for selects the target has.
115 enum SelectSupportKind {
116 ScalarValSelect, // The target supports scalar selects (ex: cmov).
117 ScalarCondVectorVal, // The target supports selects with a scalar condition
118 // and vector values (ex: cmov).
119 VectorMaskSelect // The target supports vector selects with a vector
120 // mask (ex: x86 blends).
123 static ISD::NodeType getExtendForContent(BooleanContent Content) {
125 case UndefinedBooleanContent:
126 // Extend by adding rubbish bits.
127 return ISD::ANY_EXTEND;
128 case ZeroOrOneBooleanContent:
129 // Extend by adding zero bits.
130 return ISD::ZERO_EXTEND;
131 case ZeroOrNegativeOneBooleanContent:
132 // Extend by copying the sign bit.
133 return ISD::SIGN_EXTEND;
135 llvm_unreachable("Invalid content kind");
138 /// NOTE: The constructor takes ownership of TLOF.
139 explicit TargetLoweringBase(const TargetMachine &TM,
140 const TargetLoweringObjectFile *TLOF);
141 virtual ~TargetLoweringBase();
144 /// \brief Initialize all of the actions to default values.
148 const TargetMachine &getTargetMachine() const { return TM; }
149 const DataLayout *getDataLayout() const { return DL; }
150 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; }
152 bool isBigEndian() const { return !IsLittleEndian; }
153 bool isLittleEndian() const { return IsLittleEndian; }
155 /// Return the pointer type for the given address space, defaults to
156 /// the pointer type from the data layout.
157 /// FIXME: The default needs to be removed once all the code is updated.
158 virtual MVT getPointerTy(uint32_t /*AS*/ = 0) const;
159 unsigned getPointerSizeInBits(uint32_t AS = 0) const;
160 unsigned getPointerTypeSizeInBits(Type *Ty) const;
161 virtual MVT getScalarShiftAmountTy(EVT LHSTy) const;
163 EVT getShiftAmountTy(EVT LHSTy) const;
165 /// Returns the type to be used for the index operand of:
166 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
167 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
168 virtual MVT getVectorIdxTy() const {
169 return getPointerTy();
172 /// Return true if the select operation is expensive for this target.
173 bool isSelectExpensive() const { return SelectIsExpensive; }
175 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
179 /// Return true if multiple condition registers are available.
180 bool hasMultipleConditionRegisters() const {
181 return HasMultipleConditionRegisters;
184 /// Return true if a vector of the given type should be split
185 /// (TypeSplitVector) instead of promoted (TypePromoteInteger) during type
187 virtual bool shouldSplitVectorType(EVT /*VT*/) const { return false; }
189 // There are two general methods for expanding a BUILD_VECTOR node:
190 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
192 // 2. Build the vector on the stack and then load it.
193 // If this function returns true, then method (1) will be used, subject to
194 // the constraint that all of the necessary shuffles are legal (as determined
195 // by isShuffleMaskLegal). If this function returns false, then method (2) is
196 // always used. The vector type, and the number of defined values, are
199 shouldExpandBuildVectorWithShuffles(EVT /* VT */,
200 unsigned DefinedValues) const {
201 return DefinedValues < 3;
204 /// Return true if integer divide is usually cheaper than a sequence of
205 /// several shifts, adds, and multiplies for this target.
206 bool isIntDivCheap() const { return IntDivIsCheap; }
208 /// Returns true if target has indicated at least one type should be bypassed.
209 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
211 /// Returns map of slow types for division or remainder with corresponding
213 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
214 return BypassSlowDivWidths;
217 /// Return true if pow2 div is cheaper than a chain of srl/add/sra.
218 bool isPow2DivCheap() const { return Pow2DivIsCheap; }
220 /// Return true if Flow Control is an expensive operation that should be
222 bool isJumpExpensive() const { return JumpIsExpensive; }
224 /// Return true if selects are only cheaper than branches if the branch is
225 /// unlikely to be predicted right.
226 bool isPredictableSelectExpensive() const {
227 return PredictableSelectIsExpensive;
230 /// isLoadBitCastBeneficial() - Return true if the following transform
232 /// fold (conv (load x)) -> (load (conv*)x)
233 /// On architectures that don't natively support some vector loads efficiently,
234 /// casting the load to a smaller vector of larger types and loading
235 /// is more efficient, however, this can be undone by optimizations in
237 virtual bool isLoadBitCastBeneficial(EVT /* Load */, EVT /* Bitcast */) const {
241 /// \brief Return if the target supports combining a
244 /// %andResult = and %val1, #imm-with-one-bit-set;
245 /// %icmpResult = icmp %andResult, 0
246 /// br i1 %icmpResult, label %dest1, label %dest2
248 /// into a single machine instruction of a form like:
250 /// brOnBitSet %register, #bitNumber, dest
252 bool isMaskAndBranchFoldingLegal() const {
253 return MaskAndBranchFoldingIsLegal;
256 /// Return the ValueType of the result of SETCC operations. Also used to
257 /// obtain the target's preferred type for the condition operand of SELECT and
258 /// BRCOND nodes. In the case of BRCOND the argument passed is MVT::Other
259 /// since there are no other operands to get a type hint from.
260 virtual EVT getSetCCResultType(LLVMContext &Context, EVT VT) const;
262 /// Return the ValueType for comparison libcalls. Comparions libcalls include
263 /// floating point comparion calls, and Ordered/Unordered check calls on
264 /// floating point numbers.
266 MVT::SimpleValueType getCmpLibcallReturnType() const;
268 /// For targets without i1 registers, this gives the nature of the high-bits
269 /// of boolean values held in types wider than i1.
271 /// "Boolean values" are special true/false values produced by nodes like
272 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
273 /// Not to be confused with general values promoted from i1. Some cpus
274 /// distinguish between vectors of boolean and scalars; the isVec parameter
275 /// selects between the two kinds. For example on X86 a scalar boolean should
276 /// be zero extended from i1, while the elements of a vector of booleans
277 /// should be sign extended from i1.
278 BooleanContent getBooleanContents(bool isVec) const {
279 return isVec ? BooleanVectorContents : BooleanContents;
282 /// Return target scheduling preference.
283 Sched::Preference getSchedulingPreference() const {
284 return SchedPreferenceInfo;
287 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
288 /// for different nodes. This function returns the preference (or none) for
290 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
294 /// Return the register class that should be used for the specified value
296 virtual const TargetRegisterClass *getRegClassFor(MVT VT) const {
297 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
298 assert(RC && "This value type is not natively supported!");
302 /// Return the 'representative' register class for the specified value
305 /// The 'representative' register class is the largest legal super-reg
306 /// register class for the register class of the value type. For example, on
307 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
308 /// register class is GR64 on x86_64.
309 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
310 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
314 /// Return the cost of the 'representative' register class for the specified
316 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
317 return RepRegClassCostForVT[VT.SimpleTy];
320 /// Return true if the target has native support for the specified value type.
321 /// This means that it has a register that directly holds it without
322 /// promotions or expansions.
323 bool isTypeLegal(EVT VT) const {
324 assert(!VT.isSimple() ||
325 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
326 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0;
329 class ValueTypeActionImpl {
330 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
331 /// that indicates how instruction selection should deal with the type.
332 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE];
335 ValueTypeActionImpl() {
336 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0);
339 LegalizeTypeAction getTypeAction(MVT VT) const {
340 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy];
343 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
344 unsigned I = VT.SimpleTy;
345 ValueTypeActions[I] = Action;
349 const ValueTypeActionImpl &getValueTypeActions() const {
350 return ValueTypeActions;
353 /// Return how we should legalize values of this type, either it is already
354 /// legal (return 'Legal') or we need to promote it to a larger type (return
355 /// 'Promote'), or we need to expand it into multiple registers of smaller
356 /// integer type (return 'Expand'). 'Custom' is not an option.
357 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
358 return getTypeConversion(Context, VT).first;
360 LegalizeTypeAction getTypeAction(MVT VT) const {
361 return ValueTypeActions.getTypeAction(VT);
364 /// For types supported by the target, this is an identity function. For
365 /// types that must be promoted to larger types, this returns the larger type
366 /// to promote to. For integer types that are larger than the largest integer
367 /// register, this contains one step in the expansion to get to the smaller
368 /// register. For illegal floating point types, this returns the integer type
370 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
371 return getTypeConversion(Context, VT).second;
374 /// For types supported by the target, this is an identity function. For
375 /// types that must be expanded (i.e. integer types that are larger than the
376 /// largest integer register or illegal floating point types), this returns
377 /// the largest legal type it will be expanded to.
378 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
379 assert(!VT.isVector());
381 switch (getTypeAction(Context, VT)) {
384 case TypeExpandInteger:
385 VT = getTypeToTransformTo(Context, VT);
388 llvm_unreachable("Type is not legal nor is it to be expanded!");
393 /// Vector types are broken down into some number of legal first class types.
394 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
395 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
396 /// turns into 4 EVT::i32 values with both PPC and X86.
398 /// This method returns the number of registers needed, and the VT for each
399 /// register. It also returns the VT and quantity of the intermediate values
400 /// before they are promoted/expanded.
401 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
403 unsigned &NumIntermediates,
404 MVT &RegisterVT) const;
406 struct IntrinsicInfo {
407 unsigned opc; // target opcode
408 EVT memVT; // memory VT
409 const Value* ptrVal; // value representing memory location
410 int offset; // offset off of ptrVal
411 unsigned align; // alignment
412 bool vol; // is volatile?
413 bool readMem; // reads memory?
414 bool writeMem; // writes memory?
417 /// Given an intrinsic, checks if on the target the intrinsic will need to map
418 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
419 /// true and store the intrinsic information into the IntrinsicInfo that was
420 /// passed to the function.
421 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
422 unsigned /*Intrinsic*/) const {
426 /// Returns true if the target can instruction select the specified FP
427 /// immediate natively. If false, the legalizer will materialize the FP
428 /// immediate as a load from a constant pool.
429 virtual bool isFPImmLegal(const APFloat &/*Imm*/, EVT /*VT*/) const {
433 /// Targets can use this to indicate that they only support *some*
434 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
435 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
437 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
442 /// Returns true if the operation can trap for the value type.
444 /// VT must be a legal type. By default, we optimistically assume most
445 /// operations don't trap except for divide and remainder.
446 virtual bool canOpTrap(unsigned Op, EVT VT) const;
448 /// Similar to isShuffleMaskLegal. This is used by Targets can use this to
449 /// indicate if there is a suitable VECTOR_SHUFFLE that can be used to replace
450 /// a VAND with a constant pool entry.
451 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &/*Mask*/,
456 /// Return how this operation should be treated: either it is legal, needs to
457 /// be promoted to a larger size, needs to be expanded to some other code
458 /// sequence, or the target has a custom expander for it.
459 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
460 if (VT.isExtended()) return Expand;
461 // If a target-specific SDNode requires legalization, require the target
462 // to provide custom legalization for it.
463 if (Op > array_lengthof(OpActions[0])) return Custom;
464 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy;
465 return (LegalizeAction)OpActions[I][Op];
468 /// Return true if the specified operation is legal on this target or can be
469 /// made legal with custom lowering. This is used to help guide high-level
470 /// lowering decisions.
471 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
472 return (VT == MVT::Other || isTypeLegal(VT)) &&
473 (getOperationAction(Op, VT) == Legal ||
474 getOperationAction(Op, VT) == Custom);
477 /// Return true if the specified operation is legal on this target or can be
478 /// made legal using promotion. This is used to help guide high-level lowering
480 bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
481 return (VT == MVT::Other || isTypeLegal(VT)) &&
482 (getOperationAction(Op, VT) == Legal ||
483 getOperationAction(Op, VT) == Promote);
486 /// Return true if the specified operation is illegal on this target or
487 /// unlikely to be made legal with custom lowering. This is used to help guide
488 /// high-level lowering decisions.
489 bool isOperationExpand(unsigned Op, EVT VT) const {
490 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
493 /// Return true if the specified operation is legal on this target.
494 bool isOperationLegal(unsigned Op, EVT VT) const {
495 return (VT == MVT::Other || isTypeLegal(VT)) &&
496 getOperationAction(Op, VT) == Legal;
499 /// Return how this load with extension should be treated: either it is legal,
500 /// needs to be promoted to a larger size, needs to be expanded to some other
501 /// code sequence, or the target has a custom expander for it.
502 LegalizeAction getLoadExtAction(unsigned ExtType, MVT VT) const {
503 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
504 "Table isn't big enough!");
505 return (LegalizeAction)LoadExtActions[VT.SimpleTy][ExtType];
508 /// Return true if the specified load with extension is legal on this target.
509 bool isLoadExtLegal(unsigned ExtType, EVT VT) const {
510 return VT.isSimple() &&
511 getLoadExtAction(ExtType, VT.getSimpleVT()) == Legal;
514 /// Return how this store with truncation should be treated: either it is
515 /// legal, needs to be promoted to a larger size, needs to be expanded to some
516 /// other code sequence, or the target has a custom expander for it.
517 LegalizeAction getTruncStoreAction(MVT ValVT, MVT MemVT) const {
518 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
519 "Table isn't big enough!");
520 return (LegalizeAction)TruncStoreActions[ValVT.SimpleTy]
524 /// Return true if the specified store with truncation is legal on this
526 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
527 return isTypeLegal(ValVT) && MemVT.isSimple() &&
528 getTruncStoreAction(ValVT.getSimpleVT(), MemVT.getSimpleVT()) == Legal;
531 /// Return how the indexed load should be treated: either it is legal, needs
532 /// to be promoted to a larger size, needs to be expanded to some other code
533 /// sequence, or the target has a custom expander for it.
535 getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
536 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
537 "Table isn't big enough!");
538 unsigned Ty = (unsigned)VT.SimpleTy;
539 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
542 /// Return true if the specified indexed load is legal on this target.
543 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
544 return VT.isSimple() &&
545 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
546 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
549 /// Return how the indexed store should be treated: either it is legal, needs
550 /// to be promoted to a larger size, needs to be expanded to some other code
551 /// sequence, or the target has a custom expander for it.
553 getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
554 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT < MVT::LAST_VALUETYPE &&
555 "Table isn't big enough!");
556 unsigned Ty = (unsigned)VT.SimpleTy;
557 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
560 /// Return true if the specified indexed load is legal on this target.
561 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
562 return VT.isSimple() &&
563 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
564 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
567 /// Return how the condition code should be treated: either it is legal, needs
568 /// to be expanded to some other code sequence, or the target has a custom
571 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
572 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
573 ((unsigned)VT.SimpleTy >> 4) < array_lengthof(CondCodeActions[0]) &&
574 "Table isn't big enough!");
575 // See setCondCodeAction for how this is encoded.
576 uint32_t Shift = 2 * (VT.SimpleTy & 0xF);
577 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 4];
578 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0x3);
579 assert(Action != Promote && "Can't promote condition code!");
583 /// Return true if the specified condition code is legal on this target.
584 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
586 getCondCodeAction(CC, VT) == Legal ||
587 getCondCodeAction(CC, VT) == Custom;
591 /// If the action for this operation is to promote, this method returns the
592 /// ValueType to promote to.
593 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
594 assert(getOperationAction(Op, VT) == Promote &&
595 "This operation isn't promoted!");
597 // See if this has an explicit type specified.
598 std::map<std::pair<unsigned, MVT::SimpleValueType>,
599 MVT::SimpleValueType>::const_iterator PTTI =
600 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
601 if (PTTI != PromoteToType.end()) return PTTI->second;
603 assert((VT.isInteger() || VT.isFloatingPoint()) &&
604 "Cannot autopromote this type, add it with AddPromotedToType.");
608 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
609 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
610 "Didn't find type to promote to!");
611 } while (!isTypeLegal(NVT) ||
612 getOperationAction(Op, NVT) == Promote);
616 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
617 /// operations except for the pointer size. If AllowUnknown is true, this
618 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
619 /// otherwise it will assert.
620 EVT getValueType(Type *Ty, bool AllowUnknown = false) const {
621 // Lower scalar pointers to native pointer types.
622 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
623 return getPointerTy(PTy->getAddressSpace());
625 if (Ty->isVectorTy()) {
626 VectorType *VTy = cast<VectorType>(Ty);
627 Type *Elm = VTy->getElementType();
628 // Lower vectors of pointers to native pointer types.
629 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
630 EVT PointerTy(getPointerTy(PT->getAddressSpace()));
631 Elm = PointerTy.getTypeForEVT(Ty->getContext());
634 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
635 VTy->getNumElements());
637 return EVT::getEVT(Ty, AllowUnknown);
640 /// Return the MVT corresponding to this LLVM type. See getValueType.
641 MVT getSimpleValueType(Type *Ty, bool AllowUnknown = false) const {
642 return getValueType(Ty, AllowUnknown).getSimpleVT();
645 /// Return the desired alignment for ByVal or InAlloca aggregate function
646 /// arguments in the caller parameter area. This is the actual alignment, not
648 virtual unsigned getByValTypeAlignment(Type *Ty) const;
650 /// Return the type of registers that this ValueType will eventually require.
651 MVT getRegisterType(MVT VT) const {
652 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
653 return RegisterTypeForVT[VT.SimpleTy];
656 /// Return the type of registers that this ValueType will eventually require.
657 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
659 assert((unsigned)VT.getSimpleVT().SimpleTy <
660 array_lengthof(RegisterTypeForVT));
661 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
666 unsigned NumIntermediates;
667 (void)getVectorTypeBreakdown(Context, VT, VT1,
668 NumIntermediates, RegisterVT);
671 if (VT.isInteger()) {
672 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
674 llvm_unreachable("Unsupported extended type!");
677 /// Return the number of registers that this ValueType will eventually
680 /// This is one for any types promoted to live in larger registers, but may be
681 /// more than one for types (like i64) that are split into pieces. For types
682 /// like i140, which are first promoted then expanded, it is the number of
683 /// registers needed to hold all the bits of the original type. For an i140
684 /// on a 32 bit machine this means 5 registers.
685 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
687 assert((unsigned)VT.getSimpleVT().SimpleTy <
688 array_lengthof(NumRegistersForVT));
689 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
694 unsigned NumIntermediates;
695 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
697 if (VT.isInteger()) {
698 unsigned BitWidth = VT.getSizeInBits();
699 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
700 return (BitWidth + RegWidth - 1) / RegWidth;
702 llvm_unreachable("Unsupported extended type!");
705 /// If true, then instruction selection should seek to shrink the FP constant
706 /// of the specified type to a smaller type in order to save space and / or
708 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
710 /// If true, the target has custom DAG combine transformations that it can
711 /// perform for the specified node.
712 bool hasTargetDAGCombine(ISD::NodeType NT) const {
713 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
714 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
717 /// \brief Get maximum # of store operations permitted for llvm.memset
719 /// This function returns the maximum number of store operations permitted
720 /// to replace a call to llvm.memset. The value is set by the target at the
721 /// performance threshold for such a replacement. If OptSize is true,
722 /// return the limit for functions that have OptSize attribute.
723 unsigned getMaxStoresPerMemset(bool OptSize) const {
724 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
727 /// \brief Get maximum # of store operations permitted for llvm.memcpy
729 /// This function returns the maximum number of store operations permitted
730 /// to replace a call to llvm.memcpy. The value is set by the target at the
731 /// performance threshold for such a replacement. If OptSize is true,
732 /// return the limit for functions that have OptSize attribute.
733 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
734 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
737 /// \brief Get maximum # of store operations permitted for llvm.memmove
739 /// This function returns the maximum number of store operations permitted
740 /// to replace a call to llvm.memmove. The value is set by the target at the
741 /// performance threshold for such a replacement. If OptSize is true,
742 /// return the limit for functions that have OptSize attribute.
743 unsigned getMaxStoresPerMemmove(bool OptSize) const {
744 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
747 /// \brief Determine if the target supports unaligned memory accesses.
749 /// This function returns true if the target allows unaligned memory accesses
750 /// of the specified type in the given address space. If true, it also returns
751 /// whether the unaligned memory access is "fast" in the third argument by
752 /// reference. This is used, for example, in situations where an array
753 /// copy/move/set is converted to a sequence of store operations. Its use
754 /// helps to ensure that such replacements don't generate code that causes an
755 /// alignment error (trap) on the target machine.
756 virtual bool allowsUnalignedMemoryAccesses(EVT,
757 unsigned AddrSpace = 0,
758 bool * /*Fast*/ = 0) const {
762 /// Returns the target specific optimal type for load and store operations as
763 /// a result of memset, memcpy, and memmove lowering.
765 /// If DstAlign is zero that means it's safe to destination alignment can
766 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
767 /// a need to check it against alignment requirement, probably because the
768 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
769 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
770 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
771 /// does not need to be loaded. It returns EVT::Other if the type should be
772 /// determined using generic target-independent logic.
773 virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
774 unsigned /*DstAlign*/, unsigned /*SrcAlign*/,
777 bool /*MemcpyStrSrc*/,
778 MachineFunction &/*MF*/) const {
782 /// Returns true if it's safe to use load / store of the specified type to
783 /// expand memcpy / memset inline.
785 /// This is mostly true for all types except for some special cases. For
786 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
787 /// fstpl which also does type conversion. Note the specified type doesn't
788 /// have to be legal as the hook is used before type legalization.
789 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
791 /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
792 bool usesUnderscoreSetJmp() const {
793 return UseUnderscoreSetJmp;
796 /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
797 bool usesUnderscoreLongJmp() const {
798 return UseUnderscoreLongJmp;
801 /// Return whether the target can generate code for jump tables.
802 bool supportJumpTables() const {
803 return SupportJumpTables;
806 /// Return integer threshold on number of blocks to use jump tables rather
807 /// than if sequence.
808 int getMinimumJumpTableEntries() const {
809 return MinimumJumpTableEntries;
812 /// If a physical register, this specifies the register that
813 /// llvm.savestack/llvm.restorestack should save and restore.
814 unsigned getStackPointerRegisterToSaveRestore() const {
815 return StackPointerRegisterToSaveRestore;
818 /// If a physical register, this returns the register that receives the
819 /// exception address on entry to a landing pad.
820 unsigned getExceptionPointerRegister() const {
821 return ExceptionPointerRegister;
824 /// If a physical register, this returns the register that receives the
825 /// exception typeid on entry to a landing pad.
826 unsigned getExceptionSelectorRegister() const {
827 return ExceptionSelectorRegister;
830 /// Returns the target's jmp_buf size in bytes (if never set, the default is
832 unsigned getJumpBufSize() const {
836 /// Returns the target's jmp_buf alignment in bytes (if never set, the default
838 unsigned getJumpBufAlignment() const {
839 return JumpBufAlignment;
842 /// Return the minimum stack alignment of an argument.
843 unsigned getMinStackArgumentAlignment() const {
844 return MinStackArgumentAlignment;
847 /// Return the minimum function alignment.
848 unsigned getMinFunctionAlignment() const {
849 return MinFunctionAlignment;
852 /// Return the preferred function alignment.
853 unsigned getPrefFunctionAlignment() const {
854 return PrefFunctionAlignment;
857 /// Return the preferred loop alignment.
858 unsigned getPrefLoopAlignment() const {
859 return PrefLoopAlignment;
862 /// Return whether the DAG builder should automatically insert fences and
863 /// reduce ordering for atomics.
864 bool getInsertFencesForAtomic() const {
865 return InsertFencesForAtomic;
868 /// Return true if the target stores stack protector cookies at a fixed offset
869 /// in some non-standard address space, and populates the address space and
870 /// offset as appropriate.
871 virtual bool getStackCookieLocation(unsigned &/*AddressSpace*/,
872 unsigned &/*Offset*/) const {
876 /// Returns the maximal possible offset which can be used for loads / stores
878 virtual unsigned getMaximalGlobalOffset() const {
882 /// Returns true if a cast between SrcAS and DestAS is a noop.
883 virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
887 //===--------------------------------------------------------------------===//
888 /// \name Helpers for TargetTransformInfo implementations
891 /// Get the ISD node that corresponds to the Instruction class opcode.
892 int InstructionOpcodeToISD(unsigned Opcode) const;
894 /// Estimate the cost of type-legalization and the legalized type.
895 std::pair<unsigned, MVT> getTypeLegalizationCost(Type *Ty) const;
899 //===--------------------------------------------------------------------===//
900 // TargetLowering Configuration Methods - These methods should be invoked by
901 // the derived class constructor to configure this object for the target.
904 /// \brief Reset the operation actions based on target options.
905 virtual void resetOperationActions() {}
908 /// Specify how the target extends the result of a boolean value from i1 to a
909 /// wider type. See getBooleanContents.
910 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; }
912 /// Specify how the target extends the result of a vector boolean value from a
913 /// vector of i1 to a wider type. See getBooleanContents.
914 void setBooleanVectorContents(BooleanContent Ty) {
915 BooleanVectorContents = Ty;
918 /// Specify the target scheduling preference.
919 void setSchedulingPreference(Sched::Preference Pref) {
920 SchedPreferenceInfo = Pref;
923 /// Indicate whether this target prefers to use _setjmp to implement
924 /// llvm.setjmp or the version without _. Defaults to false.
925 void setUseUnderscoreSetJmp(bool Val) {
926 UseUnderscoreSetJmp = Val;
929 /// Indicate whether this target prefers to use _longjmp to implement
930 /// llvm.longjmp or the version without _. Defaults to false.
931 void setUseUnderscoreLongJmp(bool Val) {
932 UseUnderscoreLongJmp = Val;
935 /// Indicate whether the target can generate code for jump tables.
936 void setSupportJumpTables(bool Val) {
937 SupportJumpTables = Val;
940 /// Indicate the number of blocks to generate jump tables rather than if
942 void setMinimumJumpTableEntries(int Val) {
943 MinimumJumpTableEntries = Val;
946 /// If set to a physical register, this specifies the register that
947 /// llvm.savestack/llvm.restorestack should save and restore.
948 void setStackPointerRegisterToSaveRestore(unsigned R) {
949 StackPointerRegisterToSaveRestore = R;
952 /// If set to a physical register, this sets the register that receives the
953 /// exception address on entry to a landing pad.
954 void setExceptionPointerRegister(unsigned R) {
955 ExceptionPointerRegister = R;
958 /// If set to a physical register, this sets the register that receives the
959 /// exception typeid on entry to a landing pad.
960 void setExceptionSelectorRegister(unsigned R) {
961 ExceptionSelectorRegister = R;
964 /// Tells the code generator not to expand operations into sequences that use
965 /// the select operations if possible.
966 void setSelectIsExpensive(bool isExpensive = true) {
967 SelectIsExpensive = isExpensive;
970 /// Tells the code generator that the target has multiple (allocatable)
971 /// condition registers that can be used to store the results of comparisons
972 /// for use by selects and conditional branches. With multiple condition
973 /// registers, the code generator will not aggressively sink comparisons into
974 /// the blocks of their users.
975 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
976 HasMultipleConditionRegisters = hasManyRegs;
979 /// Tells the code generator not to expand sequence of operations into a
980 /// separate sequences that increases the amount of flow control.
981 void setJumpIsExpensive(bool isExpensive = true) {
982 JumpIsExpensive = isExpensive;
985 /// Tells the code generator that integer divide is expensive, and if
986 /// possible, should be replaced by an alternate sequence of instructions not
987 /// containing an integer divide.
988 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; }
990 /// Tells the code generator which bitwidths to bypass.
991 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
992 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
995 /// Tells the code generator that it shouldn't generate srl/add/sra for a
996 /// signed divide by power of two, and let the target handle it.
997 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; }
999 /// Add the specified register class as an available regclass for the
1000 /// specified value type. This indicates the selector can handle values of
1001 /// that class natively.
1002 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
1003 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
1004 AvailableRegClasses.push_back(std::make_pair(VT, RC));
1005 RegClassForVT[VT.SimpleTy] = RC;
1008 /// Remove all register classes.
1009 void clearRegisterClasses() {
1010 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE * sizeof(TargetRegisterClass*));
1012 AvailableRegClasses.clear();
1015 /// \brief Remove all operation actions.
1016 void clearOperationActions() {
1019 /// Return the largest legal super-reg register class of the register class
1020 /// for the specified type and its associated "cost".
1021 virtual std::pair<const TargetRegisterClass*, uint8_t>
1022 findRepresentativeClass(MVT VT) const;
1024 /// Once all of the register classes are added, this allows us to compute
1025 /// derived properties we expose.
1026 void computeRegisterProperties();
1028 /// Indicate that the specified operation does not work with the specified
1029 /// type and indicate what to do about it.
1030 void setOperationAction(unsigned Op, MVT VT,
1031 LegalizeAction Action) {
1032 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1033 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action;
1036 /// Indicate that the specified load with extension does not work with the
1037 /// specified type and indicate what to do about it.
1038 void setLoadExtAction(unsigned ExtType, MVT VT,
1039 LegalizeAction Action) {
1040 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE &&
1041 "Table isn't big enough!");
1042 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action;
1045 /// Indicate that the specified truncating store does not work with the
1046 /// specified type and indicate what to do about it.
1047 void setTruncStoreAction(MVT ValVT, MVT MemVT,
1048 LegalizeAction Action) {
1049 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE &&
1050 "Table isn't big enough!");
1051 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action;
1054 /// Indicate that the specified indexed load does or does not work with the
1055 /// specified type and indicate what to do abort it.
1057 /// NOTE: All indexed mode loads are initialized to Expand in
1058 /// TargetLowering.cpp
1059 void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1060 LegalizeAction Action) {
1061 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1062 (unsigned)Action < 0xf && "Table isn't big enough!");
1063 // Load action are kept in the upper half.
1064 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
1065 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
1068 /// Indicate that the specified indexed store does or does not work with the
1069 /// specified type and indicate what to do about it.
1071 /// NOTE: All indexed mode stores are initialized to Expand in
1072 /// TargetLowering.cpp
1073 void setIndexedStoreAction(unsigned IdxMode, MVT VT,
1074 LegalizeAction Action) {
1075 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE &&
1076 (unsigned)Action < 0xf && "Table isn't big enough!");
1077 // Store action are kept in the lower half.
1078 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
1079 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
1082 /// Indicate that the specified condition code is or isn't supported on the
1083 /// target and indicate what to do about it.
1084 void setCondCodeAction(ISD::CondCode CC, MVT VT,
1085 LegalizeAction Action) {
1086 assert(VT < MVT::LAST_VALUETYPE &&
1087 (unsigned)CC < array_lengthof(CondCodeActions) &&
1088 "Table isn't big enough!");
1089 /// The lower 5 bits of the SimpleTy index into Nth 2bit set from the 32-bit
1090 /// value and the upper 27 bits index into the second dimension of the array
1091 /// to select what 32-bit value to use.
1092 uint32_t Shift = 2 * (VT.SimpleTy & 0xF);
1093 CondCodeActions[CC][VT.SimpleTy >> 4] &= ~((uint32_t)0x3 << Shift);
1094 CondCodeActions[CC][VT.SimpleTy >> 4] |= (uint32_t)Action << Shift;
1097 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
1098 /// to trying a larger integer/fp until it can find one that works. If that
1099 /// default is insufficient, this method can be used by the target to override
1101 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
1102 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
1105 /// Targets should invoke this method for each target independent node that
1106 /// they want to provide a custom DAG combiner for by implementing the
1107 /// PerformDAGCombine virtual method.
1108 void setTargetDAGCombine(ISD::NodeType NT) {
1109 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1110 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
1113 /// Set the target's required jmp_buf buffer size (in bytes); default is 200
1114 void setJumpBufSize(unsigned Size) {
1118 /// Set the target's required jmp_buf buffer alignment (in bytes); default is
1120 void setJumpBufAlignment(unsigned Align) {
1121 JumpBufAlignment = Align;
1124 /// Set the target's minimum function alignment (in log2(bytes))
1125 void setMinFunctionAlignment(unsigned Align) {
1126 MinFunctionAlignment = Align;
1129 /// Set the target's preferred function alignment. This should be set if
1130 /// there is a performance benefit to higher-than-minimum alignment (in
1132 void setPrefFunctionAlignment(unsigned Align) {
1133 PrefFunctionAlignment = Align;
1136 /// Set the target's preferred loop alignment. Default alignment is zero, it
1137 /// means the target does not care about loop alignment. The alignment is
1138 /// specified in log2(bytes).
1139 void setPrefLoopAlignment(unsigned Align) {
1140 PrefLoopAlignment = Align;
1143 /// Set the minimum stack alignment of an argument (in log2(bytes)).
1144 void setMinStackArgumentAlignment(unsigned Align) {
1145 MinStackArgumentAlignment = Align;
1148 /// Set if the DAG builder should automatically insert fences and reduce the
1149 /// order of atomic memory operations to Monotonic.
1150 void setInsertFencesForAtomic(bool fence) {
1151 InsertFencesForAtomic = fence;
1155 //===--------------------------------------------------------------------===//
1156 // Addressing mode description hooks (used by LSR etc).
1159 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
1160 /// instructions reading the address. This allows as much computation as
1161 /// possible to be done in the address mode for that operand. This hook lets
1162 /// targets also pass back when this should be done on intrinsics which
1164 virtual bool GetAddrModeArguments(IntrinsicInst * /*I*/,
1165 SmallVectorImpl<Value*> &/*Ops*/,
1166 Type *&/*AccessTy*/) const {
1170 /// This represents an addressing mode of:
1171 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
1172 /// If BaseGV is null, there is no BaseGV.
1173 /// If BaseOffs is zero, there is no base offset.
1174 /// If HasBaseReg is false, there is no base register.
1175 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
1178 GlobalValue *BaseGV;
1182 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
1185 /// Return true if the addressing mode represented by AM is legal for this
1186 /// target, for a load/store of the specified type.
1188 /// The type may be VoidTy, in which case only return true if the addressing
1189 /// mode is legal for a load/store of any legal type. TODO: Handle
1190 /// pre/postinc as well.
1191 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const;
1193 /// \brief Return the cost of the scaling factor used in the addressing mode
1194 /// represented by AM for this target, for a load/store of the specified type.
1196 /// If the AM is supported, the return value must be >= 0.
1197 /// If the AM is not supported, it returns a negative value.
1198 /// TODO: Handle pre/postinc as well.
1199 virtual int getScalingFactorCost(const AddrMode &AM, Type *Ty) const {
1200 // Default: assume that any scaling factor used in a legal AM is free.
1201 if (isLegalAddressingMode(AM, Ty)) return 0;
1205 /// Return true if the specified immediate is legal icmp immediate, that is
1206 /// the target has icmp instructions which can compare a register against the
1207 /// immediate without having to materialize the immediate into a register.
1208 virtual bool isLegalICmpImmediate(int64_t) const {
1212 /// Return true if the specified immediate is legal add immediate, that is the
1213 /// target has add instructions which can add a register with the immediate
1214 /// without having to materialize the immediate into a register.
1215 virtual bool isLegalAddImmediate(int64_t) const {
1219 /// Return true if it's significantly cheaper to shift a vector by a uniform
1220 /// scalar than by an amount which will vary across each lane. On x86, for
1221 /// example, there is a "psllw" instruction for the former case, but no simple
1222 /// instruction for a general "a << b" operation on vectors.
1223 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
1227 /// Return true if it's free to truncate a value of type Ty1 to type
1228 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1229 /// by referencing its sub-register AX.
1230 virtual bool isTruncateFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1234 /// Return true if a truncation from Ty1 to Ty2 is permitted when deciding
1235 /// whether a call is in tail position. Typically this means that both results
1236 /// would be assigned to the same register or stack slot, but it could mean
1237 /// the target performs adequate checks of its own before proceeding with the
1239 virtual bool allowTruncateForTailCall(Type * /*Ty1*/, Type * /*Ty2*/) const {
1243 virtual bool isTruncateFree(EVT /*VT1*/, EVT /*VT2*/) const {
1247 /// Return true if any actual instruction that defines a value of type Ty1
1248 /// implicitly zero-extends the value to Ty2 in the result register.
1250 /// This does not necessarily include registers defined in unknown ways, such
1251 /// as incoming arguments, or copies from unknown virtual registers. Also, if
1252 /// isTruncateFree(Ty2, Ty1) is true, this does not necessarily apply to
1253 /// truncate instructions. e.g. on x86-64, all instructions that define 32-bit
1254 /// values implicit zero-extend the result out to 64 bits.
1255 virtual bool isZExtFree(Type * /*Ty1*/, Type * /*Ty2*/) const {
1259 virtual bool isZExtFree(EVT /*VT1*/, EVT /*VT2*/) const {
1263 /// Return true if the target supplies and combines to a paired load
1264 /// two loaded values of type LoadedType next to each other in memory.
1265 /// RequiredAlignment gives the minimal alignment constraints that must be met
1266 /// to be able to select this paired load.
1268 /// This information is *not* used to generate actual paired loads, but it is
1269 /// used to generate a sequence of loads that is easier to combine into a
1271 /// For instance, something like this:
1272 /// a = load i64* addr
1273 /// b = trunc i64 a to i32
1274 /// c = lshr i64 a, 32
1275 /// d = trunc i64 c to i32
1276 /// will be optimized into:
1277 /// b = load i32* addr1
1278 /// d = load i32* addr2
1279 /// Where addr1 = addr2 +/- sizeof(i32).
1281 /// In other words, unless the target performs a post-isel load combining,
1282 /// this information should not be provided because it will generate more
1284 virtual bool hasPairedLoad(Type * /*LoadedType*/,
1285 unsigned & /*RequiredAligment*/) const {
1289 virtual bool hasPairedLoad(EVT /*LoadedType*/,
1290 unsigned & /*RequiredAligment*/) const {
1294 /// Return true if zero-extending the specific node Val to type VT2 is free
1295 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
1296 /// because it's folded such as X86 zero-extending loads).
1297 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
1298 return isZExtFree(Val.getValueType(), VT2);
1301 /// Return true if an fneg operation is free to the point where it is never
1302 /// worthwhile to replace it with a bitwise operation.
1303 virtual bool isFNegFree(EVT VT) const {
1304 assert(VT.isFloatingPoint());
1308 /// Return true if an fabs operation is free to the point where it is never
1309 /// worthwhile to replace it with a bitwise operation.
1310 virtual bool isFAbsFree(EVT VT) const {
1311 assert(VT.isFloatingPoint());
1315 /// Return true if an FMA operation is faster than a pair of fmul and fadd
1316 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
1317 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
1319 /// NOTE: This may be called before legalization on types for which FMAs are
1320 /// not legal, but should return true if those types will eventually legalize
1321 /// to types that support FMAs. After legalization, it will only be called on
1322 /// types that support FMAs (via Legal or Custom actions)
1323 virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
1327 /// Return true if it's profitable to narrow operations of type VT1 to
1328 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
1330 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
1334 /// \brief Return true if it is beneficial to convert a load of a constant to
1335 /// just the constant itself.
1336 /// On some targets it might be more efficient to use a combination of
1337 /// arithmetic instructions to materialize the constant instead of loading it
1338 /// from a constant pool.
1339 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
1343 //===--------------------------------------------------------------------===//
1344 // Runtime Library hooks
1347 /// Rename the default libcall routine name for the specified libcall.
1348 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
1349 LibcallRoutineNames[Call] = Name;
1352 /// Get the libcall routine name for the specified libcall.
1353 const char *getLibcallName(RTLIB::Libcall Call) const {
1354 return LibcallRoutineNames[Call];
1357 /// Override the default CondCode to be used to test the result of the
1358 /// comparison libcall against zero.
1359 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
1360 CmpLibcallCCs[Call] = CC;
1363 /// Get the CondCode that's to be used to test the result of the comparison
1364 /// libcall against zero.
1365 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
1366 return CmpLibcallCCs[Call];
1369 /// Set the CallingConv that should be used for the specified libcall.
1370 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
1371 LibcallCallingConvs[Call] = CC;
1374 /// Get the CallingConv that should be used for the specified libcall.
1375 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
1376 return LibcallCallingConvs[Call];
1380 const TargetMachine &TM;
1381 const DataLayout *DL;
1382 const TargetLoweringObjectFile &TLOF;
1384 /// True if this is a little endian target.
1385 bool IsLittleEndian;
1387 /// Tells the code generator not to expand operations into sequences that use
1388 /// the select operations if possible.
1389 bool SelectIsExpensive;
1391 /// Tells the code generator that the target has multiple (allocatable)
1392 /// condition registers that can be used to store the results of comparisons
1393 /// for use by selects and conditional branches. With multiple condition
1394 /// registers, the code generator will not aggressively sink comparisons into
1395 /// the blocks of their users.
1396 bool HasMultipleConditionRegisters;
1398 /// Tells the code generator not to expand integer divides by constants into a
1399 /// sequence of muls, adds, and shifts. This is a hack until a real cost
1400 /// model is in place. If we ever optimize for size, this will be set to true
1401 /// unconditionally.
1404 /// Tells the code generator to bypass slow divide or remainder
1405 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
1406 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
1407 /// div/rem when the operands are positive and less than 256.
1408 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
1410 /// Tells the code generator that it shouldn't generate srl/add/sra for a
1411 /// signed divide by power of two, and let the target handle it.
1412 bool Pow2DivIsCheap;
1414 /// Tells the code generator that it shouldn't generate extra flow control
1415 /// instructions and should attempt to combine flow control instructions via
1417 bool JumpIsExpensive;
1419 /// This target prefers to use _setjmp to implement llvm.setjmp.
1421 /// Defaults to false.
1422 bool UseUnderscoreSetJmp;
1424 /// This target prefers to use _longjmp to implement llvm.longjmp.
1426 /// Defaults to false.
1427 bool UseUnderscoreLongJmp;
1429 /// Whether the target can generate code for jumptables. If it's not true,
1430 /// then each jumptable must be lowered into if-then-else's.
1431 bool SupportJumpTables;
1433 /// Number of blocks threshold to use jump tables.
1434 int MinimumJumpTableEntries;
1436 /// Information about the contents of the high-bits in boolean values held in
1437 /// a type wider than i1. See getBooleanContents.
1438 BooleanContent BooleanContents;
1440 /// Information about the contents of the high-bits in boolean vector values
1441 /// when the element type is wider than i1. See getBooleanContents.
1442 BooleanContent BooleanVectorContents;
1444 /// The target scheduling preference: shortest possible total cycles or lowest
1446 Sched::Preference SchedPreferenceInfo;
1448 /// The size, in bytes, of the target's jmp_buf buffers
1449 unsigned JumpBufSize;
1451 /// The alignment, in bytes, of the target's jmp_buf buffers
1452 unsigned JumpBufAlignment;
1454 /// The minimum alignment that any argument on the stack needs to have.
1455 unsigned MinStackArgumentAlignment;
1457 /// The minimum function alignment (used when optimizing for size, and to
1458 /// prevent explicitly provided alignment from leading to incorrect code).
1459 unsigned MinFunctionAlignment;
1461 /// The preferred function alignment (used when alignment unspecified and
1462 /// optimizing for speed).
1463 unsigned PrefFunctionAlignment;
1465 /// The preferred loop alignment.
1466 unsigned PrefLoopAlignment;
1468 /// Whether the DAG builder should automatically insert fences and reduce
1469 /// ordering for atomics. (This will be set for for most architectures with
1470 /// weak memory ordering.)
1471 bool InsertFencesForAtomic;
1473 /// If set to a physical register, this specifies the register that
1474 /// llvm.savestack/llvm.restorestack should save and restore.
1475 unsigned StackPointerRegisterToSaveRestore;
1477 /// If set to a physical register, this specifies the register that receives
1478 /// the exception address on entry to a landing pad.
1479 unsigned ExceptionPointerRegister;
1481 /// If set to a physical register, this specifies the register that receives
1482 /// the exception typeid on entry to a landing pad.
1483 unsigned ExceptionSelectorRegister;
1485 /// This indicates the default register class to use for each ValueType the
1486 /// target supports natively.
1487 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
1488 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
1489 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
1491 /// This indicates the "representative" register class to use for each
1492 /// ValueType the target supports natively. This information is used by the
1493 /// scheduler to track register pressure. By default, the representative
1494 /// register class is the largest legal super-reg register class of the
1495 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
1496 /// representative class would be GR32.
1497 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
1499 /// This indicates the "cost" of the "representative" register class for each
1500 /// ValueType. The cost is used by the scheduler to approximate register
1502 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
1504 /// For any value types we are promoting or expanding, this contains the value
1505 /// type that we are changing to. For Expanded types, this contains one step
1506 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
1507 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
1508 /// the same type (e.g. i32 -> i32).
1509 MVT TransformToType[MVT::LAST_VALUETYPE];
1511 /// For each operation and each value type, keep a LegalizeAction that
1512 /// indicates how instruction selection should deal with the operation. Most
1513 /// operations are Legal (aka, supported natively by the target), but
1514 /// operations that are not should be described. Note that operations on
1515 /// non-legal value types are not described here.
1516 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
1518 /// For each load extension type and each value type, keep a LegalizeAction
1519 /// that indicates how instruction selection should deal with a load of a
1520 /// specific value type and extension type.
1521 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE];
1523 /// For each value type pair keep a LegalizeAction that indicates whether a
1524 /// truncating store of a specific value type and truncating type is legal.
1525 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
1527 /// For each indexed mode and each value type, keep a pair of LegalizeAction
1528 /// that indicates how instruction selection should deal with the load /
1531 /// The first dimension is the value_type for the reference. The second
1532 /// dimension represents the various modes for load store.
1533 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
1535 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
1536 /// indicates how instruction selection should deal with the condition code.
1538 /// Because each CC action takes up 2 bits, we need to have the array size be
1539 /// large enough to fit all of the value types. This can be done by rounding
1540 /// up the MVT::LAST_VALUETYPE value to the next multiple of 16.
1541 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 15) / 16];
1543 ValueTypeActionImpl ValueTypeActions;
1547 getTypeConversion(LLVMContext &Context, EVT VT) const {
1548 // If this is a simple type, use the ComputeRegisterProp mechanism.
1549 if (VT.isSimple()) {
1550 MVT SVT = VT.getSimpleVT();
1551 assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
1552 MVT NVT = TransformToType[SVT.SimpleTy];
1553 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1557 ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)
1558 && "Promote may not follow Expand or Promote");
1560 if (LA == TypeSplitVector)
1561 return LegalizeKind(LA, EVT::getVectorVT(Context,
1562 SVT.getVectorElementType(),
1563 SVT.getVectorNumElements()/2));
1564 if (LA == TypeScalarizeVector)
1565 return LegalizeKind(LA, SVT.getVectorElementType());
1566 return LegalizeKind(LA, NVT);
1569 // Handle Extended Scalar Types.
1570 if (!VT.isVector()) {
1571 assert(VT.isInteger() && "Float types must be simple");
1572 unsigned BitSize = VT.getSizeInBits();
1573 // First promote to a power-of-two size, then expand if necessary.
1574 if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1575 EVT NVT = VT.getRoundIntegerType(Context);
1576 assert(NVT != VT && "Unable to round integer VT");
1577 LegalizeKind NextStep = getTypeConversion(Context, NVT);
1578 // Avoid multi-step promotion.
1579 if (NextStep.first == TypePromoteInteger) return NextStep;
1580 // Return rounded integer type.
1581 return LegalizeKind(TypePromoteInteger, NVT);
1584 return LegalizeKind(TypeExpandInteger,
1585 EVT::getIntegerVT(Context, VT.getSizeInBits()/2));
1588 // Handle vector types.
1589 unsigned NumElts = VT.getVectorNumElements();
1590 EVT EltVT = VT.getVectorElementType();
1592 // Vectors with only one element are always scalarized.
1594 return LegalizeKind(TypeScalarizeVector, EltVT);
1596 // Try to widen vector elements until the element type is a power of two and
1597 // promote it to a legal type later on, for example:
1598 // <3 x i8> -> <4 x i8> -> <4 x i32>
1599 if (EltVT.isInteger()) {
1600 // Vectors with a number of elements that is not a power of two are always
1601 // widened, for example <3 x i8> -> <4 x i8>.
1602 if (!VT.isPow2VectorType()) {
1603 NumElts = (unsigned)NextPowerOf2(NumElts);
1604 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1605 return LegalizeKind(TypeWidenVector, NVT);
1608 // Examine the element type.
1609 LegalizeKind LK = getTypeConversion(Context, EltVT);
1611 // If type is to be expanded, split the vector.
1612 // <4 x i140> -> <2 x i140>
1613 if (LK.first == TypeExpandInteger)
1614 return LegalizeKind(TypeSplitVector,
1615 EVT::getVectorVT(Context, EltVT, NumElts / 2));
1617 // Promote the integer element types until a legal vector type is found
1618 // or until the element integer type is too big. If a legal type was not
1619 // found, fallback to the usual mechanism of widening/splitting the
1621 EVT OldEltVT = EltVT;
1623 // Increase the bitwidth of the element to the next pow-of-two
1624 // (which is greater than 8 bits).
1625 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits()
1626 ).getRoundIntegerType(Context);
1628 // Stop trying when getting a non-simple element type.
1629 // Note that vector elements may be greater than legal vector element
1630 // types. Example: X86 XMM registers hold 64bit element on 32bit
1632 if (!EltVT.isSimple()) break;
1634 // Build a new vector type and check if it is legal.
1635 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1636 // Found a legal promoted vector type.
1637 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1638 return LegalizeKind(TypePromoteInteger,
1639 EVT::getVectorVT(Context, EltVT, NumElts));
1642 // Reset the type to the unexpanded type if we did not find a legal vector
1643 // type with a promoted vector element type.
1647 // Try to widen the vector until a legal type is found.
1648 // If there is no wider legal type, split the vector.
1650 // Round up to the next power of 2.
1651 NumElts = (unsigned)NextPowerOf2(NumElts);
1653 // If there is no simple vector type with this many elements then there
1654 // cannot be a larger legal vector type. Note that this assumes that
1655 // there are no skipped intermediate vector types in the simple types.
1656 if (!EltVT.isSimple()) break;
1657 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1658 if (LargerVector == MVT()) break;
1660 // If this type is legal then widen the vector.
1661 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1662 return LegalizeKind(TypeWidenVector, LargerVector);
1665 // Widen odd vectors to next power of two.
1666 if (!VT.isPow2VectorType()) {
1667 EVT NVT = VT.getPow2VectorType(Context);
1668 return LegalizeKind(TypeWidenVector, NVT);
1671 // Vectors with illegal element types are expanded.
1672 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1673 return LegalizeKind(TypeSplitVector, NVT);
1677 std::vector<std::pair<MVT, const TargetRegisterClass*> > AvailableRegClasses;
1679 /// Targets can specify ISD nodes that they would like PerformDAGCombine
1680 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
1683 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
1685 /// For operations that must be promoted to a specific type, this holds the
1686 /// destination type. This map should be sparse, so don't hold it as an
1689 /// Targets add entries to this map with AddPromotedToType(..), clients access
1690 /// this with getTypeToPromoteTo(..).
1691 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
1694 /// Stores the name each libcall.
1695 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL];
1697 /// The ISD::CondCode that should be used to test the result of each of the
1698 /// comparison libcall against zero.
1699 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
1701 /// Stores the CallingConv that should be used for each libcall.
1702 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
1705 /// \brief Specify maximum number of store instructions per memset call.
1707 /// When lowering \@llvm.memset this field specifies the maximum number of
1708 /// store operations that may be substituted for the call to memset. Targets
1709 /// must set this value based on the cost threshold for that target. Targets
1710 /// should assume that the memset will be done using as many of the largest
1711 /// store operations first, followed by smaller ones, if necessary, per
1712 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
1713 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
1714 /// store. This only applies to setting a constant array of a constant size.
1715 unsigned MaxStoresPerMemset;
1717 /// Maximum number of stores operations that may be substituted for the call
1718 /// to memset, used for functions with OptSize attribute.
1719 unsigned MaxStoresPerMemsetOptSize;
1721 /// \brief Specify maximum bytes of store instructions per memcpy call.
1723 /// When lowering \@llvm.memcpy this field specifies the maximum number of
1724 /// store operations that may be substituted for a call to memcpy. Targets
1725 /// must set this value based on the cost threshold for that target. Targets
1726 /// should assume that the memcpy will be done using as many of the largest
1727 /// store operations first, followed by smaller ones, if necessary, per
1728 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
1729 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
1730 /// and one 1-byte store. This only applies to copying a constant array of
1732 unsigned MaxStoresPerMemcpy;
1734 /// Maximum number of store operations that may be substituted for a call to
1735 /// memcpy, used for functions with OptSize attribute.
1736 unsigned MaxStoresPerMemcpyOptSize;
1738 /// \brief Specify maximum bytes of store instructions per memmove call.
1740 /// When lowering \@llvm.memmove this field specifies the maximum number of
1741 /// store instructions that may be substituted for a call to memmove. Targets
1742 /// must set this value based on the cost threshold for that target. Targets
1743 /// should assume that the memmove will be done using as many of the largest
1744 /// store operations first, followed by smaller ones, if necessary, per
1745 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
1746 /// with 8-bit alignment would result in nine 1-byte stores. This only
1747 /// applies to copying a constant array of constant size.
1748 unsigned MaxStoresPerMemmove;
1750 /// Maximum number of store instructions that may be substituted for a call to
1751 /// memmove, used for functions with OpSize attribute.
1752 unsigned MaxStoresPerMemmoveOptSize;
1754 /// Tells the code generator that select is more expensive than a branch if
1755 /// the branch is usually predicted right.
1756 bool PredictableSelectIsExpensive;
1758 /// MaskAndBranchFoldingIsLegal - Indicates if the target supports folding
1759 /// a mask of a single bit, a compare, and a branch into a single instruction.
1760 bool MaskAndBranchFoldingIsLegal;
1763 /// Return true if the value types that can be represented by the specified
1764 /// register class are all legal.
1765 bool isLegalRC(const TargetRegisterClass *RC) const;
1767 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1768 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1769 MachineBasicBlock *emitPatchPoint(MachineInstr *MI, MachineBasicBlock *MBB) const;
1772 /// This class defines information used to lower LLVM code to legal SelectionDAG
1773 /// operators that the target instruction selector can accept natively.
1775 /// This class also defines callbacks that targets must implement to lower
1776 /// target-specific constructs to SelectionDAG operators.
1777 class TargetLowering : public TargetLoweringBase {
1778 TargetLowering(const TargetLowering&) LLVM_DELETED_FUNCTION;
1779 void operator=(const TargetLowering&) LLVM_DELETED_FUNCTION;
1782 /// NOTE: The constructor takes ownership of TLOF.
1783 explicit TargetLowering(const TargetMachine &TM,
1784 const TargetLoweringObjectFile *TLOF);
1786 /// Returns true by value, base pointer and offset pointer and addressing mode
1787 /// by reference if the node's address can be legally represented as
1788 /// pre-indexed load / store address.
1789 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
1790 SDValue &/*Offset*/,
1791 ISD::MemIndexedMode &/*AM*/,
1792 SelectionDAG &/*DAG*/) const {
1796 /// Returns true by value, base pointer and offset pointer and addressing mode
1797 /// by reference if this node can be combined with a load / store to form a
1798 /// post-indexed load / store.
1799 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
1801 SDValue &/*Offset*/,
1802 ISD::MemIndexedMode &/*AM*/,
1803 SelectionDAG &/*DAG*/) const {
1807 /// Return the entry encoding for a jump table in the current function. The
1808 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
1809 virtual unsigned getJumpTableEncoding() const;
1811 virtual const MCExpr *
1812 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
1813 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
1814 MCContext &/*Ctx*/) const {
1815 llvm_unreachable("Need to implement this hook if target has custom JTIs");
1818 /// Returns relocation base for the given PIC jumptable.
1819 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
1820 SelectionDAG &DAG) const;
1822 /// This returns the relocation base for the given PIC jumptable, the same as
1823 /// getPICJumpTableRelocBase, but as an MCExpr.
1824 virtual const MCExpr *
1825 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1826 unsigned JTI, MCContext &Ctx) const;
1828 /// Return true if folding a constant offset with the given GlobalAddress is
1829 /// legal. It is frequently not legal in PIC relocation models.
1830 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
1832 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
1833 SDValue &Chain) const;
1835 void softenSetCCOperands(SelectionDAG &DAG, EVT VT,
1836 SDValue &NewLHS, SDValue &NewRHS,
1837 ISD::CondCode &CCCode, SDLoc DL) const;
1839 /// Returns a pair of (return value, chain).
1840 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
1841 EVT RetVT, const SDValue *Ops,
1842 unsigned NumOps, bool isSigned,
1843 SDLoc dl, bool doesNotReturn = false,
1844 bool isReturnValueUsed = true) const;
1846 //===--------------------------------------------------------------------===//
1847 // TargetLowering Optimization Methods
1850 /// A convenience struct that encapsulates a DAG, and two SDValues for
1851 /// returning information from TargetLowering to its clients that want to
1853 struct TargetLoweringOpt {
1860 explicit TargetLoweringOpt(SelectionDAG &InDAG,
1862 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
1864 bool LegalTypes() const { return LegalTys; }
1865 bool LegalOperations() const { return LegalOps; }
1867 bool CombineTo(SDValue O, SDValue N) {
1873 /// Check to see if the specified operand of the specified instruction is a
1874 /// constant integer. If so, check to see if there are any bits set in the
1875 /// constant that are not demanded. If so, shrink the constant and return
1877 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded);
1879 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
1880 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
1881 /// generalized for targets with other types of implicit widening casts.
1882 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
1886 /// Look at Op. At this point, we know that only the DemandedMask bits of the
1887 /// result of Op are ever used downstream. If we can use this information to
1888 /// simplify Op, create a new simplified DAG node and return true, returning
1889 /// the original and new nodes in Old and New. Otherwise, analyze the
1890 /// expression and return a mask of KnownOne and KnownZero bits for the
1891 /// expression (used to simplify the caller). The KnownZero/One bits may only
1892 /// be accurate for those bits in the DemandedMask.
1893 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
1894 APInt &KnownZero, APInt &KnownOne,
1895 TargetLoweringOpt &TLO, unsigned Depth = 0) const;
1897 /// Determine which of the bits specified in Mask are known to be either zero
1898 /// or one and return them in the KnownZero/KnownOne bitsets.
1899 virtual void computeMaskedBitsForTargetNode(const SDValue Op,
1902 const SelectionDAG &DAG,
1903 unsigned Depth = 0) const;
1905 /// This method can be implemented by targets that want to expose additional
1906 /// information about sign bits to the DAG Combiner.
1907 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
1908 unsigned Depth = 0) const;
1910 struct DAGCombinerInfo {
1911 void *DC; // The DAG Combiner object.
1913 bool CalledByLegalizer;
1917 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
1918 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
1920 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
1921 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
1922 bool isAfterLegalizeVectorOps() const {
1923 return Level == AfterLegalizeDAG;
1925 CombineLevel getDAGCombineLevel() { return Level; }
1926 bool isCalledByLegalizer() const { return CalledByLegalizer; }
1928 void AddToWorklist(SDNode *N);
1929 void RemoveFromWorklist(SDNode *N);
1930 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To,
1932 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
1933 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
1935 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
1938 /// Return if the N is a constant or constant vector equal to the true value
1939 /// from getBooleanContents().
1940 bool isConstTrueVal(const SDNode *N) const;
1942 /// Return if the N is a constant or constant vector equal to the false value
1943 /// from getBooleanContents().
1944 bool isConstFalseVal(const SDNode *N) const;
1946 /// Try to simplify a setcc built with the specified operands and cc. If it is
1947 /// unable to simplify it, return a null SDValue.
1948 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1949 ISD::CondCode Cond, bool foldBooleans,
1950 DAGCombinerInfo &DCI, SDLoc dl) const;
1952 /// Returns true (and the GlobalValue and the offset) if the node is a
1953 /// GlobalAddress + offset.
1955 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
1957 /// This method will be invoked for all target nodes and for any
1958 /// target-independent nodes that the target has registered with invoke it
1961 /// The semantics are as follows:
1963 /// SDValue.Val == 0 - No change was made
1964 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
1965 /// otherwise - N should be replaced by the returned Operand.
1967 /// In addition, methods provided by DAGCombinerInfo may be used to perform
1968 /// more complex transformations.
1970 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
1972 /// Return true if the target has native support for the specified value type
1973 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
1974 /// i16 is legal, but undesirable since i16 instruction encodings are longer
1975 /// and some i16 instructions are slow.
1976 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
1977 // By default, assume all legal types are desirable.
1978 return isTypeLegal(VT);
1981 /// Return true if it is profitable for dag combiner to transform a floating
1982 /// point op of specified opcode to a equivalent op of an integer
1983 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
1984 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
1989 /// This method query the target whether it is beneficial for dag combiner to
1990 /// promote the specified node. If true, it should return the desired
1991 /// promotion type by reference.
1992 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
1996 //===--------------------------------------------------------------------===//
1997 // Lowering methods - These methods must be implemented by targets so that
1998 // the SelectionDAGBuilder code knows how to lower these.
2001 /// This hook must be implemented to lower the incoming (formal) arguments,
2002 /// described by the Ins array, into the specified DAG. The implementation
2003 /// should fill in the InVals array with legal-type argument values, and
2004 /// return the resulting token chain value.
2007 LowerFormalArguments(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2009 const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
2010 SDLoc /*dl*/, SelectionDAG &/*DAG*/,
2011 SmallVectorImpl<SDValue> &/*InVals*/) const {
2012 llvm_unreachable("Not Implemented");
2015 struct ArgListEntry {
2024 bool isInAlloca : 1;
2025 bool isReturned : 1;
2028 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false),
2029 isSRet(false), isNest(false), isByVal(false), isInAlloca(false),
2030 isReturned(false), Alignment(0) { }
2032 void setAttributes(ImmutableCallSite *CS, unsigned AttrIdx);
2034 typedef std::vector<ArgListEntry> ArgListTy;
2036 /// This structure contains all information that is necessary for lowering
2037 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
2038 /// needs to lower a call, and targets will see this struct in their LowerCall
2040 struct CallLoweringInfo {
2047 bool DoesNotReturn : 1;
2048 bool IsReturnValueUsed : 1;
2050 // IsTailCall should be modified by implementations of
2051 // TargetLowering::LowerCall that perform tail call conversions.
2054 unsigned NumFixedArgs;
2055 CallingConv::ID CallConv;
2060 ImmutableCallSite *CS;
2061 SmallVector<ISD::OutputArg, 32> Outs;
2062 SmallVector<SDValue, 32> OutVals;
2063 SmallVector<ISD::InputArg, 32> Ins;
2066 /// Constructs a call lowering context based on the ImmutableCallSite \p cs.
2067 CallLoweringInfo(SDValue chain, Type *retTy,
2068 FunctionType *FTy, bool isTailCall, SDValue callee,
2069 ArgListTy &args, SelectionDAG &dag, SDLoc dl,
2070 ImmutableCallSite &cs)
2071 : Chain(chain), RetTy(retTy), RetSExt(cs.paramHasAttr(0, Attribute::SExt)),
2072 RetZExt(cs.paramHasAttr(0, Attribute::ZExt)), IsVarArg(FTy->isVarArg()),
2073 IsInReg(cs.paramHasAttr(0, Attribute::InReg)),
2074 DoesNotReturn(cs.doesNotReturn()),
2075 IsReturnValueUsed(!cs.getInstruction()->use_empty()),
2076 IsTailCall(isTailCall), NumFixedArgs(FTy->getNumParams()),
2077 CallConv(cs.getCallingConv()), Callee(callee), Args(args), DAG(dag),
2080 /// Constructs a call lowering context based on the provided call
2082 CallLoweringInfo(SDValue chain, Type *retTy, bool retSExt, bool retZExt,
2083 bool isVarArg, bool isInReg, unsigned numFixedArgs,
2084 CallingConv::ID callConv, bool isTailCall,
2085 bool doesNotReturn, bool isReturnValueUsed, SDValue callee,
2086 ArgListTy &args, SelectionDAG &dag, SDLoc dl)
2087 : Chain(chain), RetTy(retTy), RetSExt(retSExt), RetZExt(retZExt),
2088 IsVarArg(isVarArg), IsInReg(isInReg), DoesNotReturn(doesNotReturn),
2089 IsReturnValueUsed(isReturnValueUsed), IsTailCall(isTailCall),
2090 NumFixedArgs(numFixedArgs), CallConv(callConv), Callee(callee),
2091 Args(args), DAG(dag), DL(dl), CS(NULL) {}
2094 /// This function lowers an abstract call to a function into an actual call.
2095 /// This returns a pair of operands. The first element is the return value
2096 /// for the function (if RetTy is not VoidTy). The second element is the
2097 /// outgoing token chain. It calls LowerCall to do the actual lowering.
2098 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
2100 /// This hook must be implemented to lower calls into the the specified
2101 /// DAG. The outgoing arguments to the call are described by the Outs array,
2102 /// and the values to be returned by the call are described by the Ins
2103 /// array. The implementation should fill in the InVals array with legal-type
2104 /// return values from the call, and return the resulting token chain value.
2106 LowerCall(CallLoweringInfo &/*CLI*/,
2107 SmallVectorImpl<SDValue> &/*InVals*/) const {
2108 llvm_unreachable("Not Implemented");
2111 /// Target-specific cleanup for formal ByVal parameters.
2112 virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
2114 /// This hook should be implemented to check whether the return values
2115 /// described by the Outs array can fit into the return registers. If false
2116 /// is returned, an sret-demotion is performed.
2117 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
2118 MachineFunction &/*MF*/, bool /*isVarArg*/,
2119 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2120 LLVMContext &/*Context*/) const
2122 // Return true by default to get preexisting behavior.
2126 /// This hook must be implemented to lower outgoing return values, described
2127 /// by the Outs array, into the specified DAG. The implementation should
2128 /// return the resulting token chain value.
2130 LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
2132 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
2133 const SmallVectorImpl<SDValue> &/*OutVals*/,
2134 SDLoc /*dl*/, SelectionDAG &/*DAG*/) const {
2135 llvm_unreachable("Not Implemented");
2138 /// Return true if result of the specified node is used by a return node
2139 /// only. It also compute and return the input chain for the tail call.
2141 /// This is used to determine whether it is possible to codegen a libcall as
2142 /// tail call at legalization time.
2143 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
2147 /// Return true if the target may be able emit the call instruction as a tail
2148 /// call. This is used by optimization passes to determine if it's profitable
2149 /// to duplicate return instructions to enable tailcall optimization.
2150 virtual bool mayBeEmittedAsTailCall(CallInst *) const {
2154 /// Return the builtin name for the __builtin___clear_cache intrinsic
2155 /// Default is to invoke the clear cache library call
2156 virtual const char * getClearCacheBuiltinName() const {
2157 return "__clear_cache";
2160 /// Return the type that should be used to zero or sign extend a
2161 /// zeroext/signext integer argument or return value. FIXME: Most C calling
2162 /// convention requires the return type to be promoted, but this is not true
2163 /// all the time, e.g. i1 on x86-64. It is also not necessary for non-C
2164 /// calling conventions. The frontend should handle this and include all of
2165 /// the necessary information.
2166 virtual MVT getTypeForExtArgOrReturn(MVT VT,
2167 ISD::NodeType /*ExtendKind*/) const {
2168 MVT MinVT = getRegisterType(MVT::i32);
2169 return VT.bitsLT(MinVT) ? MinVT : VT;
2172 /// Returns a 0 terminated array of registers that can be safely used as
2173 /// scratch registers.
2174 virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
2178 /// This callback is used to prepare for a volatile or atomic load.
2179 /// It takes a chain node as input and returns the chain for the load itself.
2181 /// Having a callback like this is necessary for targets like SystemZ,
2182 /// which allows a CPU to reuse the result of a previous load indefinitely,
2183 /// even if a cache-coherent store is performed by another CPU. The default
2184 /// implementation does nothing.
2185 virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL,
2186 SelectionDAG &DAG) const {
2190 /// This callback is invoked by the type legalizer to legalize nodes with an
2191 /// illegal operand type but legal result types. It replaces the
2192 /// LowerOperation callback in the type Legalizer. The reason we can not do
2193 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
2194 /// use this callback.
2196 /// TODO: Consider merging with ReplaceNodeResults.
2198 /// The target places new result values for the node in Results (their number
2199 /// and types must exactly match those of the original return values of
2200 /// the node), or leaves Results empty, which indicates that the node is not
2201 /// to be custom lowered after all.
2202 /// The default implementation calls LowerOperation.
2203 virtual void LowerOperationWrapper(SDNode *N,
2204 SmallVectorImpl<SDValue> &Results,
2205 SelectionDAG &DAG) const;
2207 /// This callback is invoked for operations that are unsupported by the
2208 /// target, which are registered to use 'custom' lowering, and whose defined
2209 /// values are all legal. If the target has no operations that require custom
2210 /// lowering, it need not implement this. The default implementation of this
2212 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
2214 /// This callback is invoked when a node result type is illegal for the
2215 /// target, and the operation was registered to use 'custom' lowering for that
2216 /// result type. The target places new result values for the node in Results
2217 /// (their number and types must exactly match those of the original return
2218 /// values of the node), or leaves Results empty, which indicates that the
2219 /// node is not to be custom lowered after all.
2221 /// If the target has no operations that require custom lowering, it need not
2222 /// implement this. The default implementation aborts.
2223 virtual void ReplaceNodeResults(SDNode * /*N*/,
2224 SmallVectorImpl<SDValue> &/*Results*/,
2225 SelectionDAG &/*DAG*/) const {
2226 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
2229 /// This method returns the name of a target specific DAG node.
2230 virtual const char *getTargetNodeName(unsigned Opcode) const;
2232 /// This method returns a target specific FastISel object, or null if the
2233 /// target does not support "fast" ISel.
2234 virtual FastISel *createFastISel(FunctionLoweringInfo &,
2235 const TargetLibraryInfo *) const {
2240 bool verifyReturnAddressArgumentIsConstant(SDValue Op,
2241 SelectionDAG &DAG) const;
2243 //===--------------------------------------------------------------------===//
2244 // Inline Asm Support hooks
2247 /// This hook allows the target to expand an inline asm call to be explicit
2248 /// llvm code if it wants to. This is useful for turning simple inline asms
2249 /// into LLVM intrinsics, which gives the compiler more information about the
2250 /// behavior of the code.
2251 virtual bool ExpandInlineAsm(CallInst *) const {
2255 enum ConstraintType {
2256 C_Register, // Constraint represents specific register(s).
2257 C_RegisterClass, // Constraint represents any of register(s) in class.
2258 C_Memory, // Memory constraint.
2259 C_Other, // Something else.
2260 C_Unknown // Unsupported constraint.
2263 enum ConstraintWeight {
2265 CW_Invalid = -1, // No match.
2266 CW_Okay = 0, // Acceptable.
2267 CW_Good = 1, // Good weight.
2268 CW_Better = 2, // Better weight.
2269 CW_Best = 3, // Best weight.
2271 // Well-known weights.
2272 CW_SpecificReg = CW_Okay, // Specific register operands.
2273 CW_Register = CW_Good, // Register operands.
2274 CW_Memory = CW_Better, // Memory operands.
2275 CW_Constant = CW_Best, // Constant operand.
2276 CW_Default = CW_Okay // Default or don't know type.
2279 /// This contains information for each constraint that we are lowering.
2280 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2281 /// This contains the actual string for the code, like "m". TargetLowering
2282 /// picks the 'best' code from ConstraintInfo::Codes that most closely
2283 /// matches the operand.
2284 std::string ConstraintCode;
2286 /// Information about the constraint code, e.g. Register, RegisterClass,
2287 /// Memory, Other, Unknown.
2288 TargetLowering::ConstraintType ConstraintType;
2290 /// If this is the result output operand or a clobber, this is null,
2291 /// otherwise it is the incoming operand to the CallInst. This gets
2292 /// modified as the asm is processed.
2293 Value *CallOperandVal;
2295 /// The ValueType for the operand value.
2298 /// Return true of this is an input operand that is a matching constraint
2300 bool isMatchingInputConstraint() const;
2302 /// If this is an input matching constraint, this method returns the output
2303 /// operand it matches.
2304 unsigned getMatchedOperand() const;
2306 /// Copy constructor for copying from a ConstraintInfo.
2307 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
2308 : InlineAsm::ConstraintInfo(info),
2309 ConstraintType(TargetLowering::C_Unknown),
2310 CallOperandVal(0), ConstraintVT(MVT::Other) {
2314 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector;
2316 /// Split up the constraint string from the inline assembly value into the
2317 /// specific constraints and their prefixes, and also tie in the associated
2318 /// operand values. If this returns an empty vector, and if the constraint
2319 /// string itself isn't empty, there was an error parsing.
2320 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const;
2322 /// Examine constraint type and operand type and determine a weight value.
2323 /// The operand object must already have been set up with the operand type.
2324 virtual ConstraintWeight getMultipleConstraintMatchWeight(
2325 AsmOperandInfo &info, int maIndex) const;
2327 /// Examine constraint string and operand type and determine a weight value.
2328 /// The operand object must already have been set up with the operand type.
2329 virtual ConstraintWeight getSingleConstraintMatchWeight(
2330 AsmOperandInfo &info, const char *constraint) const;
2332 /// Determines the constraint code and constraint type to use for the specific
2333 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2334 /// If the actual operand being passed in is available, it can be passed in as
2335 /// Op, otherwise an empty SDValue can be passed.
2336 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2338 SelectionDAG *DAG = 0) const;
2340 /// Given a constraint, return the type of constraint it is for this target.
2341 virtual ConstraintType getConstraintType(const std::string &Constraint) const;
2343 /// Given a physical register constraint (e.g. {edx}), return the register
2344 /// number and the register class for the register.
2346 /// Given a register class constraint, like 'r', if this corresponds directly
2347 /// to an LLVM register class, return a register of 0 and the register class
2350 /// This should only be used for C_Register constraints. On error, this
2351 /// returns a register number of 0 and a null register class pointer..
2352 virtual std::pair<unsigned, const TargetRegisterClass*>
2353 getRegForInlineAsmConstraint(const std::string &Constraint,
2356 /// Try to replace an X constraint, which matches anything, with another that
2357 /// has more specific requirements based on the type of the corresponding
2358 /// operand. This returns null if there is no replacement to make.
2359 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
2361 /// Lower the specified operand into the Ops vector. If it is invalid, don't
2362 /// add anything to Ops.
2363 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
2364 std::vector<SDValue> &Ops,
2365 SelectionDAG &DAG) const;
2367 //===--------------------------------------------------------------------===//
2368 // Div utility functions
2370 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2371 SelectionDAG &DAG) const;
2372 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2373 std::vector<SDNode*> *Created) const;
2374 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2375 std::vector<SDNode*> *Created) const;
2377 //===--------------------------------------------------------------------===//
2378 // Instruction Emitting Hooks
2381 /// This method should be implemented by targets that mark instructions with
2382 /// the 'usesCustomInserter' flag. These instructions are special in various
2383 /// ways, which require special support to insert. The specified MachineInstr
2384 /// is created but not inserted into any basic blocks, and this method is
2385 /// called to expand it into a sequence of instructions, potentially also
2386 /// creating new basic blocks and control flow.
2387 virtual MachineBasicBlock *
2388 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const;
2390 /// This method should be implemented by targets that mark instructions with
2391 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
2392 /// instruction selection by target hooks. e.g. To fill in optional defs for
2393 /// ARM 's' setting instructions.
2395 AdjustInstrPostInstrSelection(MachineInstr *MI, SDNode *Node) const;
2398 /// Given an LLVM IR type and return type attributes, compute the return value
2399 /// EVTs and flags, and optionally also the offsets, if the return value is
2400 /// being lowered to memory.
2401 void GetReturnInfo(Type* ReturnType, AttributeSet attr,
2402 SmallVectorImpl<ISD::OutputArg> &Outs,
2403 const TargetLowering &TLI);
2405 } // end llvm namespace