1 //===- llvm/Analysis/TargetTransformInfo.cpp ------------------------------===//
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 #include "llvm/Analysis/TargetTransformInfo.h"
11 #include "llvm/Analysis/TargetTransformInfoImpl.h"
12 #include "llvm/IR/CallSite.h"
13 #include "llvm/IR/DataLayout.h"
14 #include "llvm/IR/Instruction.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/IR/Operator.h"
19 #include "llvm/IR/PatternMatch.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ErrorHandling.h"
25 using namespace PatternMatch;
27 #define DEBUG_TYPE "tti"
29 static cl::opt<bool> EnableReduxCost("costmodel-reduxcost", cl::init(false),
31 cl::desc("Recognize reduction patterns."));
34 /// No-op implementation of the TTI interface using the utility base
37 /// This is used when no target specific information is available.
38 struct NoTTIImpl : TargetTransformInfoImplCRTPBase<NoTTIImpl> {
39 explicit NoTTIImpl(const DataLayout &DL)
40 : TargetTransformInfoImplCRTPBase<NoTTIImpl>(DL) {}
44 TargetTransformInfo::TargetTransformInfo(const DataLayout &DL)
45 : TTIImpl(new Model<NoTTIImpl>(NoTTIImpl(DL))) {}
47 TargetTransformInfo::~TargetTransformInfo() {}
49 TargetTransformInfo::TargetTransformInfo(TargetTransformInfo &&Arg)
50 : TTIImpl(std::move(Arg.TTIImpl)) {}
52 TargetTransformInfo &TargetTransformInfo::operator=(TargetTransformInfo &&RHS) {
53 TTIImpl = std::move(RHS.TTIImpl);
57 int TargetTransformInfo::getOperationCost(unsigned Opcode, Type *Ty,
59 int Cost = TTIImpl->getOperationCost(Opcode, Ty, OpTy);
60 assert(Cost >= 0 && "TTI should not produce negative costs!");
64 int TargetTransformInfo::getCallCost(FunctionType *FTy, int NumArgs) const {
65 int Cost = TTIImpl->getCallCost(FTy, NumArgs);
66 assert(Cost >= 0 && "TTI should not produce negative costs!");
70 int TargetTransformInfo::getCallCost(const Function *F,
71 ArrayRef<const Value *> Arguments) const {
72 int Cost = TTIImpl->getCallCost(F, Arguments);
73 assert(Cost >= 0 && "TTI should not produce negative costs!");
77 unsigned TargetTransformInfo::getInliningThresholdMultiplier() const {
78 return TTIImpl->getInliningThresholdMultiplier();
81 int TargetTransformInfo::getGEPCost(Type *PointeeType, const Value *Ptr,
82 ArrayRef<const Value *> Operands) const {
83 return TTIImpl->getGEPCost(PointeeType, Ptr, Operands);
86 int TargetTransformInfo::getExtCost(const Instruction *I,
87 const Value *Src) const {
88 return TTIImpl->getExtCost(I, Src);
91 int TargetTransformInfo::getIntrinsicCost(
92 Intrinsic::ID IID, Type *RetTy, ArrayRef<const Value *> Arguments) const {
93 int Cost = TTIImpl->getIntrinsicCost(IID, RetTy, Arguments);
94 assert(Cost >= 0 && "TTI should not produce negative costs!");
99 TargetTransformInfo::getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
100 unsigned &JTSize) const {
101 return TTIImpl->getEstimatedNumberOfCaseClusters(SI, JTSize);
104 int TargetTransformInfo::getUserCost(const User *U,
105 ArrayRef<const Value *> Operands) const {
106 int Cost = TTIImpl->getUserCost(U, Operands);
107 assert(Cost >= 0 && "TTI should not produce negative costs!");
111 bool TargetTransformInfo::hasBranchDivergence() const {
112 return TTIImpl->hasBranchDivergence();
115 bool TargetTransformInfo::isSourceOfDivergence(const Value *V) const {
116 return TTIImpl->isSourceOfDivergence(V);
119 bool llvm::TargetTransformInfo::isAlwaysUniform(const Value *V) const {
120 return TTIImpl->isAlwaysUniform(V);
123 unsigned TargetTransformInfo::getFlatAddressSpace() const {
124 return TTIImpl->getFlatAddressSpace();
127 bool TargetTransformInfo::isLoweredToCall(const Function *F) const {
128 return TTIImpl->isLoweredToCall(F);
131 void TargetTransformInfo::getUnrollingPreferences(
132 Loop *L, ScalarEvolution &SE, UnrollingPreferences &UP) const {
133 return TTIImpl->getUnrollingPreferences(L, SE, UP);
136 bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm) const {
137 return TTIImpl->isLegalAddImmediate(Imm);
140 bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm) const {
141 return TTIImpl->isLegalICmpImmediate(Imm);
144 bool TargetTransformInfo::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
149 Instruction *I) const {
150 return TTIImpl->isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
151 Scale, AddrSpace, I);
154 bool TargetTransformInfo::isLSRCostLess(LSRCost &C1, LSRCost &C2) const {
155 return TTIImpl->isLSRCostLess(C1, C2);
158 bool TargetTransformInfo::canMacroFuseCmp() const {
159 return TTIImpl->canMacroFuseCmp();
162 bool TargetTransformInfo::shouldFavorPostInc() const {
163 return TTIImpl->shouldFavorPostInc();
166 bool TargetTransformInfo::isLegalMaskedStore(Type *DataType) const {
167 return TTIImpl->isLegalMaskedStore(DataType);
170 bool TargetTransformInfo::isLegalMaskedLoad(Type *DataType) const {
171 return TTIImpl->isLegalMaskedLoad(DataType);
174 bool TargetTransformInfo::isLegalMaskedGather(Type *DataType) const {
175 return TTIImpl->isLegalMaskedGather(DataType);
178 bool TargetTransformInfo::isLegalMaskedScatter(Type *DataType) const {
179 return TTIImpl->isLegalMaskedScatter(DataType);
182 bool TargetTransformInfo::hasDivRemOp(Type *DataType, bool IsSigned) const {
183 return TTIImpl->hasDivRemOp(DataType, IsSigned);
186 bool TargetTransformInfo::hasVolatileVariant(Instruction *I,
187 unsigned AddrSpace) const {
188 return TTIImpl->hasVolatileVariant(I, AddrSpace);
191 bool TargetTransformInfo::prefersVectorizedAddressing() const {
192 return TTIImpl->prefersVectorizedAddressing();
195 int TargetTransformInfo::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
199 unsigned AddrSpace) const {
200 int Cost = TTIImpl->getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg,
202 assert(Cost >= 0 && "TTI should not produce negative costs!");
206 bool TargetTransformInfo::LSRWithInstrQueries() const {
207 return TTIImpl->LSRWithInstrQueries();
210 bool TargetTransformInfo::isTruncateFree(Type *Ty1, Type *Ty2) const {
211 return TTIImpl->isTruncateFree(Ty1, Ty2);
214 bool TargetTransformInfo::isProfitableToHoist(Instruction *I) const {
215 return TTIImpl->isProfitableToHoist(I);
218 bool TargetTransformInfo::useAA() const { return TTIImpl->useAA(); }
220 bool TargetTransformInfo::isTypeLegal(Type *Ty) const {
221 return TTIImpl->isTypeLegal(Ty);
224 unsigned TargetTransformInfo::getJumpBufAlignment() const {
225 return TTIImpl->getJumpBufAlignment();
228 unsigned TargetTransformInfo::getJumpBufSize() const {
229 return TTIImpl->getJumpBufSize();
232 bool TargetTransformInfo::shouldBuildLookupTables() const {
233 return TTIImpl->shouldBuildLookupTables();
235 bool TargetTransformInfo::shouldBuildLookupTablesForConstant(Constant *C) const {
236 return TTIImpl->shouldBuildLookupTablesForConstant(C);
239 bool TargetTransformInfo::useColdCCForColdCall(Function &F) const {
240 return TTIImpl->useColdCCForColdCall(F);
243 unsigned TargetTransformInfo::
244 getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const {
245 return TTIImpl->getScalarizationOverhead(Ty, Insert, Extract);
248 unsigned TargetTransformInfo::
249 getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
251 return TTIImpl->getOperandsScalarizationOverhead(Args, VF);
254 bool TargetTransformInfo::supportsEfficientVectorElementLoadStore() const {
255 return TTIImpl->supportsEfficientVectorElementLoadStore();
258 bool TargetTransformInfo::enableAggressiveInterleaving(bool LoopHasReductions) const {
259 return TTIImpl->enableAggressiveInterleaving(LoopHasReductions);
262 const TargetTransformInfo::MemCmpExpansionOptions *
263 TargetTransformInfo::enableMemCmpExpansion(bool IsZeroCmp) const {
264 return TTIImpl->enableMemCmpExpansion(IsZeroCmp);
267 bool TargetTransformInfo::enableInterleavedAccessVectorization() const {
268 return TTIImpl->enableInterleavedAccessVectorization();
271 bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const {
272 return TTIImpl->isFPVectorizationPotentiallyUnsafe();
275 bool TargetTransformInfo::allowsMisalignedMemoryAccesses(LLVMContext &Context,
277 unsigned AddressSpace,
280 return TTIImpl->allowsMisalignedMemoryAccesses(Context, BitWidth, AddressSpace,
284 TargetTransformInfo::PopcntSupportKind
285 TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit) const {
286 return TTIImpl->getPopcntSupport(IntTyWidthInBit);
289 bool TargetTransformInfo::haveFastSqrt(Type *Ty) const {
290 return TTIImpl->haveFastSqrt(Ty);
293 bool TargetTransformInfo::isFCmpOrdCheaperThanFCmpZero(Type *Ty) const {
294 return TTIImpl->isFCmpOrdCheaperThanFCmpZero(Ty);
297 int TargetTransformInfo::getFPOpCost(Type *Ty) const {
298 int Cost = TTIImpl->getFPOpCost(Ty);
299 assert(Cost >= 0 && "TTI should not produce negative costs!");
303 int TargetTransformInfo::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
306 int Cost = TTIImpl->getIntImmCodeSizeCost(Opcode, Idx, Imm, Ty);
307 assert(Cost >= 0 && "TTI should not produce negative costs!");
311 int TargetTransformInfo::getIntImmCost(const APInt &Imm, Type *Ty) const {
312 int Cost = TTIImpl->getIntImmCost(Imm, Ty);
313 assert(Cost >= 0 && "TTI should not produce negative costs!");
317 int TargetTransformInfo::getIntImmCost(unsigned Opcode, unsigned Idx,
318 const APInt &Imm, Type *Ty) const {
319 int Cost = TTIImpl->getIntImmCost(Opcode, Idx, Imm, Ty);
320 assert(Cost >= 0 && "TTI should not produce negative costs!");
324 int TargetTransformInfo::getIntImmCost(Intrinsic::ID IID, unsigned Idx,
325 const APInt &Imm, Type *Ty) const {
326 int Cost = TTIImpl->getIntImmCost(IID, Idx, Imm, Ty);
327 assert(Cost >= 0 && "TTI should not produce negative costs!");
331 unsigned TargetTransformInfo::getNumberOfRegisters(bool Vector) const {
332 return TTIImpl->getNumberOfRegisters(Vector);
335 unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector) const {
336 return TTIImpl->getRegisterBitWidth(Vector);
339 unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const {
340 return TTIImpl->getMinVectorRegisterBitWidth();
343 bool TargetTransformInfo::shouldMaximizeVectorBandwidth(bool OptSize) const {
344 return TTIImpl->shouldMaximizeVectorBandwidth(OptSize);
347 unsigned TargetTransformInfo::getMinimumVF(unsigned ElemWidth) const {
348 return TTIImpl->getMinimumVF(ElemWidth);
351 bool TargetTransformInfo::shouldConsiderAddressTypePromotion(
352 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const {
353 return TTIImpl->shouldConsiderAddressTypePromotion(
354 I, AllowPromotionWithoutCommonHeader);
357 unsigned TargetTransformInfo::getCacheLineSize() const {
358 return TTIImpl->getCacheLineSize();
361 llvm::Optional<unsigned> TargetTransformInfo::getCacheSize(CacheLevel Level)
363 return TTIImpl->getCacheSize(Level);
366 llvm::Optional<unsigned> TargetTransformInfo::getCacheAssociativity(
367 CacheLevel Level) const {
368 return TTIImpl->getCacheAssociativity(Level);
371 unsigned TargetTransformInfo::getPrefetchDistance() const {
372 return TTIImpl->getPrefetchDistance();
375 unsigned TargetTransformInfo::getMinPrefetchStride() const {
376 return TTIImpl->getMinPrefetchStride();
379 unsigned TargetTransformInfo::getMaxPrefetchIterationsAhead() const {
380 return TTIImpl->getMaxPrefetchIterationsAhead();
383 unsigned TargetTransformInfo::getMaxInterleaveFactor(unsigned VF) const {
384 return TTIImpl->getMaxInterleaveFactor(VF);
387 int TargetTransformInfo::getArithmeticInstrCost(
388 unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
389 OperandValueKind Opd2Info, OperandValueProperties Opd1PropInfo,
390 OperandValueProperties Opd2PropInfo,
391 ArrayRef<const Value *> Args) const {
392 int Cost = TTIImpl->getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
393 Opd1PropInfo, Opd2PropInfo, Args);
394 assert(Cost >= 0 && "TTI should not produce negative costs!");
398 int TargetTransformInfo::getShuffleCost(ShuffleKind Kind, Type *Ty, int Index,
400 int Cost = TTIImpl->getShuffleCost(Kind, Ty, Index, SubTp);
401 assert(Cost >= 0 && "TTI should not produce negative costs!");
405 int TargetTransformInfo::getCastInstrCost(unsigned Opcode, Type *Dst,
406 Type *Src, const Instruction *I) const {
407 assert ((I == nullptr || I->getOpcode() == Opcode) &&
408 "Opcode should reflect passed instruction.");
409 int Cost = TTIImpl->getCastInstrCost(Opcode, Dst, Src, I);
410 assert(Cost >= 0 && "TTI should not produce negative costs!");
414 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode, Type *Dst,
416 unsigned Index) const {
417 int Cost = TTIImpl->getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
418 assert(Cost >= 0 && "TTI should not produce negative costs!");
422 int TargetTransformInfo::getCFInstrCost(unsigned Opcode) const {
423 int Cost = TTIImpl->getCFInstrCost(Opcode);
424 assert(Cost >= 0 && "TTI should not produce negative costs!");
428 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
429 Type *CondTy, const Instruction *I) const {
430 assert ((I == nullptr || I->getOpcode() == Opcode) &&
431 "Opcode should reflect passed instruction.");
432 int Cost = TTIImpl->getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
433 assert(Cost >= 0 && "TTI should not produce negative costs!");
437 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
438 unsigned Index) const {
439 int Cost = TTIImpl->getVectorInstrCost(Opcode, Val, Index);
440 assert(Cost >= 0 && "TTI should not produce negative costs!");
444 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
446 unsigned AddressSpace,
447 const Instruction *I) const {
448 assert ((I == nullptr || I->getOpcode() == Opcode) &&
449 "Opcode should reflect passed instruction.");
450 int Cost = TTIImpl->getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
451 assert(Cost >= 0 && "TTI should not produce negative costs!");
455 int TargetTransformInfo::getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
457 unsigned AddressSpace) const {
459 TTIImpl->getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
460 assert(Cost >= 0 && "TTI should not produce negative costs!");
464 int TargetTransformInfo::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
465 Value *Ptr, bool VariableMask,
466 unsigned Alignment) const {
467 int Cost = TTIImpl->getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
469 assert(Cost >= 0 && "TTI should not produce negative costs!");
473 int TargetTransformInfo::getInterleavedMemoryOpCost(
474 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
475 unsigned Alignment, unsigned AddressSpace) const {
476 int Cost = TTIImpl->getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
477 Alignment, AddressSpace);
478 assert(Cost >= 0 && "TTI should not produce negative costs!");
482 int TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
483 ArrayRef<Type *> Tys, FastMathFlags FMF,
484 unsigned ScalarizationCostPassed) const {
485 int Cost = TTIImpl->getIntrinsicInstrCost(ID, RetTy, Tys, FMF,
486 ScalarizationCostPassed);
487 assert(Cost >= 0 && "TTI should not produce negative costs!");
491 int TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
492 ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) const {
493 int Cost = TTIImpl->getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF);
494 assert(Cost >= 0 && "TTI should not produce negative costs!");
498 int TargetTransformInfo::getCallInstrCost(Function *F, Type *RetTy,
499 ArrayRef<Type *> Tys) const {
500 int Cost = TTIImpl->getCallInstrCost(F, RetTy, Tys);
501 assert(Cost >= 0 && "TTI should not produce negative costs!");
505 unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const {
506 return TTIImpl->getNumberOfParts(Tp);
509 int TargetTransformInfo::getAddressComputationCost(Type *Tp,
511 const SCEV *Ptr) const {
512 int Cost = TTIImpl->getAddressComputationCost(Tp, SE, Ptr);
513 assert(Cost >= 0 && "TTI should not produce negative costs!");
517 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode, Type *Ty,
518 bool IsPairwiseForm) const {
519 int Cost = TTIImpl->getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm);
520 assert(Cost >= 0 && "TTI should not produce negative costs!");
524 int TargetTransformInfo::getMinMaxReductionCost(Type *Ty, Type *CondTy,
526 bool IsUnsigned) const {
528 TTIImpl->getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned);
529 assert(Cost >= 0 && "TTI should not produce negative costs!");
534 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const {
535 return TTIImpl->getCostOfKeepingLiveOverCall(Tys);
538 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst,
539 MemIntrinsicInfo &Info) const {
540 return TTIImpl->getTgtMemIntrinsic(Inst, Info);
543 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const {
544 return TTIImpl->getAtomicMemIntrinsicMaxElementSize();
547 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic(
548 IntrinsicInst *Inst, Type *ExpectedType) const {
549 return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
552 Type *TargetTransformInfo::getMemcpyLoopLoweringType(LLVMContext &Context,
555 unsigned DestAlign) const {
556 return TTIImpl->getMemcpyLoopLoweringType(Context, Length, SrcAlign,
560 void TargetTransformInfo::getMemcpyLoopResidualLoweringType(
561 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
562 unsigned RemainingBytes, unsigned SrcAlign, unsigned DestAlign) const {
563 TTIImpl->getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
564 SrcAlign, DestAlign);
567 bool TargetTransformInfo::areInlineCompatible(const Function *Caller,
568 const Function *Callee) const {
569 return TTIImpl->areInlineCompatible(Caller, Callee);
572 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode,
574 return TTIImpl->isIndexedLoadLegal(Mode, Ty);
577 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode,
579 return TTIImpl->isIndexedStoreLegal(Mode, Ty);
582 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const {
583 return TTIImpl->getLoadStoreVecRegBitWidth(AS);
586 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const {
587 return TTIImpl->isLegalToVectorizeLoad(LI);
590 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const {
591 return TTIImpl->isLegalToVectorizeStore(SI);
594 bool TargetTransformInfo::isLegalToVectorizeLoadChain(
595 unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const {
596 return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
600 bool TargetTransformInfo::isLegalToVectorizeStoreChain(
601 unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const {
602 return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
606 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF,
608 unsigned ChainSizeInBytes,
609 VectorType *VecTy) const {
610 return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
613 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF,
615 unsigned ChainSizeInBytes,
616 VectorType *VecTy) const {
617 return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
620 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode,
621 Type *Ty, ReductionFlags Flags) const {
622 return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags);
625 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const {
626 return TTIImpl->shouldExpandReduction(II);
629 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const {
630 return TTIImpl->getInstructionLatency(I);
633 static TargetTransformInfo::OperandValueKind
634 getOperandInfo(Value *V, TargetTransformInfo::OperandValueProperties &OpProps) {
635 TargetTransformInfo::OperandValueKind OpInfo =
636 TargetTransformInfo::OK_AnyValue;
637 OpProps = TargetTransformInfo::OP_None;
639 if (auto *CI = dyn_cast<ConstantInt>(V)) {
640 if (CI->getValue().isPowerOf2())
641 OpProps = TargetTransformInfo::OP_PowerOf2;
642 return TargetTransformInfo::OK_UniformConstantValue;
645 const Value *Splat = getSplatValue(V);
647 // Check for a splat of a constant or for a non uniform vector of constants
648 // and check if the constant(s) are all powers of two.
649 if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) {
650 OpInfo = TargetTransformInfo::OK_NonUniformConstantValue;
652 OpInfo = TargetTransformInfo::OK_UniformConstantValue;
653 if (auto *CI = dyn_cast<ConstantInt>(Splat))
654 if (CI->getValue().isPowerOf2())
655 OpProps = TargetTransformInfo::OP_PowerOf2;
656 } else if (auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
657 OpProps = TargetTransformInfo::OP_PowerOf2;
658 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
659 if (auto *CI = dyn_cast<ConstantInt>(CDS->getElementAsConstant(I)))
660 if (CI->getValue().isPowerOf2())
662 OpProps = TargetTransformInfo::OP_None;
668 // Check for a splat of a uniform value. This is not loop aware, so return
669 // true only for the obviously uniform cases (argument, globalvalue)
670 if (Splat && (isa<Argument>(Splat) || isa<GlobalValue>(Splat)))
671 OpInfo = TargetTransformInfo::OK_UniformValue;
676 static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft,
678 // We don't need a shuffle if we just want to have element 0 in position 0 of
680 if (!SI && Level == 0 && IsLeft)
685 SmallVector<int, 32> Mask(SI->getType()->getVectorNumElements(), -1);
687 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
688 // we look at the left or right side.
689 for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2)
692 SmallVector<int, 16> ActualMask = SI->getShuffleMask();
693 return Mask == ActualMask;
697 /// Kind of the reduction data.
699 RK_None, /// Not a reduction.
700 RK_Arithmetic, /// Binary reduction data.
701 RK_MinMax, /// Min/max reduction data.
702 RK_UnsignedMinMax, /// Unsigned min/max reduction data.
704 /// Contains opcode + LHS/RHS parts of the reduction operations.
705 struct ReductionData {
706 ReductionData() = delete;
707 ReductionData(ReductionKind Kind, unsigned Opcode, Value *LHS, Value *RHS)
708 : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind) {
709 assert(Kind != RK_None && "expected binary or min/max reduction only.");
712 Value *LHS = nullptr;
713 Value *RHS = nullptr;
714 ReductionKind Kind = RK_None;
715 bool hasSameData(ReductionData &RD) const {
716 return Kind == RD.Kind && Opcode == RD.Opcode;
721 static Optional<ReductionData> getReductionData(Instruction *I) {
723 if (m_BinOp(m_Value(L), m_Value(R)).match(I))
724 return ReductionData(RK_Arithmetic, I->getOpcode(), L, R);
725 if (auto *SI = dyn_cast<SelectInst>(I)) {
726 if (m_SMin(m_Value(L), m_Value(R)).match(SI) ||
727 m_SMax(m_Value(L), m_Value(R)).match(SI) ||
728 m_OrdFMin(m_Value(L), m_Value(R)).match(SI) ||
729 m_OrdFMax(m_Value(L), m_Value(R)).match(SI) ||
730 m_UnordFMin(m_Value(L), m_Value(R)).match(SI) ||
731 m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) {
732 auto *CI = cast<CmpInst>(SI->getCondition());
733 return ReductionData(RK_MinMax, CI->getOpcode(), L, R);
735 if (m_UMin(m_Value(L), m_Value(R)).match(SI) ||
736 m_UMax(m_Value(L), m_Value(R)).match(SI)) {
737 auto *CI = cast<CmpInst>(SI->getCondition());
738 return ReductionData(RK_UnsignedMinMax, CI->getOpcode(), L, R);
744 static ReductionKind matchPairwiseReductionAtLevel(Instruction *I,
746 unsigned NumLevels) {
747 // Match one level of pairwise operations.
748 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
749 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
750 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
751 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
752 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
756 assert(I->getType()->isVectorTy() && "Expecting a vector type");
758 Optional<ReductionData> RD = getReductionData(I);
762 ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS);
765 ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS);
769 // On level 0 we can omit one shufflevector instruction.
770 if (!Level && !RS && !LS)
773 // Shuffle inputs must match.
774 Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr;
775 Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr;
776 Value *NextLevelOp = nullptr;
777 if (NextLevelOpR && NextLevelOpL) {
778 // If we have two shuffles their operands must match.
779 if (NextLevelOpL != NextLevelOpR)
782 NextLevelOp = NextLevelOpL;
783 } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) {
784 // On the first level we can omit the shufflevector <0, undef,...>. So the
785 // input to the other shufflevector <1, undef> must match with one of the
786 // inputs to the current binary operation.
788 // %NextLevelOpL = shufflevector %R, <1, undef ...>
789 // %BinOp = fadd %NextLevelOpL, %R
790 if (NextLevelOpL && NextLevelOpL != RD->RHS)
792 else if (NextLevelOpR && NextLevelOpR != RD->LHS)
795 NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS;
799 // Check that the next levels binary operation exists and matches with the
801 if (Level + 1 != NumLevels) {
802 Optional<ReductionData> NextLevelRD =
803 getReductionData(cast<Instruction>(NextLevelOp));
804 if (!NextLevelRD || !RD->hasSameData(*NextLevelRD))
808 // Shuffle mask for pairwise operation must match.
809 if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) {
810 if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level))
812 } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) {
813 if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level))
819 if (++Level == NumLevels)
823 return matchPairwiseReductionAtLevel(cast<Instruction>(NextLevelOp), Level,
827 static ReductionKind matchPairwiseReduction(const ExtractElementInst *ReduxRoot,
828 unsigned &Opcode, Type *&Ty) {
829 if (!EnableReduxCost)
832 // Need to extract the first element.
833 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
836 Idx = CI->getZExtValue();
840 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
843 Optional<ReductionData> RD = getReductionData(RdxStart);
847 Type *VecTy = RdxStart->getType();
848 unsigned NumVecElems = VecTy->getVectorNumElements();
849 if (!isPowerOf2_32(NumVecElems))
852 // We look for a sequence of shuffle,shuffle,add triples like the following
853 // that builds a pairwise reduction tree.
856 // (X0 + X1, X2 + X3, undef, undef)
857 // ((X0 + X1) + (X2 + X3), undef, undef, undef)
859 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
860 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
861 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
862 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
863 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
864 // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
865 // <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
866 // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
867 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
868 // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
869 // %r = extractelement <4 x float> %bin.rdx8, i32 0
870 if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) ==
880 static std::pair<Value *, ShuffleVectorInst *>
881 getShuffleAndOtherOprd(Value *L, Value *R) {
882 ShuffleVectorInst *S = nullptr;
884 if ((S = dyn_cast<ShuffleVectorInst>(L)))
885 return std::make_pair(R, S);
887 S = dyn_cast<ShuffleVectorInst>(R);
888 return std::make_pair(L, S);
892 matchVectorSplittingReduction(const ExtractElementInst *ReduxRoot,
893 unsigned &Opcode, Type *&Ty) {
894 if (!EnableReduxCost)
897 // Need to extract the first element.
898 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
901 Idx = CI->getZExtValue();
905 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
908 Optional<ReductionData> RD = getReductionData(RdxStart);
912 Type *VecTy = ReduxRoot->getOperand(0)->getType();
913 unsigned NumVecElems = VecTy->getVectorNumElements();
914 if (!isPowerOf2_32(NumVecElems))
917 // We look for a sequence of shuffles and adds like the following matching one
918 // fadd, shuffle vector pair at a time.
920 // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
921 // <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
922 // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
923 // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
924 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
925 // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
926 // %r = extractelement <4 x float> %bin.rdx8, i32 0
928 unsigned MaskStart = 1;
929 Instruction *RdxOp = RdxStart;
930 SmallVector<int, 32> ShuffleMask(NumVecElems, 0);
931 unsigned NumVecElemsRemain = NumVecElems;
932 while (NumVecElemsRemain - 1) {
933 // Check for the right reduction operation.
936 Optional<ReductionData> RDLevel = getReductionData(RdxOp);
937 if (!RDLevel || !RDLevel->hasSameData(*RD))
941 ShuffleVectorInst *Shuffle;
942 std::tie(NextRdxOp, Shuffle) =
943 getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS);
945 // Check the current reduction operation and the shuffle use the same value.
946 if (Shuffle == nullptr)
948 if (Shuffle->getOperand(0) != NextRdxOp)
951 // Check that shuffle masks matches.
952 for (unsigned j = 0; j != MaskStart; ++j)
953 ShuffleMask[j] = MaskStart + j;
954 // Fill the rest of the mask with -1 for undef.
955 std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1);
957 SmallVector<int, 16> Mask = Shuffle->getShuffleMask();
958 if (ShuffleMask != Mask)
961 RdxOp = dyn_cast<Instruction>(NextRdxOp);
962 NumVecElemsRemain /= 2;
971 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const {
972 switch (I->getOpcode()) {
973 case Instruction::GetElementPtr:
974 return getUserCost(I);
976 case Instruction::Ret:
977 case Instruction::PHI:
978 case Instruction::Br: {
979 return getCFInstrCost(I->getOpcode());
981 case Instruction::Add:
982 case Instruction::FAdd:
983 case Instruction::Sub:
984 case Instruction::FSub:
985 case Instruction::Mul:
986 case Instruction::FMul:
987 case Instruction::UDiv:
988 case Instruction::SDiv:
989 case Instruction::FDiv:
990 case Instruction::URem:
991 case Instruction::SRem:
992 case Instruction::FRem:
993 case Instruction::Shl:
994 case Instruction::LShr:
995 case Instruction::AShr:
996 case Instruction::And:
997 case Instruction::Or:
998 case Instruction::Xor: {
999 TargetTransformInfo::OperandValueKind Op1VK, Op2VK;
1000 TargetTransformInfo::OperandValueProperties Op1VP, Op2VP;
1001 Op1VK = getOperandInfo(I->getOperand(0), Op1VP);
1002 Op2VK = getOperandInfo(I->getOperand(1), Op2VP);
1003 SmallVector<const Value *, 2> Operands(I->operand_values());
1004 return getArithmeticInstrCost(I->getOpcode(), I->getType(), Op1VK, Op2VK,
1005 Op1VP, Op2VP, Operands);
1007 case Instruction::Select: {
1008 const SelectInst *SI = cast<SelectInst>(I);
1009 Type *CondTy = SI->getCondition()->getType();
1010 return getCmpSelInstrCost(I->getOpcode(), I->getType(), CondTy, I);
1012 case Instruction::ICmp:
1013 case Instruction::FCmp: {
1014 Type *ValTy = I->getOperand(0)->getType();
1015 return getCmpSelInstrCost(I->getOpcode(), ValTy, I->getType(), I);
1017 case Instruction::Store: {
1018 const StoreInst *SI = cast<StoreInst>(I);
1019 Type *ValTy = SI->getValueOperand()->getType();
1020 return getMemoryOpCost(I->getOpcode(), ValTy,
1022 SI->getPointerAddressSpace(), I);
1024 case Instruction::Load: {
1025 const LoadInst *LI = cast<LoadInst>(I);
1026 return getMemoryOpCost(I->getOpcode(), I->getType(),
1028 LI->getPointerAddressSpace(), I);
1030 case Instruction::ZExt:
1031 case Instruction::SExt:
1032 case Instruction::FPToUI:
1033 case Instruction::FPToSI:
1034 case Instruction::FPExt:
1035 case Instruction::PtrToInt:
1036 case Instruction::IntToPtr:
1037 case Instruction::SIToFP:
1038 case Instruction::UIToFP:
1039 case Instruction::Trunc:
1040 case Instruction::FPTrunc:
1041 case Instruction::BitCast:
1042 case Instruction::AddrSpaceCast: {
1043 Type *SrcTy = I->getOperand(0)->getType();
1044 return getCastInstrCost(I->getOpcode(), I->getType(), SrcTy, I);
1046 case Instruction::ExtractElement: {
1047 const ExtractElementInst * EEI = cast<ExtractElementInst>(I);
1048 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1051 Idx = CI->getZExtValue();
1053 // Try to match a reduction sequence (series of shufflevector and vector
1054 // adds followed by a extractelement).
1055 unsigned ReduxOpCode;
1058 switch (matchVectorSplittingReduction(EEI, ReduxOpCode, ReduxType)) {
1060 return getArithmeticReductionCost(ReduxOpCode, ReduxType,
1061 /*IsPairwiseForm=*/false);
1063 return getMinMaxReductionCost(
1064 ReduxType, CmpInst::makeCmpResultType(ReduxType),
1065 /*IsPairwiseForm=*/false, /*IsUnsigned=*/false);
1066 case RK_UnsignedMinMax:
1067 return getMinMaxReductionCost(
1068 ReduxType, CmpInst::makeCmpResultType(ReduxType),
1069 /*IsPairwiseForm=*/false, /*IsUnsigned=*/true);
1074 switch (matchPairwiseReduction(EEI, ReduxOpCode, ReduxType)) {
1076 return getArithmeticReductionCost(ReduxOpCode, ReduxType,
1077 /*IsPairwiseForm=*/true);
1079 return getMinMaxReductionCost(
1080 ReduxType, CmpInst::makeCmpResultType(ReduxType),
1081 /*IsPairwiseForm=*/true, /*IsUnsigned=*/false);
1082 case RK_UnsignedMinMax:
1083 return getMinMaxReductionCost(
1084 ReduxType, CmpInst::makeCmpResultType(ReduxType),
1085 /*IsPairwiseForm=*/true, /*IsUnsigned=*/true);
1090 return getVectorInstrCost(I->getOpcode(),
1091 EEI->getOperand(0)->getType(), Idx);
1093 case Instruction::InsertElement: {
1094 const InsertElementInst * IE = cast<InsertElementInst>(I);
1095 ConstantInt *CI = dyn_cast<ConstantInt>(IE->getOperand(2));
1098 Idx = CI->getZExtValue();
1099 return getVectorInstrCost(I->getOpcode(),
1100 IE->getType(), Idx);
1102 case Instruction::ShuffleVector: {
1103 const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1104 // TODO: Identify and add costs for insert/extract subvector, etc.
1105 if (Shuffle->changesLength())
1108 if (Shuffle->isIdentity())
1111 Type *Ty = Shuffle->getType();
1112 if (Shuffle->isReverse())
1113 return TTIImpl->getShuffleCost(SK_Reverse, Ty, 0, nullptr);
1115 if (Shuffle->isSelect())
1116 return TTIImpl->getShuffleCost(SK_Select, Ty, 0, nullptr);
1118 if (Shuffle->isTranspose())
1119 return TTIImpl->getShuffleCost(SK_Transpose, Ty, 0, nullptr);
1121 if (Shuffle->isZeroEltSplat())
1122 return TTIImpl->getShuffleCost(SK_Broadcast, Ty, 0, nullptr);
1124 if (Shuffle->isSingleSource())
1125 return TTIImpl->getShuffleCost(SK_PermuteSingleSrc, Ty, 0, nullptr);
1127 return TTIImpl->getShuffleCost(SK_PermuteTwoSrc, Ty, 0, nullptr);
1129 case Instruction::Call:
1130 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1131 SmallVector<Value *, 4> Args(II->arg_operands());
1134 if (auto *FPMO = dyn_cast<FPMathOperator>(II))
1135 FMF = FPMO->getFastMathFlags();
1137 return getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(),
1142 // We don't have any information on this instruction.
1147 TargetTransformInfo::Concept::~Concept() {}
1149 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {}
1151 TargetIRAnalysis::TargetIRAnalysis(
1152 std::function<Result(const Function &)> TTICallback)
1153 : TTICallback(std::move(TTICallback)) {}
1155 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F,
1156 FunctionAnalysisManager &) {
1157 return TTICallback(F);
1160 AnalysisKey TargetIRAnalysis::Key;
1162 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) {
1163 return Result(F.getParent()->getDataLayout());
1166 // Register the basic pass.
1167 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti",
1168 "Target Transform Information", false, true)
1169 char TargetTransformInfoWrapperPass::ID = 0;
1171 void TargetTransformInfoWrapperPass::anchor() {}
1173 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass()
1174 : ImmutablePass(ID) {
1175 initializeTargetTransformInfoWrapperPassPass(
1176 *PassRegistry::getPassRegistry());
1179 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass(
1180 TargetIRAnalysis TIRA)
1181 : ImmutablePass(ID), TIRA(std::move(TIRA)) {
1182 initializeTargetTransformInfoWrapperPassPass(
1183 *PassRegistry::getPassRegistry());
1186 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) {
1187 FunctionAnalysisManager DummyFAM;
1188 TTI = TIRA.run(F, DummyFAM);
1193 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) {
1194 return new TargetTransformInfoWrapperPass(std::move(TIRA));