1 //===- TargetTransformInfoImpl.h --------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file provides helpers for the implementation of
11 /// a TargetTransformInfo-conforming class.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
16 #define LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/Analysis/VectorUtils.h"
30 /// \brief Base class for use as a mix-in that aids implementing
31 /// a TargetTransformInfo-compatible class.
32 class TargetTransformInfoImplBase {
34 typedef TargetTransformInfo TTI;
38 explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {}
41 // Provide value semantics. MSVC requires that we spell all of these out.
42 TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
44 TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg) : DL(Arg.DL) {}
46 const DataLayout &getDataLayout() const { return DL; }
48 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
51 // By default, just classify everything as 'basic'.
52 return TTI::TCC_Basic;
54 case Instruction::GetElementPtr:
55 llvm_unreachable("Use getGEPCost for GEP operations!");
57 case Instruction::BitCast:
58 assert(OpTy && "Cast instructions must provide the operand type");
59 if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
60 // Identity and pointer-to-pointer casts are free.
63 // Otherwise, the default basic cost is used.
64 return TTI::TCC_Basic;
66 case Instruction::FDiv:
67 case Instruction::FRem:
68 case Instruction::SDiv:
69 case Instruction::SRem:
70 case Instruction::UDiv:
71 case Instruction::URem:
72 return TTI::TCC_Expensive;
74 case Instruction::IntToPtr: {
75 // An inttoptr cast is free so long as the input is a legal integer type
76 // which doesn't contain values outside the range of a pointer.
77 unsigned OpSize = OpTy->getScalarSizeInBits();
78 if (DL.isLegalInteger(OpSize) &&
79 OpSize <= DL.getPointerTypeSizeInBits(Ty))
82 // Otherwise it's not a no-op.
83 return TTI::TCC_Basic;
85 case Instruction::PtrToInt: {
86 // A ptrtoint cast is free so long as the result is large enough to store
87 // the pointer, and a legal integer type.
88 unsigned DestSize = Ty->getScalarSizeInBits();
89 if (DL.isLegalInteger(DestSize) &&
90 DestSize >= DL.getPointerTypeSizeInBits(OpTy))
93 // Otherwise it's not a no-op.
94 return TTI::TCC_Basic;
96 case Instruction::Trunc:
97 // trunc to a native type is free (assuming the target has compare and
98 // shift-right of the same width).
99 if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty)))
100 return TTI::TCC_Free;
102 return TTI::TCC_Basic;
106 int getGEPCost(Type *PointeeType, const Value *Ptr,
107 ArrayRef<const Value *> Operands) {
108 // In the basic model, we just assume that all-constant GEPs will be folded
109 // into their uses via addressing modes.
110 for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
111 if (!isa<Constant>(Operands[Idx]))
112 return TTI::TCC_Basic;
114 return TTI::TCC_Free;
117 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
120 return SI.getNumCases();
123 unsigned getCallCost(FunctionType *FTy, int NumArgs) {
124 assert(FTy && "FunctionType must be provided to this routine.");
126 // The target-independent implementation just measures the size of the
127 // function by approximating that each argument will take on average one
128 // instruction to prepare.
131 // Set the argument number to the number of explicit arguments in the
133 NumArgs = FTy->getNumParams();
135 return TTI::TCC_Basic * (NumArgs + 1);
138 unsigned getInliningThresholdMultiplier() { return 1; }
140 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
141 ArrayRef<Type *> ParamTys) {
144 // Intrinsics rarely (if ever) have normal argument setup constraints.
145 // Model them as having a basic instruction cost.
146 // FIXME: This is wrong for libc intrinsics.
147 return TTI::TCC_Basic;
149 case Intrinsic::annotation:
150 case Intrinsic::assume:
151 case Intrinsic::dbg_declare:
152 case Intrinsic::dbg_value:
153 case Intrinsic::invariant_start:
154 case Intrinsic::invariant_end:
155 case Intrinsic::lifetime_start:
156 case Intrinsic::lifetime_end:
157 case Intrinsic::objectsize:
158 case Intrinsic::ptr_annotation:
159 case Intrinsic::var_annotation:
160 case Intrinsic::experimental_gc_result:
161 case Intrinsic::experimental_gc_relocate:
162 case Intrinsic::coro_alloc:
163 case Intrinsic::coro_begin:
164 case Intrinsic::coro_free:
165 case Intrinsic::coro_end:
166 case Intrinsic::coro_frame:
167 case Intrinsic::coro_size:
168 case Intrinsic::coro_suspend:
169 case Intrinsic::coro_param:
170 case Intrinsic::coro_subfn_addr:
171 // These intrinsics don't actually represent code after lowering.
172 return TTI::TCC_Free;
176 bool hasBranchDivergence() { return false; }
178 bool isSourceOfDivergence(const Value *V) { return false; }
180 unsigned getFlatAddressSpace () {
184 bool isLoweredToCall(const Function *F) {
185 // FIXME: These should almost certainly not be handled here, and instead
186 // handled with the help of TLI or the target itself. This was largely
187 // ported from existing analysis heuristics here so that such refactorings
188 // can take place in the future.
190 if (F->isIntrinsic())
193 if (F->hasLocalLinkage() || !F->hasName())
196 StringRef Name = F->getName();
198 // These will all likely lower to a single selection DAG node.
199 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
200 Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
201 Name == "fmin" || Name == "fminf" || Name == "fminl" ||
202 Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
203 Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
204 Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
207 // These are all likely to be optimized into something smaller.
208 if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
209 Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
210 Name == "floorf" || Name == "ceil" || Name == "round" ||
211 Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
218 void getUnrollingPreferences(Loop *, TTI::UnrollingPreferences &) {}
220 bool isLegalAddImmediate(int64_t Imm) { return false; }
222 bool isLegalICmpImmediate(int64_t Imm) { return false; }
224 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
225 bool HasBaseReg, int64_t Scale,
226 unsigned AddrSpace) {
227 // Guess that only reg and reg+reg addressing is allowed. This heuristic is
228 // taken from the implementation of LSR.
229 return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
232 bool isLegalMaskedStore(Type *DataType) { return false; }
234 bool isLegalMaskedLoad(Type *DataType) { return false; }
236 bool isLegalMaskedScatter(Type *DataType) { return false; }
238 bool isLegalMaskedGather(Type *DataType) { return false; }
240 bool prefersVectorizedAddressing() { return true; }
242 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
243 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
244 // Guess that all legal addressing mode are free.
245 if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
251 bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) { return true; }
253 bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
255 bool isProfitableToHoist(Instruction *I) { return true; }
257 bool isTypeLegal(Type *Ty) { return false; }
259 unsigned getJumpBufAlignment() { return 0; }
261 unsigned getJumpBufSize() { return 0; }
263 bool shouldBuildLookupTables() { return true; }
264 bool shouldBuildLookupTablesForConstant(Constant *C) { return true; }
266 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
270 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
271 unsigned VF) { return 0; }
273 bool supportsEfficientVectorElementLoadStore() { return false; }
275 bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
277 bool expandMemCmp(Instruction *I, unsigned &MaxLoadSize) { return false; }
279 bool enableInterleavedAccessVectorization() { return false; }
281 bool isFPVectorizationPotentiallyUnsafe() { return false; }
283 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
285 unsigned AddressSpace,
287 bool *Fast) { return false; }
289 TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
290 return TTI::PSK_Software;
293 bool haveFastSqrt(Type *Ty) { return false; }
295 unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
297 int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
302 unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
304 unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
306 return TTI::TCC_Free;
309 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
311 return TTI::TCC_Free;
314 unsigned getNumberOfRegisters(bool Vector) { return 8; }
316 unsigned getRegisterBitWidth(bool Vector) { return 32; }
318 unsigned getMinVectorRegisterBitWidth() { return 128; }
321 shouldConsiderAddressTypePromotion(const Instruction &I,
322 bool &AllowPromotionWithoutCommonHeader) {
323 AllowPromotionWithoutCommonHeader = false;
327 unsigned getCacheLineSize() { return 0; }
329 unsigned getPrefetchDistance() { return 0; }
331 unsigned getMinPrefetchStride() { return 1; }
333 unsigned getMaxPrefetchIterationsAhead() { return UINT_MAX; }
335 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
337 unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
338 TTI::OperandValueKind Opd1Info,
339 TTI::OperandValueKind Opd2Info,
340 TTI::OperandValueProperties Opd1PropInfo,
341 TTI::OperandValueProperties Opd2PropInfo,
342 ArrayRef<const Value *> Args) {
346 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
351 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
352 const Instruction *I) { return 1; }
354 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
355 VectorType *VecTy, unsigned Index) {
359 unsigned getCFInstrCost(unsigned Opcode) { return 1; }
361 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
362 const Instruction *I) {
366 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
370 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
371 unsigned AddressSpace, const Instruction *I) {
375 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
376 unsigned AddressSpace) {
380 unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
382 unsigned Alignment) {
386 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
388 ArrayRef<unsigned> Indices,
390 unsigned AddressSpace) {
394 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
395 ArrayRef<Type *> Tys, FastMathFlags FMF,
396 unsigned ScalarizationCostPassed) {
399 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
400 ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
404 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
408 unsigned getNumberOfParts(Type *Tp) { return 0; }
410 unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *,
415 unsigned getReductionCost(unsigned, Type *, bool) { return 1; }
417 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
419 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
423 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
424 Type *ExpectedType) {
428 bool areInlineCompatible(const Function *Caller,
429 const Function *Callee) const {
430 return (Caller->getFnAttribute("target-cpu") ==
431 Callee->getFnAttribute("target-cpu")) &&
432 (Caller->getFnAttribute("target-features") ==
433 Callee->getFnAttribute("target-features"));
436 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
438 bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
440 bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
442 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
444 unsigned AddrSpace) const {
448 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
450 unsigned AddrSpace) const {
454 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
455 unsigned ChainSizeInBytes,
456 VectorType *VecTy) const {
460 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
461 unsigned ChainSizeInBytes,
462 VectorType *VecTy) const {
466 bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
467 TTI::ReductionFlags Flags) const {
471 bool shouldExpandReduction(const IntrinsicInst *II) const {
476 // Obtain the minimum required size to hold the value (without the sign)
477 // In case of a vector it returns the min required size for one element.
478 unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
479 if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
480 const auto* VectorValue = cast<Constant>(Val);
482 // In case of a vector need to pick the max between the min
483 // required size for each element
484 auto *VT = cast<VectorType>(Val->getType());
486 // Assume unsigned elements
489 // The max required size is the total vector width divided by num
490 // of elements in the vector
491 unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
493 unsigned MinRequiredSize = 0;
494 for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
495 if (auto* IntElement =
496 dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
497 bool signedElement = IntElement->getValue().isNegative();
498 // Get the element min required size.
499 unsigned ElementMinRequiredSize =
500 IntElement->getValue().getMinSignedBits() - 1;
501 // In case one element is signed then all the vector is signed.
502 isSigned |= signedElement;
503 // Save the max required bit size between all the elements.
504 MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
507 // not an int constant element
508 return MaxRequiredSize;
511 return MinRequiredSize;
514 if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
515 isSigned = CI->getValue().isNegative();
516 return CI->getValue().getMinSignedBits() - 1;
519 if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
521 return Cast->getSrcTy()->getScalarSizeInBits() - 1;
524 if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
526 return Cast->getSrcTy()->getScalarSizeInBits();
530 return Val->getType()->getScalarSizeInBits();
533 bool isStridedAccess(const SCEV *Ptr) {
534 return Ptr && isa<SCEVAddRecExpr>(Ptr);
537 const SCEVConstant *getConstantStrideStep(ScalarEvolution *SE,
539 if (!isStridedAccess(Ptr))
541 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
542 return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
545 bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr,
546 int64_t MergeDistance) {
547 const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
550 APInt StrideVal = Step->getAPInt();
551 if (StrideVal.getBitWidth() > 64)
553 // FIXME: need to take absolute value for negtive stride case
554 return StrideVal.getSExtValue() < MergeDistance;
558 /// \brief CRTP base class for use as a mix-in that aids implementing
559 /// a TargetTransformInfo-compatible class.
560 template <typename T>
561 class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
563 typedef TargetTransformInfoImplBase BaseT;
566 explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
569 using BaseT::getCallCost;
571 unsigned getCallCost(const Function *F, int NumArgs) {
572 assert(F && "A concrete function must be provided to this routine.");
575 // Set the argument number to the number of explicit arguments in the
577 NumArgs = F->arg_size();
579 if (Intrinsic::ID IID = F->getIntrinsicID()) {
580 FunctionType *FTy = F->getFunctionType();
581 SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
582 return static_cast<T *>(this)
583 ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
586 if (!static_cast<T *>(this)->isLoweredToCall(F))
587 return TTI::TCC_Basic; // Give a basic cost if it will be lowered
590 return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
593 unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
594 // Simply delegate to generic handling of the call.
595 // FIXME: We should use instsimplify or something else to catch calls which
596 // will constant fold with these arguments.
597 return static_cast<T *>(this)->getCallCost(F, Arguments.size());
600 using BaseT::getGEPCost;
602 int getGEPCost(Type *PointeeType, const Value *Ptr,
603 ArrayRef<const Value *> Operands) {
604 const GlobalValue *BaseGV = nullptr;
605 if (Ptr != nullptr) {
606 // TODO: will remove this when pointers have an opaque type.
607 assert(Ptr->getType()->getScalarType()->getPointerElementType() ==
609 "explicit pointee type doesn't match operand's pointee type");
610 BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
612 bool HasBaseReg = (BaseGV == nullptr);
613 int64_t BaseOffset = 0;
616 auto GTI = gep_type_begin(PointeeType, Operands);
618 for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
619 TargetType = GTI.getIndexedType();
620 // We assume that the cost of Scalar GEP with constant index and the
621 // cost of Vector GEP with splat constant index are the same.
622 const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
624 if (auto Splat = getSplatValue(*I))
625 ConstIdx = dyn_cast<ConstantInt>(Splat);
626 if (StructType *STy = GTI.getStructTypeOrNull()) {
627 // For structures the index is always splat or scalar constant
628 assert(ConstIdx && "Unexpected GEP index");
629 uint64_t Field = ConstIdx->getZExtValue();
630 BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
632 int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
634 BaseOffset += ConstIdx->getSExtValue() * ElementSize;
636 // Needs scale register.
638 // No addressing mode takes two scale registers.
639 return TTI::TCC_Basic;
645 // Assumes the address space is 0 when Ptr is nullptr.
647 (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
648 if (static_cast<T *>(this)->isLegalAddressingMode(
649 TargetType, const_cast<GlobalValue *>(BaseGV), BaseOffset,
650 HasBaseReg, Scale, AS))
651 return TTI::TCC_Free;
652 return TTI::TCC_Basic;
655 using BaseT::getIntrinsicCost;
657 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
658 ArrayRef<const Value *> Arguments) {
659 // Delegate to the generic intrinsic handling code. This mostly provides an
660 // opportunity for targets to (for example) special case the cost of
661 // certain intrinsics based on constants used as arguments.
662 SmallVector<Type *, 8> ParamTys;
663 ParamTys.reserve(Arguments.size());
664 for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
665 ParamTys.push_back(Arguments[Idx]->getType());
666 return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
669 unsigned getUserCost(const User *U) {
671 return TTI::TCC_Free; // Model all PHI nodes as free.
673 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
674 SmallVector<Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end());
675 return static_cast<T *>(this)->getGEPCost(
676 GEP->getSourceElementType(), GEP->getPointerOperand(), Indices);
679 if (auto CS = ImmutableCallSite(U)) {
680 const Function *F = CS.getCalledFunction();
682 // Just use the called value type.
683 Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
684 return static_cast<T *>(this)
685 ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
688 SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
689 return static_cast<T *>(this)->getCallCost(F, Arguments);
692 if (const CastInst *CI = dyn_cast<CastInst>(U)) {
693 // Result of a cmp instruction is often extended (to be used by other
694 // cmp instructions, logical or return instructions). These are usually
695 // nop on most sane targets.
696 if (isa<CmpInst>(CI->getOperand(0)))
697 return TTI::TCC_Free;
700 return static_cast<T *>(this)->getOperationCost(
701 Operator::getOpcode(U), U->getType(),
702 U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);