1 //===- BasicTTIImpl.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 a helper that implements much of the TTI interface in
11 /// terms of the target-independent code generator and TargetLowering
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
17 #define LLVM_CODEGEN_BASICTTIIMPL_H
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/TargetTransformInfoImpl.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetSubtargetInfo.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
28 extern cl::opt<unsigned> PartialUnrollingThreshold;
30 /// \brief Base class which can be used to help build a TTI implementation.
32 /// This class provides as much implementation of the TTI interface as is
33 /// possible using the target independent parts of the code generator.
35 /// In order to subclass it, your class must implement a getST() method to
36 /// return the subtarget, and a getTLI() method to return the target lowering.
37 /// We need these methods implemented in the derived class so that this class
38 /// doesn't have to duplicate storage for them.
40 class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
42 typedef TargetTransformInfoImplCRTPBase<T> BaseT;
43 typedef TargetTransformInfo TTI;
45 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
46 /// are set if the result needs to be inserted and/or extracted from vectors.
47 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
48 assert(Ty->isVectorTy() && "Can only scalarize vectors");
51 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
53 Cost += static_cast<T *>(this)
54 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
56 Cost += static_cast<T *>(this)
57 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
63 /// Estimate the cost overhead of SK_Alternate shuffle.
64 unsigned getAltShuffleOverhead(Type *Ty) {
65 assert(Ty->isVectorTy() && "Can only shuffle vectors");
67 // Shuffle cost is equal to the cost of extracting element from its argument
68 // plus the cost of inserting them onto the result vector.
70 // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
71 // index 0 of first vector, index 1 of second vector,index 2 of first
72 // vector and finally index 3 of second vector and insert them at index
73 // <0,1,2,3> of result vector.
74 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
75 Cost += static_cast<T *>(this)
76 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
77 Cost += static_cast<T *>(this)
78 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
83 /// \brief Local query method delegates up to T which *must* implement this!
84 const TargetSubtargetInfo *getST() const {
85 return static_cast<const T *>(this)->getST();
88 /// \brief Local query method delegates up to T which *must* implement this!
89 const TargetLoweringBase *getTLI() const {
90 return static_cast<const T *>(this)->getTLI();
94 explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
97 using TargetTransformInfoImplBase::DL;
100 // Provide value semantics. MSVC requires that we spell all of these out.
101 BasicTTIImplBase(const BasicTTIImplBase &Arg)
102 : BaseT(static_cast<const BaseT &>(Arg)) {}
103 BasicTTIImplBase(BasicTTIImplBase &&Arg)
104 : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
106 /// \name Scalar TTI Implementations
109 bool hasBranchDivergence() { return false; }
111 bool isSourceOfDivergence(const Value *V) { return false; }
113 bool isLegalAddImmediate(int64_t imm) {
114 return getTLI()->isLegalAddImmediate(imm);
117 bool isLegalICmpImmediate(int64_t imm) {
118 return getTLI()->isLegalICmpImmediate(imm);
121 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
122 bool HasBaseReg, int64_t Scale,
123 unsigned AddrSpace) {
124 TargetLoweringBase::AddrMode AM;
126 AM.BaseOffs = BaseOffset;
127 AM.HasBaseReg = HasBaseReg;
129 return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace);
132 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
133 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
134 TargetLoweringBase::AddrMode AM;
136 AM.BaseOffs = BaseOffset;
137 AM.HasBaseReg = HasBaseReg;
139 return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
142 bool isTruncateFree(Type *Ty1, Type *Ty2) {
143 return getTLI()->isTruncateFree(Ty1, Ty2);
146 bool isZExtFree(Type *Ty1, Type *Ty2) const {
147 return getTLI()->isZExtFree(Ty1, Ty2);
150 bool isProfitableToHoist(Instruction *I) {
151 return getTLI()->isProfitableToHoist(I);
154 bool isTypeLegal(Type *Ty) {
155 EVT VT = getTLI()->getValueType(DL, Ty);
156 return getTLI()->isTypeLegal(VT);
159 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
160 ArrayRef<const Value *> Arguments) {
161 return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
164 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
165 ArrayRef<Type *> ParamTys) {
166 if (IID == Intrinsic::cttz) {
167 if (getTLI()->isCheapToSpeculateCttz())
168 return TargetTransformInfo::TCC_Basic;
169 return TargetTransformInfo::TCC_Expensive;
172 if (IID == Intrinsic::ctlz) {
173 if (getTLI()->isCheapToSpeculateCtlz())
174 return TargetTransformInfo::TCC_Basic;
175 return TargetTransformInfo::TCC_Expensive;
178 return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
181 unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
183 unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
185 bool shouldBuildLookupTables() {
186 const TargetLoweringBase *TLI = getTLI();
187 return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
188 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
191 bool haveFastSqrt(Type *Ty) {
192 const TargetLoweringBase *TLI = getTLI();
193 EVT VT = TLI->getValueType(DL, Ty);
194 return TLI->isTypeLegal(VT) &&
195 TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
198 unsigned getFPOpCost(Type *Ty) {
199 // By default, FP instructions are no more expensive since they are
200 // implemented in HW. Target specific TTI can override this.
201 return TargetTransformInfo::TCC_Basic;
204 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
205 const TargetLoweringBase *TLI = getTLI();
208 case Instruction::Trunc: {
209 if (TLI->isTruncateFree(OpTy, Ty))
210 return TargetTransformInfo::TCC_Free;
211 return TargetTransformInfo::TCC_Basic;
213 case Instruction::ZExt: {
214 if (TLI->isZExtFree(OpTy, Ty))
215 return TargetTransformInfo::TCC_Free;
216 return TargetTransformInfo::TCC_Basic;
220 return BaseT::getOperationCost(Opcode, Ty, OpTy);
223 void getUnrollingPreferences(Loop *L, TTI::UnrollingPreferences &UP) {
224 // This unrolling functionality is target independent, but to provide some
225 // motivation for its intended use, for x86:
227 // According to the Intel 64 and IA-32 Architectures Optimization Reference
228 // Manual, Intel Core models and later have a loop stream detector (and
229 // associated uop queue) that can benefit from partial unrolling.
230 // The relevant requirements are:
231 // - The loop must have no more than 4 (8 for Nehalem and later) branches
232 // taken, and none of them may be calls.
233 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
235 // According to the Software Optimization Guide for AMD Family 15h
236 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
237 // and loop buffer which can benefit from partial unrolling.
238 // The relevant requirements are:
239 // - The loop must have fewer than 16 branches
240 // - The loop must have less than 40 uops in all executed loop branches
242 // The number of taken branches in a loop is hard to estimate here, and
243 // benchmarking has revealed that it is better not to be conservative when
244 // estimating the branch count. As a result, we'll ignore the branch limits
245 // until someone finds a case where it matters in practice.
248 const TargetSubtargetInfo *ST = getST();
249 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
250 MaxOps = PartialUnrollingThreshold;
251 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
252 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
256 // Scan the loop: don't unroll loops with calls.
257 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
261 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
262 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
263 ImmutableCallSite CS(&*J);
264 if (const Function *F = CS.getCalledFunction()) {
265 if (!static_cast<T *>(this)->isLoweredToCall(F))
273 // Enable runtime and partial unrolling up to the specified size.
274 UP.Partial = UP.Runtime = true;
275 UP.PartialThreshold = UP.PartialOptSizeThreshold = MaxOps;
280 /// \name Vector TTI Implementations
283 unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
285 unsigned getRegisterBitWidth(bool Vector) { return 32; }
287 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
289 unsigned getArithmeticInstrCost(
290 unsigned Opcode, Type *Ty,
291 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
292 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
293 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
294 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None) {
295 // Check if any of the operands are vector operands.
296 const TargetLoweringBase *TLI = getTLI();
297 int ISD = TLI->InstructionOpcodeToISD(Opcode);
298 assert(ISD && "Invalid opcode");
300 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
302 bool IsFloat = Ty->getScalarType()->isFloatingPointTy();
303 // Assume that floating point arithmetic operations cost twice as much as
304 // integer operations.
305 unsigned OpCost = (IsFloat ? 2 : 1);
307 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
308 // The operation is legal. Assume it costs 1.
309 // If the type is split to multiple registers, assume that there is some
311 // TODO: Once we have extract/insert subvector cost we need to use them.
313 return LT.first * 2 * OpCost;
314 return LT.first * 1 * OpCost;
317 if (!TLI->isOperationExpand(ISD, LT.second)) {
318 // If the operation is custom lowered then assume
319 // thare the code is twice as expensive.
320 return LT.first * 2 * OpCost;
323 // Else, assume that we need to scalarize this op.
324 if (Ty->isVectorTy()) {
325 unsigned Num = Ty->getVectorNumElements();
326 unsigned Cost = static_cast<T *>(this)
327 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
328 // return the cost of multiple scalar invocation plus the cost of
330 // and extracting the values.
331 return getScalarizationOverhead(Ty, true, true) + Num * Cost;
334 // We don't know anything about this scalar instruction.
338 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
340 if (Kind == TTI::SK_Alternate) {
341 return getAltShuffleOverhead(Tp);
346 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
347 const TargetLoweringBase *TLI = getTLI();
348 int ISD = TLI->InstructionOpcodeToISD(Opcode);
349 assert(ISD && "Invalid opcode");
350 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
351 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
353 // Check for NOOP conversions.
354 if (SrcLT.first == DstLT.first &&
355 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
357 // Bitcast between types that are legalized to the same type are free.
358 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
362 if (Opcode == Instruction::Trunc &&
363 TLI->isTruncateFree(SrcLT.second, DstLT.second))
366 if (Opcode == Instruction::ZExt &&
367 TLI->isZExtFree(SrcLT.second, DstLT.second))
370 // If the cast is marked as legal (or promote) then assume low cost.
371 if (SrcLT.first == DstLT.first &&
372 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
375 // Handle scalar conversions.
376 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
378 // Scalar bitcasts are usually free.
379 if (Opcode == Instruction::BitCast)
382 // Just check the op cost. If the operation is legal then assume it costs
384 if (!TLI->isOperationExpand(ISD, DstLT.second))
387 // Assume that illegal scalar instruction are expensive.
391 // Check vector-to-vector casts.
392 if (Dst->isVectorTy() && Src->isVectorTy()) {
394 // If the cast is between same-sized registers, then the check is simple.
395 if (SrcLT.first == DstLT.first &&
396 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
398 // Assume that Zext is done using AND.
399 if (Opcode == Instruction::ZExt)
402 // Assume that sext is done using SHL and SRA.
403 if (Opcode == Instruction::SExt)
406 // Just check the op cost. If the operation is legal then assume it
408 // 1 and multiply by the type-legalization overhead.
409 if (!TLI->isOperationExpand(ISD, DstLT.second))
410 return SrcLT.first * 1;
413 // If we are converting vectors and the operation is illegal, or
414 // if the vectors are legalized to different types, estimate the
415 // scalarization costs.
416 unsigned Num = Dst->getVectorNumElements();
417 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
418 Opcode, Dst->getScalarType(), Src->getScalarType());
420 // Return the cost of multiple scalar invocation plus the cost of
421 // inserting and extracting the values.
422 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
425 // We already handled vector-to-vector and scalar-to-scalar conversions.
427 // is where we handle bitcast between vectors and scalars. We need to assume
428 // that the conversion is scalarized in one way or another.
429 if (Opcode == Instruction::BitCast)
430 // Illegal bitcasts are done by storing and loading from a stack slot.
431 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
433 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
436 llvm_unreachable("Unhandled cast");
439 unsigned getCFInstrCost(unsigned Opcode) {
440 // Branches are assumed to be predicted.
444 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
445 const TargetLoweringBase *TLI = getTLI();
446 int ISD = TLI->InstructionOpcodeToISD(Opcode);
447 assert(ISD && "Invalid opcode");
449 // Selects on vectors are actually vector selects.
450 if (ISD == ISD::SELECT) {
451 assert(CondTy && "CondTy must exist");
452 if (CondTy->isVectorTy())
455 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
457 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
458 !TLI->isOperationExpand(ISD, LT.second)) {
459 // The operation is legal. Assume it costs 1. Multiply
460 // by the type-legalization overhead.
464 // Otherwise, assume that the cast is scalarized.
465 if (ValTy->isVectorTy()) {
466 unsigned Num = ValTy->getVectorNumElements();
468 CondTy = CondTy->getScalarType();
469 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
470 Opcode, ValTy->getScalarType(), CondTy);
472 // Return the cost of multiple scalar invocation plus the cost of
474 // and extracting the values.
475 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
478 // Unknown scalar opcode.
482 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
483 std::pair<unsigned, MVT> LT =
484 getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
489 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
490 unsigned AddressSpace) {
491 assert(!Src->isVoidTy() && "Invalid type");
492 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
494 // Assuming that all loads of legal types cost 1.
495 unsigned Cost = LT.first;
497 if (Src->isVectorTy() &&
498 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
499 // This is a vector load that legalizes to a larger type than the vector
500 // itself. Unless the corresponding extending load or truncating store is
501 // legal, then this will scalarize.
502 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
503 EVT MemVT = getTLI()->getValueType(DL, Src, true);
504 if (MemVT.isSimple() && MemVT != MVT::Other) {
505 if (Opcode == Instruction::Store)
506 LA = getTLI()->getTruncStoreAction(LT.second, MemVT.getSimpleVT());
508 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
511 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
512 // This is a vector load/store for some illegal type that is scalarized.
513 // We must account for the cost of building or decomposing the vector.
514 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
515 Opcode == Instruction::Store);
522 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
524 ArrayRef<unsigned> Indices,
526 unsigned AddressSpace) {
527 VectorType *VT = dyn_cast<VectorType>(VecTy);
528 assert(VT && "Expect a vector type for interleaved memory op");
530 unsigned NumElts = VT->getNumElements();
531 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
533 unsigned NumSubElts = NumElts / Factor;
534 VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
536 // Firstly, the cost of load/store operation.
537 unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
538 Opcode, VecTy, Alignment, AddressSpace);
540 // Then plus the cost of interleave operation.
541 if (Opcode == Instruction::Load) {
542 // The interleave cost is similar to extract sub vectors' elements
543 // from the wide vector, and insert them into sub vectors.
545 // E.g. An interleaved load of factor 2 (with one member of index 0):
546 // %vec = load <8 x i32>, <8 x i32>* %ptr
547 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
548 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
549 // <8 x i32> vector and insert them into a <4 x i32> vector.
551 assert(Indices.size() <= Factor &&
552 "Interleaved memory op has too many members");
554 for (unsigned Index : Indices) {
555 assert(Index < Factor && "Invalid index for interleaved memory op");
557 // Extract elements from loaded vector for each sub vector.
558 for (unsigned i = 0; i < NumSubElts; i++)
559 Cost += static_cast<T *>(this)->getVectorInstrCost(
560 Instruction::ExtractElement, VT, Index + i * Factor);
563 unsigned InsSubCost = 0;
564 for (unsigned i = 0; i < NumSubElts; i++)
565 InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
566 Instruction::InsertElement, SubVT, i);
568 Cost += Indices.size() * InsSubCost;
570 // The interleave cost is extract all elements from sub vectors, and
571 // insert them into the wide vector.
573 // E.g. An interleaved store of factor 2:
574 // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
575 // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
576 // The cost is estimated as extract all elements from both <4 x i32>
577 // vectors and insert into the <8 x i32> vector.
579 unsigned ExtSubCost = 0;
580 for (unsigned i = 0; i < NumSubElts; i++)
581 ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
582 Instruction::ExtractElement, SubVT, i);
583 Cost += ExtSubCost * Factor;
585 for (unsigned i = 0; i < NumElts; i++)
586 Cost += static_cast<T *>(this)
587 ->getVectorInstrCost(Instruction::InsertElement, VT, i);
593 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
594 ArrayRef<Type *> Tys) {
598 // Assume that we need to scalarize this intrinsic.
599 unsigned ScalarizationCost = 0;
600 unsigned ScalarCalls = 1;
601 Type *ScalarRetTy = RetTy;
602 if (RetTy->isVectorTy()) {
603 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
604 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
605 ScalarRetTy = RetTy->getScalarType();
607 SmallVector<Type *, 4> ScalarTys;
608 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
610 if (Ty->isVectorTy()) {
611 ScalarizationCost += getScalarizationOverhead(Ty, false, true);
612 ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
613 Ty = Ty->getScalarType();
615 ScalarTys.push_back(Ty);
617 if (ScalarCalls == 1)
618 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
620 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
621 IID, ScalarRetTy, ScalarTys);
623 return ScalarCalls * ScalarCost + ScalarizationCost;
625 // Look for intrinsics that can be lowered directly or turned into a scalar
627 case Intrinsic::sqrt:
639 case Intrinsic::exp2:
645 case Intrinsic::log10:
648 case Intrinsic::log2:
651 case Intrinsic::fabs:
654 case Intrinsic::minnum:
657 case Intrinsic::maxnum:
660 case Intrinsic::copysign:
661 ISD = ISD::FCOPYSIGN;
663 case Intrinsic::floor:
666 case Intrinsic::ceil:
669 case Intrinsic::trunc:
672 case Intrinsic::nearbyint:
673 ISD = ISD::FNEARBYINT;
675 case Intrinsic::rint:
678 case Intrinsic::round:
687 case Intrinsic::fmuladd:
690 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
691 case Intrinsic::lifetime_start:
692 case Intrinsic::lifetime_end:
694 case Intrinsic::masked_store:
695 return static_cast<T *>(this)
696 ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
697 case Intrinsic::masked_load:
698 return static_cast<T *>(this)
699 ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
702 const TargetLoweringBase *TLI = getTLI();
703 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
705 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
706 // The operation is legal. Assume it costs 1.
707 // If the type is split to multiple registers, assume that there is some
709 // TODO: Once we have extract/insert subvector cost we need to use them.
715 if (!TLI->isOperationExpand(ISD, LT.second)) {
716 // If the operation is custom lowered then assume
717 // thare the code is twice as expensive.
721 // If we can't lower fmuladd into an FMA estimate the cost as a floating
722 // point mul followed by an add.
723 if (IID == Intrinsic::fmuladd)
724 return static_cast<T *>(this)
725 ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
726 static_cast<T *>(this)
727 ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
729 // Else, assume that we need to scalarize this intrinsic. For math builtins
730 // this will emit a costly libcall, adding call overhead and spills. Make it
732 if (RetTy->isVectorTy()) {
733 unsigned ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
734 unsigned ScalarCalls = RetTy->getVectorNumElements();
735 SmallVector<Type *, 4> ScalarTys;
736 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
738 if (Ty->isVectorTy())
739 Ty = Ty->getScalarType();
740 ScalarTys.push_back(Ty);
742 unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
743 IID, RetTy->getScalarType(), ScalarTys);
744 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
745 if (Tys[i]->isVectorTy()) {
746 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
747 ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
751 return ScalarCalls * ScalarCost + ScalarizationCost;
754 // This is going to be turned into a library call, make it expensive.
758 /// \brief Compute a cost of the given call instruction.
760 /// Compute the cost of calling function F with return type RetTy and
761 /// argument types Tys. F might be nullptr, in this case the cost of an
762 /// arbitrary call with the specified signature will be returned.
763 /// This is used, for instance, when we estimate call of a vector
764 /// counterpart of the given function.
765 /// \param F Called function, might be nullptr.
766 /// \param RetTy Return value types.
767 /// \param Tys Argument types.
768 /// \returns The cost of Call instruction.
769 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
773 unsigned getNumberOfParts(Type *Tp) {
774 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
778 unsigned getAddressComputationCost(Type *Ty, bool IsComplex) { return 0; }
780 unsigned getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwise) {
781 assert(Ty->isVectorTy() && "Expect a vector type");
782 unsigned NumVecElts = Ty->getVectorNumElements();
783 unsigned NumReduxLevels = Log2_32(NumVecElts);
786 static_cast<T *>(this)->getArithmeticInstrCost(Opcode, Ty);
787 // Assume the pairwise shuffles add a cost.
788 unsigned ShuffleCost =
789 NumReduxLevels * (IsPairwise + 1) *
790 static_cast<T *>(this)
791 ->getShuffleCost(TTI::SK_ExtractSubvector, Ty, NumVecElts / 2, Ty);
792 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
798 /// \brief Concrete BasicTTIImpl that can be used if no further customization
800 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
801 typedef BasicTTIImplBase<BasicTTIImpl> BaseT;
802 friend class BasicTTIImplBase<BasicTTIImpl>;
804 const TargetSubtargetInfo *ST;
805 const TargetLoweringBase *TLI;
807 const TargetSubtargetInfo *getST() const { return ST; }
808 const TargetLoweringBase *getTLI() const { return TLI; }
811 explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
813 // Provide value semantics. MSVC requires that we spell all of these out.
814 BasicTTIImpl(const BasicTTIImpl &Arg)
815 : BaseT(static_cast<const BaseT &>(Arg)), ST(Arg.ST), TLI(Arg.TLI) {}
816 BasicTTIImpl(BasicTTIImpl &&Arg)
817 : BaseT(std::move(static_cast<BaseT &>(Arg))), ST(std::move(Arg.ST)),
818 TLI(std::move(Arg.TLI)) {}