1 //===- BasicTargetTransformInfo.cpp - Basic target-independent TTI impl ---===//
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 the implementation of a basic TargetTransformInfo pass
11 /// predicated on the target abstractions present in the target independent
12 /// code generator. It uses these (primarily TargetLowering) to model as much
13 /// of the TTI query interface as possible. It is included by most targets so
14 /// that they can specialize only a small subset of the query space.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "basictti"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Target/TargetLowering.h"
28 class BasicTTI final : public ImmutablePass, public TargetTransformInfo {
29 const TargetMachine *TM;
31 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
32 /// are set if the result needs to be inserted and/or extracted from vectors.
33 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
35 const TargetLoweringBase *getTLI() const { return TM->getTargetLowering(); }
38 BasicTTI() : ImmutablePass(ID), TM(0) {
39 llvm_unreachable("This pass cannot be directly constructed");
42 BasicTTI(const TargetMachine *TM) : ImmutablePass(ID), TM(TM) {
43 initializeBasicTTIPass(*PassRegistry::getPassRegistry());
46 void initializePass() override {
50 void getAnalysisUsage(AnalysisUsage &AU) const override {
51 TargetTransformInfo::getAnalysisUsage(AU);
54 /// Pass identification.
57 /// Provide necessary pointer adjustments for the two base classes.
58 void *getAdjustedAnalysisPointer(const void *ID) override {
59 if (ID == &TargetTransformInfo::ID)
60 return (TargetTransformInfo*)this;
64 bool hasBranchDivergence() const override;
66 /// \name Scalar TTI Implementations
69 bool isLegalAddImmediate(int64_t imm) const override;
70 bool isLegalICmpImmediate(int64_t imm) const override;
71 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
72 int64_t BaseOffset, bool HasBaseReg,
73 int64_t Scale) const override;
74 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
75 int64_t BaseOffset, bool HasBaseReg,
76 int64_t Scale) const override;
77 bool isTruncateFree(Type *Ty1, Type *Ty2) const override;
78 bool isTypeLegal(Type *Ty) const override;
79 unsigned getJumpBufAlignment() const override;
80 unsigned getJumpBufSize() const override;
81 bool shouldBuildLookupTables() const override;
82 bool haveFastSqrt(Type *Ty) const override;
83 void getUnrollingPreferences(Loop *L,
84 UnrollingPreferences &UP) const override;
88 /// \name Vector TTI Implementations
91 unsigned getNumberOfRegisters(bool Vector) const override;
92 unsigned getMaximumUnrollFactor() const override;
93 unsigned getRegisterBitWidth(bool Vector) const override;
94 unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind,
95 OperandValueKind) const override;
96 unsigned getShuffleCost(ShuffleKind Kind, Type *Tp,
97 int Index, Type *SubTp) const override;
98 unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
99 Type *Src) const override;
100 unsigned getCFInstrCost(unsigned Opcode) const override;
101 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
102 Type *CondTy) const override;
103 unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
104 unsigned Index) const override;
105 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
106 unsigned AddressSpace) const override;
107 unsigned getIntrinsicInstrCost(Intrinsic::ID, Type *RetTy,
108 ArrayRef<Type*> Tys) const override;
109 unsigned getNumberOfParts(Type *Tp) const override;
110 unsigned getAddressComputationCost( Type *Ty, bool IsComplex) const override;
111 unsigned getReductionCost(unsigned Opcode, Type *Ty,
112 bool IsPairwise) const override;
119 INITIALIZE_AG_PASS(BasicTTI, TargetTransformInfo, "basictti",
120 "Target independent code generator's TTI", true, true, false)
121 char BasicTTI::ID = 0;
124 llvm::createBasicTargetTransformInfoPass(const TargetMachine *TM) {
125 return new BasicTTI(TM);
128 bool BasicTTI::hasBranchDivergence() const { return false; }
130 bool BasicTTI::isLegalAddImmediate(int64_t imm) const {
131 return getTLI()->isLegalAddImmediate(imm);
134 bool BasicTTI::isLegalICmpImmediate(int64_t imm) const {
135 return getTLI()->isLegalICmpImmediate(imm);
138 bool BasicTTI::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
139 int64_t BaseOffset, bool HasBaseReg,
140 int64_t Scale) const {
141 TargetLoweringBase::AddrMode AM;
143 AM.BaseOffs = BaseOffset;
144 AM.HasBaseReg = HasBaseReg;
146 return getTLI()->isLegalAddressingMode(AM, Ty);
149 int BasicTTI::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
150 int64_t BaseOffset, bool HasBaseReg,
151 int64_t Scale) const {
152 TargetLoweringBase::AddrMode AM;
154 AM.BaseOffs = BaseOffset;
155 AM.HasBaseReg = HasBaseReg;
157 return getTLI()->getScalingFactorCost(AM, Ty);
160 bool BasicTTI::isTruncateFree(Type *Ty1, Type *Ty2) const {
161 return getTLI()->isTruncateFree(Ty1, Ty2);
164 bool BasicTTI::isTypeLegal(Type *Ty) const {
165 EVT T = getTLI()->getValueType(Ty);
166 return getTLI()->isTypeLegal(T);
169 unsigned BasicTTI::getJumpBufAlignment() const {
170 return getTLI()->getJumpBufAlignment();
173 unsigned BasicTTI::getJumpBufSize() const {
174 return getTLI()->getJumpBufSize();
177 bool BasicTTI::shouldBuildLookupTables() const {
178 const TargetLoweringBase *TLI = getTLI();
179 return TLI->supportJumpTables() &&
180 (TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
181 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
184 bool BasicTTI::haveFastSqrt(Type *Ty) const {
185 const TargetLoweringBase *TLI = getTLI();
186 EVT VT = TLI->getValueType(Ty);
187 return TLI->isTypeLegal(VT) && TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
190 void BasicTTI::getUnrollingPreferences(Loop *, UnrollingPreferences &) const { }
192 //===----------------------------------------------------------------------===//
194 // Calls used by the vectorizers.
196 //===----------------------------------------------------------------------===//
198 unsigned BasicTTI::getScalarizationOverhead(Type *Ty, bool Insert,
199 bool Extract) const {
200 assert (Ty->isVectorTy() && "Can only scalarize vectors");
203 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
205 Cost += TopTTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
207 Cost += TopTTI->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
213 unsigned BasicTTI::getNumberOfRegisters(bool Vector) const {
217 unsigned BasicTTI::getRegisterBitWidth(bool Vector) const {
221 unsigned BasicTTI::getMaximumUnrollFactor() const {
225 unsigned BasicTTI::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
227 OperandValueKind) const {
228 // Check if any of the operands are vector operands.
229 const TargetLoweringBase *TLI = getTLI();
230 int ISD = TLI->InstructionOpcodeToISD(Opcode);
231 assert(ISD && "Invalid opcode");
233 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Ty);
235 bool IsFloat = Ty->getScalarType()->isFloatingPointTy();
236 // Assume that floating point arithmetic operations cost twice as much as
237 // integer operations.
238 unsigned OpCost = (IsFloat ? 2 : 1);
240 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
241 // The operation is legal. Assume it costs 1.
242 // If the type is split to multiple registers, assume that there is some
244 // TODO: Once we have extract/insert subvector cost we need to use them.
246 return LT.first * 2 * OpCost;
247 return LT.first * 1 * OpCost;
250 if (!TLI->isOperationExpand(ISD, LT.second)) {
251 // If the operation is custom lowered then assume
252 // thare the code is twice as expensive.
253 return LT.first * 2 * OpCost;
256 // Else, assume that we need to scalarize this op.
257 if (Ty->isVectorTy()) {
258 unsigned Num = Ty->getVectorNumElements();
259 unsigned Cost = TopTTI->getArithmeticInstrCost(Opcode, Ty->getScalarType());
260 // return the cost of multiple scalar invocation plus the cost of inserting
261 // and extracting the values.
262 return getScalarizationOverhead(Ty, true, true) + Num * Cost;
265 // We don't know anything about this scalar instruction.
269 unsigned BasicTTI::getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
274 unsigned BasicTTI::getCastInstrCost(unsigned Opcode, Type *Dst,
276 const TargetLoweringBase *TLI = getTLI();
277 int ISD = TLI->InstructionOpcodeToISD(Opcode);
278 assert(ISD && "Invalid opcode");
280 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(Src);
281 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(Dst);
283 // Check for NOOP conversions.
284 if (SrcLT.first == DstLT.first &&
285 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
287 // Bitcast between types that are legalized to the same type are free.
288 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
292 if (Opcode == Instruction::Trunc &&
293 TLI->isTruncateFree(SrcLT.second, DstLT.second))
296 if (Opcode == Instruction::ZExt &&
297 TLI->isZExtFree(SrcLT.second, DstLT.second))
300 // If the cast is marked as legal (or promote) then assume low cost.
301 if (TLI->isOperationLegalOrPromote(ISD, DstLT.second))
304 // Handle scalar conversions.
305 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
307 // Scalar bitcasts are usually free.
308 if (Opcode == Instruction::BitCast)
311 // Just check the op cost. If the operation is legal then assume it costs 1.
312 if (!TLI->isOperationExpand(ISD, DstLT.second))
315 // Assume that illegal scalar instruction are expensive.
319 // Check vector-to-vector casts.
320 if (Dst->isVectorTy() && Src->isVectorTy()) {
322 // If the cast is between same-sized registers, then the check is simple.
323 if (SrcLT.first == DstLT.first &&
324 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
326 // Assume that Zext is done using AND.
327 if (Opcode == Instruction::ZExt)
330 // Assume that sext is done using SHL and SRA.
331 if (Opcode == Instruction::SExt)
334 // Just check the op cost. If the operation is legal then assume it costs
335 // 1 and multiply by the type-legalization overhead.
336 if (!TLI->isOperationExpand(ISD, DstLT.second))
337 return SrcLT.first * 1;
340 // If we are converting vectors and the operation is illegal, or
341 // if the vectors are legalized to different types, estimate the
342 // scalarization costs.
343 unsigned Num = Dst->getVectorNumElements();
344 unsigned Cost = TopTTI->getCastInstrCost(Opcode, Dst->getScalarType(),
345 Src->getScalarType());
347 // Return the cost of multiple scalar invocation plus the cost of
348 // inserting and extracting the values.
349 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
352 // We already handled vector-to-vector and scalar-to-scalar conversions. This
353 // is where we handle bitcast between vectors and scalars. We need to assume
354 // that the conversion is scalarized in one way or another.
355 if (Opcode == Instruction::BitCast)
356 // Illegal bitcasts are done by storing and loading from a stack slot.
357 return (Src->isVectorTy()? getScalarizationOverhead(Src, false, true):0) +
358 (Dst->isVectorTy()? getScalarizationOverhead(Dst, true, false):0);
360 llvm_unreachable("Unhandled cast");
363 unsigned BasicTTI::getCFInstrCost(unsigned Opcode) const {
364 // Branches are assumed to be predicted.
368 unsigned BasicTTI::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
369 Type *CondTy) const {
370 const TargetLoweringBase *TLI = getTLI();
371 int ISD = TLI->InstructionOpcodeToISD(Opcode);
372 assert(ISD && "Invalid opcode");
374 // Selects on vectors are actually vector selects.
375 if (ISD == ISD::SELECT) {
376 assert(CondTy && "CondTy must exist");
377 if (CondTy->isVectorTy())
381 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(ValTy);
383 if (!TLI->isOperationExpand(ISD, LT.second)) {
384 // The operation is legal. Assume it costs 1. Multiply
385 // by the type-legalization overhead.
389 // Otherwise, assume that the cast is scalarized.
390 if (ValTy->isVectorTy()) {
391 unsigned Num = ValTy->getVectorNumElements();
393 CondTy = CondTy->getScalarType();
394 unsigned Cost = TopTTI->getCmpSelInstrCost(Opcode, ValTy->getScalarType(),
397 // Return the cost of multiple scalar invocation plus the cost of inserting
398 // and extracting the values.
399 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
402 // Unknown scalar opcode.
406 unsigned BasicTTI::getVectorInstrCost(unsigned Opcode, Type *Val,
407 unsigned Index) const {
411 unsigned BasicTTI::getMemoryOpCost(unsigned Opcode, Type *Src,
413 unsigned AddressSpace) const {
414 assert(!Src->isVoidTy() && "Invalid type");
415 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Src);
417 // Assume that all loads of legal types cost 1.
421 unsigned BasicTTI::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
422 ArrayRef<Type *> Tys) const {
426 // Assume that we need to scalarize this intrinsic.
427 unsigned ScalarizationCost = 0;
428 unsigned ScalarCalls = 1;
429 if (RetTy->isVectorTy()) {
430 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
431 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
433 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
434 if (Tys[i]->isVectorTy()) {
435 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
436 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
440 return ScalarCalls + ScalarizationCost;
442 // Look for intrinsics that can be lowered directly or turned into a scalar
444 case Intrinsic::sqrt: ISD = ISD::FSQRT; break;
445 case Intrinsic::sin: ISD = ISD::FSIN; break;
446 case Intrinsic::cos: ISD = ISD::FCOS; break;
447 case Intrinsic::exp: ISD = ISD::FEXP; break;
448 case Intrinsic::exp2: ISD = ISD::FEXP2; break;
449 case Intrinsic::log: ISD = ISD::FLOG; break;
450 case Intrinsic::log10: ISD = ISD::FLOG10; break;
451 case Intrinsic::log2: ISD = ISD::FLOG2; break;
452 case Intrinsic::fabs: ISD = ISD::FABS; break;
453 case Intrinsic::copysign: ISD = ISD::FCOPYSIGN; break;
454 case Intrinsic::floor: ISD = ISD::FFLOOR; break;
455 case Intrinsic::ceil: ISD = ISD::FCEIL; break;
456 case Intrinsic::trunc: ISD = ISD::FTRUNC; break;
457 case Intrinsic::nearbyint:
458 ISD = ISD::FNEARBYINT; break;
459 case Intrinsic::rint: ISD = ISD::FRINT; break;
460 case Intrinsic::round: ISD = ISD::FROUND; break;
461 case Intrinsic::pow: ISD = ISD::FPOW; break;
462 case Intrinsic::fma: ISD = ISD::FMA; break;
463 case Intrinsic::fmuladd: ISD = ISD::FMA; break; // FIXME: mul + add?
464 case Intrinsic::lifetime_start:
465 case Intrinsic::lifetime_end:
469 const TargetLoweringBase *TLI = getTLI();
470 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(RetTy);
472 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
473 // The operation is legal. Assume it costs 1.
474 // If the type is split to multiple registers, assume that thre is some
476 // TODO: Once we have extract/insert subvector cost we need to use them.
482 if (!TLI->isOperationExpand(ISD, LT.second)) {
483 // If the operation is custom lowered then assume
484 // thare the code is twice as expensive.
488 // Else, assume that we need to scalarize this intrinsic. For math builtins
489 // this will emit a costly libcall, adding call overhead and spills. Make it
491 if (RetTy->isVectorTy()) {
492 unsigned Num = RetTy->getVectorNumElements();
493 unsigned Cost = TopTTI->getIntrinsicInstrCost(IID, RetTy->getScalarType(),
495 return 10 * Cost * Num;
498 // This is going to be turned into a library call, make it expensive.
502 unsigned BasicTTI::getNumberOfParts(Type *Tp) const {
503 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Tp);
507 unsigned BasicTTI::getAddressComputationCost(Type *Ty, bool IsComplex) const {
511 unsigned BasicTTI::getReductionCost(unsigned Opcode, Type *Ty,
512 bool IsPairwise) const {
513 assert(Ty->isVectorTy() && "Expect a vector type");
514 unsigned NumVecElts = Ty->getVectorNumElements();
515 unsigned NumReduxLevels = Log2_32(NumVecElts);
516 unsigned ArithCost = NumReduxLevels *
517 TopTTI->getArithmeticInstrCost(Opcode, Ty);
518 // Assume the pairwise shuffles add a cost.
519 unsigned ShuffleCost =
520 NumReduxLevels * (IsPairwise + 1) *
521 TopTTI->getShuffleCost(SK_ExtractSubvector, Ty, NumVecElts / 2, Ty);
522 return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);