[Alignment][NFC] Support compile time constants
[llvm-core.git] / include / llvm / CodeGen / BasicTTIImpl.h
blobf73976dbacf950b637d0316155fc2e14f4b24291
1 //===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This file provides a helper that implements much of the TTI interface in
11 /// terms of the target-independent code generator and TargetLowering
12 /// interfaces.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
17 #define LLVM_CODEGEN_BASICTTIIMPL_H
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/Analysis/TargetTransformInfoImpl.h"
27 #include "llvm/CodeGen/ISDOpcodes.h"
28 #include "llvm/CodeGen/TargetLowering.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/CallSite.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Operator.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/MC/MCSchedule.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MachineValueType.h"
49 #include "llvm/Support/MathExtras.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <cstdint>
53 #include <limits>
54 #include <utility>
56 namespace llvm {
58 class Function;
59 class GlobalValue;
60 class LLVMContext;
61 class ScalarEvolution;
62 class SCEV;
63 class TargetMachine;
65 extern cl::opt<unsigned> PartialUnrollingThreshold;
67 /// Base class which can be used to help build a TTI implementation.
68 ///
69 /// This class provides as much implementation of the TTI interface as is
70 /// possible using the target independent parts of the code generator.
71 ///
72 /// In order to subclass it, your class must implement a getST() method to
73 /// return the subtarget, and a getTLI() method to return the target lowering.
74 /// We need these methods implemented in the derived class so that this class
75 /// doesn't have to duplicate storage for them.
76 template <typename T>
77 class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
78 private:
79 using BaseT = TargetTransformInfoImplCRTPBase<T>;
80 using TTI = TargetTransformInfo;
82 /// Estimate a cost of Broadcast as an extract and sequence of insert
83 /// operations.
84 unsigned getBroadcastShuffleOverhead(Type *Ty) {
85 assert(Ty->isVectorTy() && "Can only shuffle vectors");
86 unsigned Cost = 0;
87 // Broadcast cost is equal to the cost of extracting the zero'th element
88 // plus the cost of inserting it into every element of the result vector.
89 Cost += static_cast<T *>(this)->getVectorInstrCost(
90 Instruction::ExtractElement, Ty, 0);
92 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
93 Cost += static_cast<T *>(this)->getVectorInstrCost(
94 Instruction::InsertElement, Ty, i);
96 return Cost;
99 /// Estimate a cost of shuffle as a sequence of extract and insert
100 /// operations.
101 unsigned getPermuteShuffleOverhead(Type *Ty) {
102 assert(Ty->isVectorTy() && "Can only shuffle vectors");
103 unsigned Cost = 0;
104 // Shuffle cost is equal to the cost of extracting element from its argument
105 // plus the cost of inserting them onto the result vector.
107 // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
108 // index 0 of first vector, index 1 of second vector,index 2 of first
109 // vector and finally index 3 of second vector and insert them at index
110 // <0,1,2,3> of result vector.
111 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
112 Cost += static_cast<T *>(this)
113 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
114 Cost += static_cast<T *>(this)
115 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
117 return Cost;
120 /// Estimate a cost of subvector extraction as a sequence of extract and
121 /// insert operations.
122 unsigned getExtractSubvectorOverhead(Type *Ty, int Index, Type *SubTy) {
123 assert(Ty && Ty->isVectorTy() && SubTy && SubTy->isVectorTy() &&
124 "Can only extract subvectors from vectors");
125 int NumSubElts = SubTy->getVectorNumElements();
126 assert((Index + NumSubElts) <= (int)Ty->getVectorNumElements() &&
127 "SK_ExtractSubvector index out of range");
129 unsigned Cost = 0;
130 // Subvector extraction cost is equal to the cost of extracting element from
131 // the source type plus the cost of inserting them into the result vector
132 // type.
133 for (int i = 0; i != NumSubElts; ++i) {
134 Cost += static_cast<T *>(this)->getVectorInstrCost(
135 Instruction::ExtractElement, Ty, i + Index);
136 Cost += static_cast<T *>(this)->getVectorInstrCost(
137 Instruction::InsertElement, SubTy, i);
139 return Cost;
142 /// Estimate a cost of subvector insertion as a sequence of extract and
143 /// insert operations.
144 unsigned getInsertSubvectorOverhead(Type *Ty, int Index, Type *SubTy) {
145 assert(Ty && Ty->isVectorTy() && SubTy && SubTy->isVectorTy() &&
146 "Can only insert subvectors into vectors");
147 int NumSubElts = SubTy->getVectorNumElements();
148 assert((Index + NumSubElts) <= (int)Ty->getVectorNumElements() &&
149 "SK_InsertSubvector index out of range");
151 unsigned Cost = 0;
152 // Subvector insertion cost is equal to the cost of extracting element from
153 // the source type plus the cost of inserting them into the result vector
154 // type.
155 for (int i = 0; i != NumSubElts; ++i) {
156 Cost += static_cast<T *>(this)->getVectorInstrCost(
157 Instruction::ExtractElement, SubTy, i);
158 Cost += static_cast<T *>(this)->getVectorInstrCost(
159 Instruction::InsertElement, Ty, i + Index);
161 return Cost;
164 /// Local query method delegates up to T which *must* implement this!
165 const TargetSubtargetInfo *getST() const {
166 return static_cast<const T *>(this)->getST();
169 /// Local query method delegates up to T which *must* implement this!
170 const TargetLoweringBase *getTLI() const {
171 return static_cast<const T *>(this)->getTLI();
174 static ISD::MemIndexedMode getISDIndexedMode(TTI::MemIndexedMode M) {
175 switch (M) {
176 case TTI::MIM_Unindexed:
177 return ISD::UNINDEXED;
178 case TTI::MIM_PreInc:
179 return ISD::PRE_INC;
180 case TTI::MIM_PreDec:
181 return ISD::PRE_DEC;
182 case TTI::MIM_PostInc:
183 return ISD::POST_INC;
184 case TTI::MIM_PostDec:
185 return ISD::POST_DEC;
187 llvm_unreachable("Unexpected MemIndexedMode");
190 protected:
191 explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
192 : BaseT(DL) {}
193 virtual ~BasicTTIImplBase() = default;
195 using TargetTransformInfoImplBase::DL;
197 public:
198 /// \name Scalar TTI Implementations
199 /// @{
200 bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth,
201 unsigned AddressSpace, unsigned Alignment,
202 bool *Fast) const {
203 EVT E = EVT::getIntegerVT(Context, BitWidth);
204 return getTLI()->allowsMisalignedMemoryAccesses(
205 E, AddressSpace, Alignment, MachineMemOperand::MONone, Fast);
208 bool hasBranchDivergence() { return false; }
210 bool isSourceOfDivergence(const Value *V) { return false; }
212 bool isAlwaysUniform(const Value *V) { return false; }
214 unsigned getFlatAddressSpace() {
215 // Return an invalid address space.
216 return -1;
219 bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
220 Intrinsic::ID IID) const {
221 return false;
224 bool rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
225 Value *OldV, Value *NewV) const {
226 return false;
229 bool isLegalAddImmediate(int64_t imm) {
230 return getTLI()->isLegalAddImmediate(imm);
233 bool isLegalICmpImmediate(int64_t imm) {
234 return getTLI()->isLegalICmpImmediate(imm);
237 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
238 bool HasBaseReg, int64_t Scale,
239 unsigned AddrSpace, Instruction *I = nullptr) {
240 TargetLoweringBase::AddrMode AM;
241 AM.BaseGV = BaseGV;
242 AM.BaseOffs = BaseOffset;
243 AM.HasBaseReg = HasBaseReg;
244 AM.Scale = Scale;
245 return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
248 bool isIndexedLoadLegal(TTI::MemIndexedMode M, Type *Ty,
249 const DataLayout &DL) const {
250 EVT VT = getTLI()->getValueType(DL, Ty);
251 return getTLI()->isIndexedLoadLegal(getISDIndexedMode(M), VT);
254 bool isIndexedStoreLegal(TTI::MemIndexedMode M, Type *Ty,
255 const DataLayout &DL) const {
256 EVT VT = getTLI()->getValueType(DL, Ty);
257 return getTLI()->isIndexedStoreLegal(getISDIndexedMode(M), VT);
260 bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
261 return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
264 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
265 bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
266 TargetLoweringBase::AddrMode AM;
267 AM.BaseGV = BaseGV;
268 AM.BaseOffs = BaseOffset;
269 AM.HasBaseReg = HasBaseReg;
270 AM.Scale = Scale;
271 return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
274 bool isTruncateFree(Type *Ty1, Type *Ty2) {
275 return getTLI()->isTruncateFree(Ty1, Ty2);
278 bool isProfitableToHoist(Instruction *I) {
279 return getTLI()->isProfitableToHoist(I);
282 bool useAA() const { return getST()->useAA(); }
284 bool isTypeLegal(Type *Ty) {
285 EVT VT = getTLI()->getValueType(DL, Ty);
286 return getTLI()->isTypeLegal(VT);
289 int getGEPCost(Type *PointeeType, const Value *Ptr,
290 ArrayRef<const Value *> Operands) {
291 return BaseT::getGEPCost(PointeeType, Ptr, Operands);
294 int getExtCost(const Instruction *I, const Value *Src) {
295 if (getTLI()->isExtFree(I))
296 return TargetTransformInfo::TCC_Free;
298 if (isa<ZExtInst>(I) || isa<SExtInst>(I))
299 if (const LoadInst *LI = dyn_cast<LoadInst>(Src))
300 if (getTLI()->isExtLoad(LI, I, DL))
301 return TargetTransformInfo::TCC_Free;
303 return TargetTransformInfo::TCC_Basic;
306 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
307 ArrayRef<const Value *> Arguments, const User *U) {
308 return BaseT::getIntrinsicCost(IID, RetTy, Arguments, U);
311 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
312 ArrayRef<Type *> ParamTys, const User *U) {
313 if (IID == Intrinsic::cttz) {
314 if (getTLI()->isCheapToSpeculateCttz())
315 return TargetTransformInfo::TCC_Basic;
316 return TargetTransformInfo::TCC_Expensive;
319 if (IID == Intrinsic::ctlz) {
320 if (getTLI()->isCheapToSpeculateCtlz())
321 return TargetTransformInfo::TCC_Basic;
322 return TargetTransformInfo::TCC_Expensive;
325 return BaseT::getIntrinsicCost(IID, RetTy, ParamTys, U);
328 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
329 unsigned &JumpTableSize) {
330 /// Try to find the estimated number of clusters. Note that the number of
331 /// clusters identified in this function could be different from the actual
332 /// numbers found in lowering. This function ignore switches that are
333 /// lowered with a mix of jump table / bit test / BTree. This function was
334 /// initially intended to be used when estimating the cost of switch in
335 /// inline cost heuristic, but it's a generic cost model to be used in other
336 /// places (e.g., in loop unrolling).
337 unsigned N = SI.getNumCases();
338 const TargetLoweringBase *TLI = getTLI();
339 const DataLayout &DL = this->getDataLayout();
341 JumpTableSize = 0;
342 bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
344 // Early exit if both a jump table and bit test are not allowed.
345 if (N < 1 || (!IsJTAllowed && DL.getIndexSizeInBits(0u) < N))
346 return N;
348 APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
349 APInt MinCaseVal = MaxCaseVal;
350 for (auto CI : SI.cases()) {
351 const APInt &CaseVal = CI.getCaseValue()->getValue();
352 if (CaseVal.sgt(MaxCaseVal))
353 MaxCaseVal = CaseVal;
354 if (CaseVal.slt(MinCaseVal))
355 MinCaseVal = CaseVal;
358 // Check if suitable for a bit test
359 if (N <= DL.getIndexSizeInBits(0u)) {
360 SmallPtrSet<const BasicBlock *, 4> Dests;
361 for (auto I : SI.cases())
362 Dests.insert(I.getCaseSuccessor());
364 if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
365 DL))
366 return 1;
369 // Check if suitable for a jump table.
370 if (IsJTAllowed) {
371 if (N < 2 || N < TLI->getMinimumJumpTableEntries())
372 return N;
373 uint64_t Range =
374 (MaxCaseVal - MinCaseVal)
375 .getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
376 // Check whether a range of clusters is dense enough for a jump table
377 if (TLI->isSuitableForJumpTable(&SI, N, Range)) {
378 JumpTableSize = Range;
379 return 1;
382 return N;
385 bool shouldBuildLookupTables() {
386 const TargetLoweringBase *TLI = getTLI();
387 return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
388 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
391 bool haveFastSqrt(Type *Ty) {
392 const TargetLoweringBase *TLI = getTLI();
393 EVT VT = TLI->getValueType(DL, Ty);
394 return TLI->isTypeLegal(VT) &&
395 TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
398 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
399 return true;
402 unsigned getFPOpCost(Type *Ty) {
403 // Check whether FADD is available, as a proxy for floating-point in
404 // general.
405 const TargetLoweringBase *TLI = getTLI();
406 EVT VT = TLI->getValueType(DL, Ty);
407 if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
408 return TargetTransformInfo::TCC_Basic;
409 return TargetTransformInfo::TCC_Expensive;
412 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
413 const TargetLoweringBase *TLI = getTLI();
414 switch (Opcode) {
415 default: break;
416 case Instruction::Trunc:
417 if (TLI->isTruncateFree(OpTy, Ty))
418 return TargetTransformInfo::TCC_Free;
419 return TargetTransformInfo::TCC_Basic;
420 case Instruction::ZExt:
421 if (TLI->isZExtFree(OpTy, Ty))
422 return TargetTransformInfo::TCC_Free;
423 return TargetTransformInfo::TCC_Basic;
425 case Instruction::AddrSpaceCast:
426 if (TLI->isFreeAddrSpaceCast(OpTy->getPointerAddressSpace(),
427 Ty->getPointerAddressSpace()))
428 return TargetTransformInfo::TCC_Free;
429 return TargetTransformInfo::TCC_Basic;
432 return BaseT::getOperationCost(Opcode, Ty, OpTy);
435 unsigned getInliningThresholdMultiplier() { return 1; }
437 int getInlinerVectorBonusPercent() { return 150; }
439 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
440 TTI::UnrollingPreferences &UP) {
441 // This unrolling functionality is target independent, but to provide some
442 // motivation for its intended use, for x86:
444 // According to the Intel 64 and IA-32 Architectures Optimization Reference
445 // Manual, Intel Core models and later have a loop stream detector (and
446 // associated uop queue) that can benefit from partial unrolling.
447 // The relevant requirements are:
448 // - The loop must have no more than 4 (8 for Nehalem and later) branches
449 // taken, and none of them may be calls.
450 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
452 // According to the Software Optimization Guide for AMD Family 15h
453 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
454 // and loop buffer which can benefit from partial unrolling.
455 // The relevant requirements are:
456 // - The loop must have fewer than 16 branches
457 // - The loop must have less than 40 uops in all executed loop branches
459 // The number of taken branches in a loop is hard to estimate here, and
460 // benchmarking has revealed that it is better not to be conservative when
461 // estimating the branch count. As a result, we'll ignore the branch limits
462 // until someone finds a case where it matters in practice.
464 unsigned MaxOps;
465 const TargetSubtargetInfo *ST = getST();
466 if (PartialUnrollingThreshold.getNumOccurrences() > 0)
467 MaxOps = PartialUnrollingThreshold;
468 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
469 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
470 else
471 return;
473 // Scan the loop: don't unroll loops with calls.
474 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
475 ++I) {
476 BasicBlock *BB = *I;
478 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
479 if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
480 ImmutableCallSite CS(&*J);
481 if (const Function *F = CS.getCalledFunction()) {
482 if (!static_cast<T *>(this)->isLoweredToCall(F))
483 continue;
486 return;
490 // Enable runtime and partial unrolling up to the specified size.
491 // Enable using trip count upper bound to unroll loops.
492 UP.Partial = UP.Runtime = UP.UpperBound = true;
493 UP.PartialThreshold = MaxOps;
495 // Avoid unrolling when optimizing for size.
496 UP.OptSizeThreshold = 0;
497 UP.PartialOptSizeThreshold = 0;
499 // Set number of instructions optimized when "back edge"
500 // becomes "fall through" to default value of 2.
501 UP.BEInsns = 2;
504 bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
505 AssumptionCache &AC,
506 TargetLibraryInfo *LibInfo,
507 HardwareLoopInfo &HWLoopInfo) {
508 return BaseT::isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
511 int getInstructionLatency(const Instruction *I) {
512 if (isa<LoadInst>(I))
513 return getST()->getSchedModel().DefaultLoadLatency;
515 return BaseT::getInstructionLatency(I);
518 virtual Optional<unsigned>
519 getCacheSize(TargetTransformInfo::CacheLevel Level) const {
520 return Optional<unsigned>(
521 getST()->getCacheSize(static_cast<unsigned>(Level)));
524 virtual Optional<unsigned>
525 getCacheAssociativity(TargetTransformInfo::CacheLevel Level) const {
526 Optional<unsigned> TargetResult =
527 getST()->getCacheAssociativity(static_cast<unsigned>(Level));
529 if (TargetResult)
530 return TargetResult;
532 return BaseT::getCacheAssociativity(Level);
535 virtual unsigned getCacheLineSize() const {
536 return getST()->getCacheLineSize();
539 virtual unsigned getPrefetchDistance() const {
540 return getST()->getPrefetchDistance();
543 virtual unsigned getMinPrefetchStride() const {
544 return getST()->getMinPrefetchStride();
547 virtual unsigned getMaxPrefetchIterationsAhead() const {
548 return getST()->getMaxPrefetchIterationsAhead();
551 /// @}
553 /// \name Vector TTI Implementations
554 /// @{
556 unsigned getRegisterBitWidth(bool Vector) const { return 32; }
558 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
559 /// are set if the result needs to be inserted and/or extracted from vectors.
560 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
561 assert(Ty->isVectorTy() && "Can only scalarize vectors");
562 unsigned Cost = 0;
564 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
565 if (Insert)
566 Cost += static_cast<T *>(this)
567 ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
568 if (Extract)
569 Cost += static_cast<T *>(this)
570 ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
573 return Cost;
576 /// Estimate the overhead of scalarizing an instructions unique
577 /// non-constant operands. The types of the arguments are ordinarily
578 /// scalar, in which case the costs are multiplied with VF.
579 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
580 unsigned VF) {
581 unsigned Cost = 0;
582 SmallPtrSet<const Value*, 4> UniqueOperands;
583 for (const Value *A : Args) {
584 if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
585 Type *VecTy = nullptr;
586 if (A->getType()->isVectorTy()) {
587 VecTy = A->getType();
588 // If A is a vector operand, VF should be 1 or correspond to A.
589 assert((VF == 1 || VF == VecTy->getVectorNumElements()) &&
590 "Vector argument does not match VF");
592 else
593 VecTy = VectorType::get(A->getType(), VF);
595 Cost += getScalarizationOverhead(VecTy, false, true);
599 return Cost;
602 unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
603 assert(VecTy->isVectorTy());
605 unsigned Cost = 0;
607 Cost += getScalarizationOverhead(VecTy, true, false);
608 if (!Args.empty())
609 Cost += getOperandsScalarizationOverhead(Args,
610 VecTy->getVectorNumElements());
611 else
612 // When no information on arguments is provided, we add the cost
613 // associated with one argument as a heuristic.
614 Cost += getScalarizationOverhead(VecTy, false, true);
616 return Cost;
619 unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
621 unsigned getArithmeticInstrCost(
622 unsigned Opcode, Type *Ty,
623 TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
624 TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
625 TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
626 TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
627 ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
628 // Check if any of the operands are vector operands.
629 const TargetLoweringBase *TLI = getTLI();
630 int ISD = TLI->InstructionOpcodeToISD(Opcode);
631 assert(ISD && "Invalid opcode");
633 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
635 bool IsFloat = Ty->isFPOrFPVectorTy();
636 // Assume that floating point arithmetic operations cost twice as much as
637 // integer operations.
638 unsigned OpCost = (IsFloat ? 2 : 1);
640 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
641 // The operation is legal. Assume it costs 1.
642 // TODO: Once we have extract/insert subvector cost we need to use them.
643 return LT.first * OpCost;
646 if (!TLI->isOperationExpand(ISD, LT.second)) {
647 // If the operation is custom lowered, then assume that the code is twice
648 // as expensive.
649 return LT.first * 2 * OpCost;
652 // Else, assume that we need to scalarize this op.
653 // TODO: If one of the types get legalized by splitting, handle this
654 // similarly to what getCastInstrCost() does.
655 if (Ty->isVectorTy()) {
656 unsigned Num = Ty->getVectorNumElements();
657 unsigned Cost = static_cast<T *>(this)
658 ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
659 // Return the cost of multiple scalar invocation plus the cost of
660 // inserting and extracting the values.
661 return getScalarizationOverhead(Ty, Args) + Num * Cost;
664 // We don't know anything about this scalar instruction.
665 return OpCost;
668 unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
669 Type *SubTp) {
670 switch (Kind) {
671 case TTI::SK_Broadcast:
672 return getBroadcastShuffleOverhead(Tp);
673 case TTI::SK_Select:
674 case TTI::SK_Reverse:
675 case TTI::SK_Transpose:
676 case TTI::SK_PermuteSingleSrc:
677 case TTI::SK_PermuteTwoSrc:
678 return getPermuteShuffleOverhead(Tp);
679 case TTI::SK_ExtractSubvector:
680 return getExtractSubvectorOverhead(Tp, Index, SubTp);
681 case TTI::SK_InsertSubvector:
682 return getInsertSubvectorOverhead(Tp, Index, SubTp);
684 llvm_unreachable("Unknown TTI::ShuffleKind");
687 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
688 const Instruction *I = nullptr) {
689 const TargetLoweringBase *TLI = getTLI();
690 int ISD = TLI->InstructionOpcodeToISD(Opcode);
691 assert(ISD && "Invalid opcode");
692 std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
693 std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
695 // Check for NOOP conversions.
696 if (SrcLT.first == DstLT.first &&
697 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
699 // Bitcast between types that are legalized to the same type are free.
700 if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
701 return 0;
704 if (Opcode == Instruction::Trunc &&
705 TLI->isTruncateFree(SrcLT.second, DstLT.second))
706 return 0;
708 if (Opcode == Instruction::ZExt &&
709 TLI->isZExtFree(SrcLT.second, DstLT.second))
710 return 0;
712 if (Opcode == Instruction::AddrSpaceCast &&
713 TLI->isFreeAddrSpaceCast(Src->getPointerAddressSpace(),
714 Dst->getPointerAddressSpace()))
715 return 0;
717 // If this is a zext/sext of a load, return 0 if the corresponding
718 // extending load exists on target.
719 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
720 I && isa<LoadInst>(I->getOperand(0))) {
721 EVT ExtVT = EVT::getEVT(Dst);
722 EVT LoadVT = EVT::getEVT(Src);
723 unsigned LType =
724 ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
725 if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
726 return 0;
729 // If the cast is marked as legal (or promote) then assume low cost.
730 if (SrcLT.first == DstLT.first &&
731 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
732 return 1;
734 // Handle scalar conversions.
735 if (!Src->isVectorTy() && !Dst->isVectorTy()) {
736 // Scalar bitcasts are usually free.
737 if (Opcode == Instruction::BitCast)
738 return 0;
740 // Just check the op cost. If the operation is legal then assume it costs
741 // 1.
742 if (!TLI->isOperationExpand(ISD, DstLT.second))
743 return 1;
745 // Assume that illegal scalar instruction are expensive.
746 return 4;
749 // Check vector-to-vector casts.
750 if (Dst->isVectorTy() && Src->isVectorTy()) {
751 // If the cast is between same-sized registers, then the check is simple.
752 if (SrcLT.first == DstLT.first &&
753 SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
755 // Assume that Zext is done using AND.
756 if (Opcode == Instruction::ZExt)
757 return 1;
759 // Assume that sext is done using SHL and SRA.
760 if (Opcode == Instruction::SExt)
761 return 2;
763 // Just check the op cost. If the operation is legal then assume it
764 // costs
765 // 1 and multiply by the type-legalization overhead.
766 if (!TLI->isOperationExpand(ISD, DstLT.second))
767 return SrcLT.first * 1;
770 // If we are legalizing by splitting, query the concrete TTI for the cost
771 // of casting the original vector twice. We also need to factor in the
772 // cost of the split itself. Count that as 1, to be consistent with
773 // TLI->getTypeLegalizationCost().
774 if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
775 TargetLowering::TypeSplitVector) ||
776 (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
777 TargetLowering::TypeSplitVector)) {
778 Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
779 Dst->getVectorNumElements() / 2);
780 Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
781 Src->getVectorNumElements() / 2);
782 T *TTI = static_cast<T *>(this);
783 return TTI->getVectorSplitCost() +
784 (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
787 // In other cases where the source or destination are illegal, assume
788 // the operation will get scalarized.
789 unsigned Num = Dst->getVectorNumElements();
790 unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
791 Opcode, Dst->getScalarType(), Src->getScalarType(), I);
793 // Return the cost of multiple scalar invocation plus the cost of
794 // inserting and extracting the values.
795 return getScalarizationOverhead(Dst, true, true) + Num * Cost;
798 // We already handled vector-to-vector and scalar-to-scalar conversions.
799 // This
800 // is where we handle bitcast between vectors and scalars. We need to assume
801 // that the conversion is scalarized in one way or another.
802 if (Opcode == Instruction::BitCast)
803 // Illegal bitcasts are done by storing and loading from a stack slot.
804 return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
805 : 0) +
806 (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
807 : 0);
809 llvm_unreachable("Unhandled cast");
812 unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
813 VectorType *VecTy, unsigned Index) {
814 return static_cast<T *>(this)->getVectorInstrCost(
815 Instruction::ExtractElement, VecTy, Index) +
816 static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
817 VecTy->getElementType());
820 unsigned getCFInstrCost(unsigned Opcode) {
821 // Branches are assumed to be predicted.
822 return 0;
825 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
826 const Instruction *I) {
827 const TargetLoweringBase *TLI = getTLI();
828 int ISD = TLI->InstructionOpcodeToISD(Opcode);
829 assert(ISD && "Invalid opcode");
831 // Selects on vectors are actually vector selects.
832 if (ISD == ISD::SELECT) {
833 assert(CondTy && "CondTy must exist");
834 if (CondTy->isVectorTy())
835 ISD = ISD::VSELECT;
837 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
839 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
840 !TLI->isOperationExpand(ISD, LT.second)) {
841 // The operation is legal. Assume it costs 1. Multiply
842 // by the type-legalization overhead.
843 return LT.first * 1;
846 // Otherwise, assume that the cast is scalarized.
847 // TODO: If one of the types get legalized by splitting, handle this
848 // similarly to what getCastInstrCost() does.
849 if (ValTy->isVectorTy()) {
850 unsigned Num = ValTy->getVectorNumElements();
851 if (CondTy)
852 CondTy = CondTy->getScalarType();
853 unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
854 Opcode, ValTy->getScalarType(), CondTy, I);
856 // Return the cost of multiple scalar invocation plus the cost of
857 // inserting and extracting the values.
858 return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
861 // Unknown scalar opcode.
862 return 1;
865 unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
866 std::pair<unsigned, MVT> LT =
867 getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
869 return LT.first;
872 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
873 unsigned AddressSpace, const Instruction *I = nullptr) {
874 assert(!Src->isVoidTy() && "Invalid type");
875 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
877 // Assuming that all loads of legal types cost 1.
878 unsigned Cost = LT.first;
880 if (Src->isVectorTy() &&
881 Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
882 // This is a vector load that legalizes to a larger type than the vector
883 // itself. Unless the corresponding extending load or truncating store is
884 // legal, then this will scalarize.
885 TargetLowering::LegalizeAction LA = TargetLowering::Expand;
886 EVT MemVT = getTLI()->getValueType(DL, Src);
887 if (Opcode == Instruction::Store)
888 LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
889 else
890 LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
892 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
893 // This is a vector load/store for some illegal type that is scalarized.
894 // We must account for the cost of building or decomposing the vector.
895 Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
896 Opcode == Instruction::Store);
900 return Cost;
903 unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
904 unsigned Factor,
905 ArrayRef<unsigned> Indices,
906 unsigned Alignment, unsigned AddressSpace,
907 bool UseMaskForCond = false,
908 bool UseMaskForGaps = false) {
909 VectorType *VT = dyn_cast<VectorType>(VecTy);
910 assert(VT && "Expect a vector type for interleaved memory op");
912 unsigned NumElts = VT->getNumElements();
913 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
915 unsigned NumSubElts = NumElts / Factor;
916 VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
918 // Firstly, the cost of load/store operation.
919 unsigned Cost;
920 if (UseMaskForCond || UseMaskForGaps)
921 Cost = static_cast<T *>(this)->getMaskedMemoryOpCost(
922 Opcode, VecTy, Alignment, AddressSpace);
923 else
924 Cost = static_cast<T *>(this)->getMemoryOpCost(Opcode, VecTy, Alignment,
925 AddressSpace);
927 // Legalize the vector type, and get the legalized and unlegalized type
928 // sizes.
929 MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
930 unsigned VecTySize =
931 static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
932 unsigned VecTyLTSize = VecTyLT.getStoreSize();
934 // Return the ceiling of dividing A by B.
935 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
937 // Scale the cost of the memory operation by the fraction of legalized
938 // instructions that will actually be used. We shouldn't account for the
939 // cost of dead instructions since they will be removed.
941 // E.g., An interleaved load of factor 8:
942 // %vec = load <16 x i64>, <16 x i64>* %ptr
943 // %v0 = shufflevector %vec, undef, <0, 8>
945 // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
946 // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
947 // type). The other loads are unused.
949 // We only scale the cost of loads since interleaved store groups aren't
950 // allowed to have gaps.
951 if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
952 // The number of loads of a legal type it will take to represent a load
953 // of the unlegalized vector type.
954 unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
956 // The number of elements of the unlegalized type that correspond to a
957 // single legal instruction.
958 unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
960 // Determine which legal instructions will be used.
961 BitVector UsedInsts(NumLegalInsts, false);
962 for (unsigned Index : Indices)
963 for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
964 UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
966 // Scale the cost of the load by the fraction of legal instructions that
967 // will be used.
968 Cost *= UsedInsts.count() / NumLegalInsts;
971 // Then plus the cost of interleave operation.
972 if (Opcode == Instruction::Load) {
973 // The interleave cost is similar to extract sub vectors' elements
974 // from the wide vector, and insert them into sub vectors.
976 // E.g. An interleaved load of factor 2 (with one member of index 0):
977 // %vec = load <8 x i32>, <8 x i32>* %ptr
978 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
979 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
980 // <8 x i32> vector and insert them into a <4 x i32> vector.
982 assert(Indices.size() <= Factor &&
983 "Interleaved memory op has too many members");
985 for (unsigned Index : Indices) {
986 assert(Index < Factor && "Invalid index for interleaved memory op");
988 // Extract elements from loaded vector for each sub vector.
989 for (unsigned i = 0; i < NumSubElts; i++)
990 Cost += static_cast<T *>(this)->getVectorInstrCost(
991 Instruction::ExtractElement, VT, Index + i * Factor);
994 unsigned InsSubCost = 0;
995 for (unsigned i = 0; i < NumSubElts; i++)
996 InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
997 Instruction::InsertElement, SubVT, i);
999 Cost += Indices.size() * InsSubCost;
1000 } else {
1001 // The interleave cost is extract all elements from sub vectors, and
1002 // insert them into the wide vector.
1004 // E.g. An interleaved store of factor 2:
1005 // %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
1006 // store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
1007 // The cost is estimated as extract all elements from both <4 x i32>
1008 // vectors and insert into the <8 x i32> vector.
1010 unsigned ExtSubCost = 0;
1011 for (unsigned i = 0; i < NumSubElts; i++)
1012 ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
1013 Instruction::ExtractElement, SubVT, i);
1014 Cost += ExtSubCost * Factor;
1016 for (unsigned i = 0; i < NumElts; i++)
1017 Cost += static_cast<T *>(this)
1018 ->getVectorInstrCost(Instruction::InsertElement, VT, i);
1021 if (!UseMaskForCond)
1022 return Cost;
1024 Type *I8Type = Type::getInt8Ty(VT->getContext());
1025 VectorType *MaskVT = VectorType::get(I8Type, NumElts);
1026 SubVT = VectorType::get(I8Type, NumSubElts);
1028 // The Mask shuffling cost is extract all the elements of the Mask
1029 // and insert each of them Factor times into the wide vector:
1031 // E.g. an interleaved group with factor 3:
1032 // %mask = icmp ult <8 x i32> %vec1, %vec2
1033 // %interleaved.mask = shufflevector <8 x i1> %mask, <8 x i1> undef,
1034 // <24 x i32> <0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7>
1035 // The cost is estimated as extract all mask elements from the <8xi1> mask
1036 // vector and insert them factor times into the <24xi1> shuffled mask
1037 // vector.
1038 for (unsigned i = 0; i < NumSubElts; i++)
1039 Cost += static_cast<T *>(this)->getVectorInstrCost(
1040 Instruction::ExtractElement, SubVT, i);
1042 for (unsigned i = 0; i < NumElts; i++)
1043 Cost += static_cast<T *>(this)->getVectorInstrCost(
1044 Instruction::InsertElement, MaskVT, i);
1046 // The Gaps mask is invariant and created outside the loop, therefore the
1047 // cost of creating it is not accounted for here. However if we have both
1048 // a MaskForGaps and some other mask that guards the execution of the
1049 // memory access, we need to account for the cost of And-ing the two masks
1050 // inside the loop.
1051 if (UseMaskForGaps)
1052 Cost += static_cast<T *>(this)->getArithmeticInstrCost(
1053 BinaryOperator::And, MaskVT);
1055 return Cost;
1058 /// Get intrinsic cost based on arguments.
1059 unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
1060 ArrayRef<Value *> Args, FastMathFlags FMF,
1061 unsigned VF = 1) {
1062 unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
1063 assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type");
1064 auto *ConcreteTTI = static_cast<T *>(this);
1066 switch (IID) {
1067 default: {
1068 // Assume that we need to scalarize this intrinsic.
1069 SmallVector<Type *, 4> Types;
1070 for (Value *Op : Args) {
1071 Type *OpTy = Op->getType();
1072 assert(VF == 1 || !OpTy->isVectorTy());
1073 Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
1076 if (VF > 1 && !RetTy->isVoidTy())
1077 RetTy = VectorType::get(RetTy, VF);
1079 // Compute the scalarization overhead based on Args for a vector
1080 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
1081 // CostModel will pass a vector RetTy and VF is 1.
1082 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max();
1083 if (RetVF > 1 || VF > 1) {
1084 ScalarizationCost = 0;
1085 if (!RetTy->isVoidTy())
1086 ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
1087 ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
1090 return ConcreteTTI->getIntrinsicInstrCost(IID, RetTy, Types, FMF,
1091 ScalarizationCost);
1093 case Intrinsic::masked_scatter: {
1094 assert(VF == 1 && "Can't vectorize types here.");
1095 Value *Mask = Args[3];
1096 bool VarMask = !isa<Constant>(Mask);
1097 unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
1098 return ConcreteTTI->getGatherScatterOpCost(
1099 Instruction::Store, Args[0]->getType(), Args[1], VarMask, Alignment);
1101 case Intrinsic::masked_gather: {
1102 assert(VF == 1 && "Can't vectorize types here.");
1103 Value *Mask = Args[2];
1104 bool VarMask = !isa<Constant>(Mask);
1105 unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
1106 return ConcreteTTI->getGatherScatterOpCost(Instruction::Load, RetTy,
1107 Args[0], VarMask, Alignment);
1109 case Intrinsic::experimental_vector_reduce_add:
1110 case Intrinsic::experimental_vector_reduce_mul:
1111 case Intrinsic::experimental_vector_reduce_and:
1112 case Intrinsic::experimental_vector_reduce_or:
1113 case Intrinsic::experimental_vector_reduce_xor:
1114 case Intrinsic::experimental_vector_reduce_v2_fadd:
1115 case Intrinsic::experimental_vector_reduce_v2_fmul:
1116 case Intrinsic::experimental_vector_reduce_smax:
1117 case Intrinsic::experimental_vector_reduce_smin:
1118 case Intrinsic::experimental_vector_reduce_fmax:
1119 case Intrinsic::experimental_vector_reduce_fmin:
1120 case Intrinsic::experimental_vector_reduce_umax:
1121 case Intrinsic::experimental_vector_reduce_umin:
1122 return getIntrinsicInstrCost(IID, RetTy, Args[0]->getType(), FMF);
1123 case Intrinsic::fshl:
1124 case Intrinsic::fshr: {
1125 Value *X = Args[0];
1126 Value *Y = Args[1];
1127 Value *Z = Args[2];
1128 TTI::OperandValueProperties OpPropsX, OpPropsY, OpPropsZ, OpPropsBW;
1129 TTI::OperandValueKind OpKindX = TTI::getOperandInfo(X, OpPropsX);
1130 TTI::OperandValueKind OpKindY = TTI::getOperandInfo(Y, OpPropsY);
1131 TTI::OperandValueKind OpKindZ = TTI::getOperandInfo(Z, OpPropsZ);
1132 TTI::OperandValueKind OpKindBW = TTI::OK_UniformConstantValue;
1133 OpPropsBW = isPowerOf2_32(RetTy->getScalarSizeInBits()) ? TTI::OP_PowerOf2
1134 : TTI::OP_None;
1135 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
1136 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
1137 unsigned Cost = 0;
1138 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::Or, RetTy);
1139 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::Sub, RetTy);
1140 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::Shl, RetTy,
1141 OpKindX, OpKindZ, OpPropsX);
1142 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::LShr, RetTy,
1143 OpKindY, OpKindZ, OpPropsY);
1144 // Non-constant shift amounts requires a modulo.
1145 if (OpKindZ != TTI::OK_UniformConstantValue &&
1146 OpKindZ != TTI::OK_NonUniformConstantValue)
1147 Cost += ConcreteTTI->getArithmeticInstrCost(BinaryOperator::URem, RetTy,
1148 OpKindZ, OpKindBW, OpPropsZ,
1149 OpPropsBW);
1150 // For non-rotates (X != Y) we must add shift-by-zero handling costs.
1151 if (X != Y) {
1152 Type *CondTy = Type::getInt1Ty(RetTy->getContext());
1153 if (RetVF > 1)
1154 CondTy = VectorType::get(CondTy, RetVF);
1155 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy,
1156 CondTy, nullptr);
1157 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::Select, RetTy,
1158 CondTy, nullptr);
1160 return Cost;
1165 /// Get intrinsic cost based on argument types.
1166 /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
1167 /// cost of scalarizing the arguments and the return value will be computed
1168 /// based on types.
1169 unsigned getIntrinsicInstrCost(
1170 Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> Tys, FastMathFlags FMF,
1171 unsigned ScalarizationCostPassed = std::numeric_limits<unsigned>::max()) {
1172 unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
1173 auto *ConcreteTTI = static_cast<T *>(this);
1175 SmallVector<unsigned, 2> ISDs;
1176 unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
1177 switch (IID) {
1178 default: {
1179 // Assume that we need to scalarize this intrinsic.
1180 unsigned ScalarizationCost = ScalarizationCostPassed;
1181 unsigned ScalarCalls = 1;
1182 Type *ScalarRetTy = RetTy;
1183 if (RetTy->isVectorTy()) {
1184 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1185 ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
1186 ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
1187 ScalarRetTy = RetTy->getScalarType();
1189 SmallVector<Type *, 4> ScalarTys;
1190 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1191 Type *Ty = Tys[i];
1192 if (Ty->isVectorTy()) {
1193 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1194 ScalarizationCost += getScalarizationOverhead(Ty, false, true);
1195 ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
1196 Ty = Ty->getScalarType();
1198 ScalarTys.push_back(Ty);
1200 if (ScalarCalls == 1)
1201 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
1203 unsigned ScalarCost =
1204 ConcreteTTI->getIntrinsicInstrCost(IID, ScalarRetTy, ScalarTys, FMF);
1206 return ScalarCalls * ScalarCost + ScalarizationCost;
1208 // Look for intrinsics that can be lowered directly or turned into a scalar
1209 // intrinsic call.
1210 case Intrinsic::sqrt:
1211 ISDs.push_back(ISD::FSQRT);
1212 break;
1213 case Intrinsic::sin:
1214 ISDs.push_back(ISD::FSIN);
1215 break;
1216 case Intrinsic::cos:
1217 ISDs.push_back(ISD::FCOS);
1218 break;
1219 case Intrinsic::exp:
1220 ISDs.push_back(ISD::FEXP);
1221 break;
1222 case Intrinsic::exp2:
1223 ISDs.push_back(ISD::FEXP2);
1224 break;
1225 case Intrinsic::log:
1226 ISDs.push_back(ISD::FLOG);
1227 break;
1228 case Intrinsic::log10:
1229 ISDs.push_back(ISD::FLOG10);
1230 break;
1231 case Intrinsic::log2:
1232 ISDs.push_back(ISD::FLOG2);
1233 break;
1234 case Intrinsic::fabs:
1235 ISDs.push_back(ISD::FABS);
1236 break;
1237 case Intrinsic::canonicalize:
1238 ISDs.push_back(ISD::FCANONICALIZE);
1239 break;
1240 case Intrinsic::minnum:
1241 ISDs.push_back(ISD::FMINNUM);
1242 if (FMF.noNaNs())
1243 ISDs.push_back(ISD::FMINIMUM);
1244 break;
1245 case Intrinsic::maxnum:
1246 ISDs.push_back(ISD::FMAXNUM);
1247 if (FMF.noNaNs())
1248 ISDs.push_back(ISD::FMAXIMUM);
1249 break;
1250 case Intrinsic::copysign:
1251 ISDs.push_back(ISD::FCOPYSIGN);
1252 break;
1253 case Intrinsic::floor:
1254 ISDs.push_back(ISD::FFLOOR);
1255 break;
1256 case Intrinsic::ceil:
1257 ISDs.push_back(ISD::FCEIL);
1258 break;
1259 case Intrinsic::trunc:
1260 ISDs.push_back(ISD::FTRUNC);
1261 break;
1262 case Intrinsic::nearbyint:
1263 ISDs.push_back(ISD::FNEARBYINT);
1264 break;
1265 case Intrinsic::rint:
1266 ISDs.push_back(ISD::FRINT);
1267 break;
1268 case Intrinsic::round:
1269 ISDs.push_back(ISD::FROUND);
1270 break;
1271 case Intrinsic::pow:
1272 ISDs.push_back(ISD::FPOW);
1273 break;
1274 case Intrinsic::fma:
1275 ISDs.push_back(ISD::FMA);
1276 break;
1277 case Intrinsic::fmuladd:
1278 ISDs.push_back(ISD::FMA);
1279 break;
1280 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
1281 case Intrinsic::lifetime_start:
1282 case Intrinsic::lifetime_end:
1283 case Intrinsic::sideeffect:
1284 return 0;
1285 case Intrinsic::masked_store:
1286 return ConcreteTTI->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0,
1288 case Intrinsic::masked_load:
1289 return ConcreteTTI->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
1290 case Intrinsic::experimental_vector_reduce_add:
1291 return ConcreteTTI->getArithmeticReductionCost(Instruction::Add, Tys[0],
1292 /*IsPairwiseForm=*/false);
1293 case Intrinsic::experimental_vector_reduce_mul:
1294 return ConcreteTTI->getArithmeticReductionCost(Instruction::Mul, Tys[0],
1295 /*IsPairwiseForm=*/false);
1296 case Intrinsic::experimental_vector_reduce_and:
1297 return ConcreteTTI->getArithmeticReductionCost(Instruction::And, Tys[0],
1298 /*IsPairwiseForm=*/false);
1299 case Intrinsic::experimental_vector_reduce_or:
1300 return ConcreteTTI->getArithmeticReductionCost(Instruction::Or, Tys[0],
1301 /*IsPairwiseForm=*/false);
1302 case Intrinsic::experimental_vector_reduce_xor:
1303 return ConcreteTTI->getArithmeticReductionCost(Instruction::Xor, Tys[0],
1304 /*IsPairwiseForm=*/false);
1305 case Intrinsic::experimental_vector_reduce_v2_fadd:
1306 return ConcreteTTI->getArithmeticReductionCost(
1307 Instruction::FAdd, Tys[0],
1308 /*IsPairwiseForm=*/false); // FIXME: Add new flag for cost of strict
1309 // reductions.
1310 case Intrinsic::experimental_vector_reduce_v2_fmul:
1311 return ConcreteTTI->getArithmeticReductionCost(
1312 Instruction::FMul, Tys[0],
1313 /*IsPairwiseForm=*/false); // FIXME: Add new flag for cost of strict
1314 // reductions.
1315 case Intrinsic::experimental_vector_reduce_smax:
1316 case Intrinsic::experimental_vector_reduce_smin:
1317 case Intrinsic::experimental_vector_reduce_fmax:
1318 case Intrinsic::experimental_vector_reduce_fmin:
1319 return ConcreteTTI->getMinMaxReductionCost(
1320 Tys[0], CmpInst::makeCmpResultType(Tys[0]), /*IsPairwiseForm=*/false,
1321 /*IsUnsigned=*/true);
1322 case Intrinsic::experimental_vector_reduce_umax:
1323 case Intrinsic::experimental_vector_reduce_umin:
1324 return ConcreteTTI->getMinMaxReductionCost(
1325 Tys[0], CmpInst::makeCmpResultType(Tys[0]), /*IsPairwiseForm=*/false,
1326 /*IsUnsigned=*/false);
1327 case Intrinsic::sadd_sat:
1328 case Intrinsic::ssub_sat: {
1329 Type *CondTy = Type::getInt1Ty(RetTy->getContext());
1330 if (RetVF > 1)
1331 CondTy = VectorType::get(CondTy, RetVF);
1333 Type *OpTy = StructType::create({RetTy, CondTy});
1334 Intrinsic::ID OverflowOp = IID == Intrinsic::sadd_sat
1335 ? Intrinsic::sadd_with_overflow
1336 : Intrinsic::ssub_with_overflow;
1338 // SatMax -> Overflow && SumDiff < 0
1339 // SatMin -> Overflow && SumDiff >= 0
1340 unsigned Cost = 0;
1341 Cost += ConcreteTTI->getIntrinsicInstrCost(
1342 OverflowOp, OpTy, {RetTy, RetTy}, FMF, ScalarizationCostPassed);
1343 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy,
1344 CondTy, nullptr);
1345 Cost += 2 * ConcreteTTI->getCmpSelInstrCost(BinaryOperator::Select, RetTy,
1346 CondTy, nullptr);
1347 return Cost;
1349 case Intrinsic::uadd_sat:
1350 case Intrinsic::usub_sat: {
1351 Type *CondTy = Type::getInt1Ty(RetTy->getContext());
1352 if (RetVF > 1)
1353 CondTy = VectorType::get(CondTy, RetVF);
1355 Type *OpTy = StructType::create({RetTy, CondTy});
1356 Intrinsic::ID OverflowOp = IID == Intrinsic::uadd_sat
1357 ? Intrinsic::uadd_with_overflow
1358 : Intrinsic::usub_with_overflow;
1360 unsigned Cost = 0;
1361 Cost += ConcreteTTI->getIntrinsicInstrCost(
1362 OverflowOp, OpTy, {RetTy, RetTy}, FMF, ScalarizationCostPassed);
1363 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::Select, RetTy,
1364 CondTy, nullptr);
1365 return Cost;
1367 case Intrinsic::smul_fix:
1368 case Intrinsic::umul_fix: {
1369 unsigned ExtSize = RetTy->getScalarSizeInBits() * 2;
1370 Type *ExtTy = Type::getIntNTy(RetTy->getContext(), ExtSize);
1371 if (RetVF > 1)
1372 ExtTy = VectorType::get(ExtTy, RetVF);
1374 unsigned ExtOp =
1375 IID == Intrinsic::smul_fix ? Instruction::SExt : Instruction::ZExt;
1377 unsigned Cost = 0;
1378 Cost += 2 * ConcreteTTI->getCastInstrCost(ExtOp, ExtTy, RetTy);
1379 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::Mul, ExtTy);
1380 Cost +=
1381 2 * ConcreteTTI->getCastInstrCost(Instruction::Trunc, RetTy, ExtTy);
1382 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::LShr, RetTy,
1383 TTI::OK_AnyValue,
1384 TTI::OK_UniformConstantValue);
1385 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::Shl, RetTy,
1386 TTI::OK_AnyValue,
1387 TTI::OK_UniformConstantValue);
1388 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::Or, RetTy);
1389 return Cost;
1391 case Intrinsic::sadd_with_overflow:
1392 case Intrinsic::ssub_with_overflow: {
1393 Type *SumTy = RetTy->getContainedType(0);
1394 Type *OverflowTy = RetTy->getContainedType(1);
1395 unsigned Opcode = IID == Intrinsic::sadd_with_overflow
1396 ? BinaryOperator::Add
1397 : BinaryOperator::Sub;
1399 // LHSSign -> LHS >= 0
1400 // RHSSign -> RHS >= 0
1401 // SumSign -> Sum >= 0
1403 // Add:
1404 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
1405 // Sub:
1406 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
1407 unsigned Cost = 0;
1408 Cost += ConcreteTTI->getArithmeticInstrCost(Opcode, SumTy);
1409 Cost += 3 * ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, SumTy,
1410 OverflowTy, nullptr);
1411 Cost += 2 * ConcreteTTI->getCmpSelInstrCost(
1412 BinaryOperator::ICmp, OverflowTy, OverflowTy, nullptr);
1413 Cost +=
1414 ConcreteTTI->getArithmeticInstrCost(BinaryOperator::And, OverflowTy);
1415 return Cost;
1417 case Intrinsic::uadd_with_overflow:
1418 case Intrinsic::usub_with_overflow: {
1419 Type *SumTy = RetTy->getContainedType(0);
1420 Type *OverflowTy = RetTy->getContainedType(1);
1421 unsigned Opcode = IID == Intrinsic::uadd_with_overflow
1422 ? BinaryOperator::Add
1423 : BinaryOperator::Sub;
1425 unsigned Cost = 0;
1426 Cost += ConcreteTTI->getArithmeticInstrCost(Opcode, SumTy);
1427 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, SumTy,
1428 OverflowTy, nullptr);
1429 return Cost;
1431 case Intrinsic::smul_with_overflow:
1432 case Intrinsic::umul_with_overflow: {
1433 Type *MulTy = RetTy->getContainedType(0);
1434 Type *OverflowTy = RetTy->getContainedType(1);
1435 unsigned ExtSize = MulTy->getScalarSizeInBits() * 2;
1436 Type *ExtTy = Type::getIntNTy(RetTy->getContext(), ExtSize);
1437 if (MulTy->isVectorTy())
1438 ExtTy = VectorType::get(ExtTy, MulTy->getVectorNumElements() );
1440 unsigned ExtOp =
1441 IID == Intrinsic::smul_fix ? Instruction::SExt : Instruction::ZExt;
1443 unsigned Cost = 0;
1444 Cost += 2 * ConcreteTTI->getCastInstrCost(ExtOp, ExtTy, MulTy);
1445 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::Mul, ExtTy);
1446 Cost +=
1447 2 * ConcreteTTI->getCastInstrCost(Instruction::Trunc, MulTy, ExtTy);
1448 Cost += ConcreteTTI->getArithmeticInstrCost(Instruction::LShr, MulTy,
1449 TTI::OK_AnyValue,
1450 TTI::OK_UniformConstantValue);
1452 if (IID == Intrinsic::smul_with_overflow)
1453 Cost += ConcreteTTI->getArithmeticInstrCost(
1454 Instruction::AShr, MulTy, TTI::OK_AnyValue,
1455 TTI::OK_UniformConstantValue);
1457 Cost += ConcreteTTI->getCmpSelInstrCost(BinaryOperator::ICmp, MulTy,
1458 OverflowTy, nullptr);
1459 return Cost;
1461 case Intrinsic::ctpop:
1462 ISDs.push_back(ISD::CTPOP);
1463 // In case of legalization use TCC_Expensive. This is cheaper than a
1464 // library call but still not a cheap instruction.
1465 SingleCallCost = TargetTransformInfo::TCC_Expensive;
1466 break;
1467 // FIXME: ctlz, cttz, ...
1470 const TargetLoweringBase *TLI = getTLI();
1471 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
1473 SmallVector<unsigned, 2> LegalCost;
1474 SmallVector<unsigned, 2> CustomCost;
1475 for (unsigned ISD : ISDs) {
1476 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1477 if (IID == Intrinsic::fabs && LT.second.isFloatingPoint() &&
1478 TLI->isFAbsFree(LT.second)) {
1479 return 0;
1482 // The operation is legal. Assume it costs 1.
1483 // If the type is split to multiple registers, assume that there is some
1484 // overhead to this.
1485 // TODO: Once we have extract/insert subvector cost we need to use them.
1486 if (LT.first > 1)
1487 LegalCost.push_back(LT.first * 2);
1488 else
1489 LegalCost.push_back(LT.first * 1);
1490 } else if (!TLI->isOperationExpand(ISD, LT.second)) {
1491 // If the operation is custom lowered then assume
1492 // that the code is twice as expensive.
1493 CustomCost.push_back(LT.first * 2);
1497 auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
1498 if (MinLegalCostI != LegalCost.end())
1499 return *MinLegalCostI;
1501 auto MinCustomCostI =
1502 std::min_element(CustomCost.begin(), CustomCost.end());
1503 if (MinCustomCostI != CustomCost.end())
1504 return *MinCustomCostI;
1506 // If we can't lower fmuladd into an FMA estimate the cost as a floating
1507 // point mul followed by an add.
1508 if (IID == Intrinsic::fmuladd)
1509 return ConcreteTTI->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
1510 ConcreteTTI->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
1512 // Else, assume that we need to scalarize this intrinsic. For math builtins
1513 // this will emit a costly libcall, adding call overhead and spills. Make it
1514 // very expensive.
1515 if (RetTy->isVectorTy()) {
1516 unsigned ScalarizationCost =
1517 ((ScalarizationCostPassed != std::numeric_limits<unsigned>::max())
1518 ? ScalarizationCostPassed
1519 : getScalarizationOverhead(RetTy, true, false));
1520 unsigned ScalarCalls = RetTy->getVectorNumElements();
1521 SmallVector<Type *, 4> ScalarTys;
1522 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1523 Type *Ty = Tys[i];
1524 if (Ty->isVectorTy())
1525 Ty = Ty->getScalarType();
1526 ScalarTys.push_back(Ty);
1528 unsigned ScalarCost = ConcreteTTI->getIntrinsicInstrCost(
1529 IID, RetTy->getScalarType(), ScalarTys, FMF);
1530 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
1531 if (Tys[i]->isVectorTy()) {
1532 if (ScalarizationCostPassed == std::numeric_limits<unsigned>::max())
1533 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
1534 ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
1538 return ScalarCalls * ScalarCost + ScalarizationCost;
1541 // This is going to be turned into a library call, make it expensive.
1542 return SingleCallCost;
1545 /// Compute a cost of the given call instruction.
1547 /// Compute the cost of calling function F with return type RetTy and
1548 /// argument types Tys. F might be nullptr, in this case the cost of an
1549 /// arbitrary call with the specified signature will be returned.
1550 /// This is used, for instance, when we estimate call of a vector
1551 /// counterpart of the given function.
1552 /// \param F Called function, might be nullptr.
1553 /// \param RetTy Return value types.
1554 /// \param Tys Argument types.
1555 /// \returns The cost of Call instruction.
1556 unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
1557 return 10;
1560 unsigned getNumberOfParts(Type *Tp) {
1561 std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
1562 return LT.first;
1565 unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
1566 const SCEV *) {
1567 return 0;
1570 /// Try to calculate arithmetic and shuffle op costs for reduction operations.
1571 /// We're assuming that reduction operation are performing the following way:
1572 /// 1. Non-pairwise reduction
1573 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1574 /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
1575 /// \----------------v-------------/ \----------v------------/
1576 /// n/2 elements n/2 elements
1577 /// %red1 = op <n x t> %val, <n x t> val1
1578 /// After this operation we have a vector %red1 where only the first n/2
1579 /// elements are meaningful, the second n/2 elements are undefined and can be
1580 /// dropped. All other operations are actually working with the vector of
1581 /// length n/2, not n, though the real vector length is still n.
1582 /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
1583 /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
1584 /// \----------------v-------------/ \----------v------------/
1585 /// n/4 elements 3*n/4 elements
1586 /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
1587 /// length n/2, the resulting vector has length n/4 etc.
1588 /// 2. Pairwise reduction:
1589 /// Everything is the same except for an additional shuffle operation which
1590 /// is used to produce operands for pairwise kind of reductions.
1591 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
1592 /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
1593 /// \-------------v----------/ \----------v------------/
1594 /// n/2 elements n/2 elements
1595 /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
1596 /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
1597 /// \-------------v----------/ \----------v------------/
1598 /// n/2 elements n/2 elements
1599 /// %red1 = op <n x t> %val1, <n x t> val2
1600 /// Again, the operation is performed on <n x t> vector, but the resulting
1601 /// vector %red1 is <n/2 x t> vector.
1603 /// The cost model should take into account that the actual length of the
1604 /// vector is reduced on each iteration.
1605 unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1606 bool IsPairwise) {
1607 assert(Ty->isVectorTy() && "Expect a vector type");
1608 Type *ScalarTy = Ty->getVectorElementType();
1609 unsigned NumVecElts = Ty->getVectorNumElements();
1610 unsigned NumReduxLevels = Log2_32(NumVecElts);
1611 unsigned ArithCost = 0;
1612 unsigned ShuffleCost = 0;
1613 auto *ConcreteTTI = static_cast<T *>(this);
1614 std::pair<unsigned, MVT> LT =
1615 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1616 unsigned LongVectorCount = 0;
1617 unsigned MVTLen =
1618 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1619 while (NumVecElts > MVTLen) {
1620 NumVecElts /= 2;
1621 Type *SubTy = VectorType::get(ScalarTy, NumVecElts);
1622 // Assume the pairwise shuffles add a cost.
1623 ShuffleCost += (IsPairwise + 1) *
1624 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1625 NumVecElts, SubTy);
1626 ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, SubTy);
1627 Ty = SubTy;
1628 ++LongVectorCount;
1631 NumReduxLevels -= LongVectorCount;
1633 // The minimal length of the vector is limited by the real length of vector
1634 // operations performed on the current platform. That's why several final
1635 // reduction operations are performed on the vectors with the same
1636 // architecture-dependent length.
1638 // Non pairwise reductions need one shuffle per reduction level. Pairwise
1639 // reductions need two shuffles on every level, but the last one. On that
1640 // level one of the shuffles is <0, u, u, ...> which is identity.
1641 unsigned NumShuffles = NumReduxLevels;
1642 if (IsPairwise && NumReduxLevels >= 1)
1643 NumShuffles += NumReduxLevels - 1;
1644 ShuffleCost += NumShuffles *
1645 ConcreteTTI->getShuffleCost(TTI::SK_PermuteSingleSrc, Ty,
1646 0, Ty);
1647 ArithCost += NumReduxLevels *
1648 ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
1649 return ShuffleCost + ArithCost +
1650 ConcreteTTI->getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
1653 /// Try to calculate op costs for min/max reduction operations.
1654 /// \param CondTy Conditional type for the Select instruction.
1655 unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
1656 bool) {
1657 assert(Ty->isVectorTy() && "Expect a vector type");
1658 Type *ScalarTy = Ty->getVectorElementType();
1659 Type *ScalarCondTy = CondTy->getVectorElementType();
1660 unsigned NumVecElts = Ty->getVectorNumElements();
1661 unsigned NumReduxLevels = Log2_32(NumVecElts);
1662 unsigned CmpOpcode;
1663 if (Ty->isFPOrFPVectorTy()) {
1664 CmpOpcode = Instruction::FCmp;
1665 } else {
1666 assert(Ty->isIntOrIntVectorTy() &&
1667 "expecting floating point or integer type for min/max reduction");
1668 CmpOpcode = Instruction::ICmp;
1670 unsigned MinMaxCost = 0;
1671 unsigned ShuffleCost = 0;
1672 auto *ConcreteTTI = static_cast<T *>(this);
1673 std::pair<unsigned, MVT> LT =
1674 ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
1675 unsigned LongVectorCount = 0;
1676 unsigned MVTLen =
1677 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
1678 while (NumVecElts > MVTLen) {
1679 NumVecElts /= 2;
1680 Type *SubTy = VectorType::get(ScalarTy, NumVecElts);
1681 CondTy = VectorType::get(ScalarCondTy, NumVecElts);
1683 // Assume the pairwise shuffles add a cost.
1684 ShuffleCost += (IsPairwise + 1) *
1685 ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
1686 NumVecElts, SubTy);
1687 MinMaxCost +=
1688 ConcreteTTI->getCmpSelInstrCost(CmpOpcode, SubTy, CondTy, nullptr) +
1689 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, SubTy, CondTy,
1690 nullptr);
1691 Ty = SubTy;
1692 ++LongVectorCount;
1695 NumReduxLevels -= LongVectorCount;
1697 // The minimal length of the vector is limited by the real length of vector
1698 // operations performed on the current platform. That's why several final
1699 // reduction opertions are perfomed on the vectors with the same
1700 // architecture-dependent length.
1702 // Non pairwise reductions need one shuffle per reduction level. Pairwise
1703 // reductions need two shuffles on every level, but the last one. On that
1704 // level one of the shuffles is <0, u, u, ...> which is identity.
1705 unsigned NumShuffles = NumReduxLevels;
1706 if (IsPairwise && NumReduxLevels >= 1)
1707 NumShuffles += NumReduxLevels - 1;
1708 ShuffleCost += NumShuffles *
1709 ConcreteTTI->getShuffleCost(TTI::SK_PermuteSingleSrc, Ty,
1710 0, Ty);
1711 MinMaxCost +=
1712 NumReduxLevels *
1713 (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
1714 ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
1715 nullptr));
1716 // The last min/max should be in vector registers and we counted it above.
1717 // So just need a single extractelement.
1718 return ShuffleCost + MinMaxCost +
1719 ConcreteTTI->getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
1722 unsigned getVectorSplitCost() { return 1; }
1724 /// @}
1727 /// Concrete BasicTTIImpl that can be used if no further customization
1728 /// is needed.
1729 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
1730 using BaseT = BasicTTIImplBase<BasicTTIImpl>;
1732 friend class BasicTTIImplBase<BasicTTIImpl>;
1734 const TargetSubtargetInfo *ST;
1735 const TargetLoweringBase *TLI;
1737 const TargetSubtargetInfo *getST() const { return ST; }
1738 const TargetLoweringBase *getTLI() const { return TLI; }
1740 public:
1741 explicit BasicTTIImpl(const TargetMachine *TM, const Function &F);
1744 } // end namespace llvm
1746 #endif // LLVM_CODEGEN_BASICTTIIMPL_H