1 //===- llvm/Analysis/TargetTransformInfo.cpp ------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Analysis/TargetTransformInfo.h"
10 #include "llvm/Analysis/TargetTransformInfoImpl.h"
11 #include "llvm/IR/CallSite.h"
12 #include "llvm/IR/CFG.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"
22 #include "llvm/Analysis/CFG.h"
23 #include "llvm/Analysis/LoopIterator.h"
27 using namespace PatternMatch
;
29 #define DEBUG_TYPE "tti"
31 static cl::opt
<bool> EnableReduxCost("costmodel-reduxcost", cl::init(false),
33 cl::desc("Recognize reduction patterns."));
36 /// No-op implementation of the TTI interface using the utility base
39 /// This is used when no target specific information is available.
40 struct NoTTIImpl
: TargetTransformInfoImplCRTPBase
<NoTTIImpl
> {
41 explicit NoTTIImpl(const DataLayout
&DL
)
42 : TargetTransformInfoImplCRTPBase
<NoTTIImpl
>(DL
) {}
44 unsigned getCacheLineSize() const { return 0; }
46 llvm::Optional
<unsigned> getCacheSize(TargetTransformInfo::CacheLevel Level
) const {
48 case TargetTransformInfo::CacheLevel::L1D
:
50 case TargetTransformInfo::CacheLevel::L2D
:
51 return llvm::Optional
<unsigned>();
53 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
56 llvm::Optional
<unsigned> getCacheAssociativity(
57 TargetTransformInfo::CacheLevel Level
) const {
59 case TargetTransformInfo::CacheLevel::L1D
:
61 case TargetTransformInfo::CacheLevel::L2D
:
62 return llvm::Optional
<unsigned>();
65 llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
68 unsigned getPrefetchDistance() const { return 0; }
69 unsigned getMinPrefetchStride() const { return 1; }
70 unsigned getMaxPrefetchIterationsAhead() const { return UINT_MAX
; }
74 bool HardwareLoopInfo::canAnalyze(LoopInfo
&LI
) {
75 // If the loop has irreducible control flow, it can not be converted to
77 LoopBlocksRPO
RPOT(L
);
79 if (containsIrreducibleCFG
<const BasicBlock
*>(RPOT
, LI
))
84 bool HardwareLoopInfo::isHardwareLoopCandidate(ScalarEvolution
&SE
,
85 LoopInfo
&LI
, DominatorTree
&DT
,
87 bool ForceHardwareLoopPHI
) {
88 SmallVector
<BasicBlock
*, 4> ExitingBlocks
;
89 L
->getExitingBlocks(ExitingBlocks
);
91 for (BasicBlock
*BB
: ExitingBlocks
) {
92 // If we pass the updated counter back through a phi, we need to know
93 // which latch the updated value will be coming from.
94 if (!L
->isLoopLatch(BB
)) {
95 if (ForceHardwareLoopPHI
|| CounterInReg
)
99 const SCEV
*EC
= SE
.getExitCount(L
, BB
);
100 if (isa
<SCEVCouldNotCompute
>(EC
))
102 if (const SCEVConstant
*ConstEC
= dyn_cast
<SCEVConstant
>(EC
)) {
103 if (ConstEC
->getValue()->isZero())
105 } else if (!SE
.isLoopInvariant(EC
, L
))
108 if (SE
.getTypeSizeInBits(EC
->getType()) > CountType
->getBitWidth())
111 // If this exiting block is contained in a nested loop, it is not eligible
112 // for insertion of the branch-and-decrement since the inner loop would
113 // end up messing up the value in the CTR.
114 if (!IsNestingLegal
&& LI
.getLoopFor(BB
) != L
&& !ForceNestedLoop
)
117 // We now have a loop-invariant count of loop iterations (which is not the
118 // constant zero) for which we know that this loop will not exit via this
121 // We need to make sure that this block will run on every loop iteration.
122 // For this to be true, we must dominate all blocks with backedges. Such
123 // blocks are in-loop predecessors to the header block.
124 bool NotAlways
= false;
125 for (BasicBlock
*Pred
: predecessors(L
->getHeader())) {
126 if (!L
->contains(Pred
))
129 if (!DT
.dominates(BB
, Pred
)) {
138 // Make sure this blocks ends with a conditional branch.
139 Instruction
*TI
= BB
->getTerminator();
143 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
)) {
144 if (!BI
->isConditional())
151 // Note that this block may not be the loop latch block, even if the loop
152 // has a latch block.
163 TargetTransformInfo::TargetTransformInfo(const DataLayout
&DL
)
164 : TTIImpl(new Model
<NoTTIImpl
>(NoTTIImpl(DL
))) {}
166 TargetTransformInfo::~TargetTransformInfo() {}
168 TargetTransformInfo::TargetTransformInfo(TargetTransformInfo
&&Arg
)
169 : TTIImpl(std::move(Arg
.TTIImpl
)) {}
171 TargetTransformInfo
&TargetTransformInfo::operator=(TargetTransformInfo
&&RHS
) {
172 TTIImpl
= std::move(RHS
.TTIImpl
);
176 int TargetTransformInfo::getOperationCost(unsigned Opcode
, Type
*Ty
,
178 int Cost
= TTIImpl
->getOperationCost(Opcode
, Ty
, OpTy
);
179 assert(Cost
>= 0 && "TTI should not produce negative costs!");
183 int TargetTransformInfo::getCallCost(FunctionType
*FTy
, int NumArgs
,
184 const User
*U
) const {
185 int Cost
= TTIImpl
->getCallCost(FTy
, NumArgs
, U
);
186 assert(Cost
>= 0 && "TTI should not produce negative costs!");
190 int TargetTransformInfo::getCallCost(const Function
*F
,
191 ArrayRef
<const Value
*> Arguments
,
192 const User
*U
) const {
193 int Cost
= TTIImpl
->getCallCost(F
, Arguments
, U
);
194 assert(Cost
>= 0 && "TTI should not produce negative costs!");
198 unsigned TargetTransformInfo::getInliningThresholdMultiplier() const {
199 return TTIImpl
->getInliningThresholdMultiplier();
202 int TargetTransformInfo::getInlinerVectorBonusPercent() const {
203 return TTIImpl
->getInlinerVectorBonusPercent();
206 int TargetTransformInfo::getGEPCost(Type
*PointeeType
, const Value
*Ptr
,
207 ArrayRef
<const Value
*> Operands
) const {
208 return TTIImpl
->getGEPCost(PointeeType
, Ptr
, Operands
);
211 int TargetTransformInfo::getExtCost(const Instruction
*I
,
212 const Value
*Src
) const {
213 return TTIImpl
->getExtCost(I
, Src
);
216 int TargetTransformInfo::getIntrinsicCost(
217 Intrinsic::ID IID
, Type
*RetTy
, ArrayRef
<const Value
*> Arguments
,
218 const User
*U
) const {
219 int Cost
= TTIImpl
->getIntrinsicCost(IID
, RetTy
, Arguments
, U
);
220 assert(Cost
>= 0 && "TTI should not produce negative costs!");
225 TargetTransformInfo::getEstimatedNumberOfCaseClusters(const SwitchInst
&SI
,
226 unsigned &JTSize
) const {
227 return TTIImpl
->getEstimatedNumberOfCaseClusters(SI
, JTSize
);
230 int TargetTransformInfo::getUserCost(const User
*U
,
231 ArrayRef
<const Value
*> Operands
) const {
232 int Cost
= TTIImpl
->getUserCost(U
, Operands
);
233 assert(Cost
>= 0 && "TTI should not produce negative costs!");
237 bool TargetTransformInfo::hasBranchDivergence() const {
238 return TTIImpl
->hasBranchDivergence();
241 bool TargetTransformInfo::isSourceOfDivergence(const Value
*V
) const {
242 return TTIImpl
->isSourceOfDivergence(V
);
245 bool llvm::TargetTransformInfo::isAlwaysUniform(const Value
*V
) const {
246 return TTIImpl
->isAlwaysUniform(V
);
249 unsigned TargetTransformInfo::getFlatAddressSpace() const {
250 return TTIImpl
->getFlatAddressSpace();
253 bool TargetTransformInfo::collectFlatAddressOperands(
254 SmallVectorImpl
<int> &OpIndexes
, Intrinsic::ID IID
) const {
255 return TTIImpl
->collectFlatAddressOperands(OpIndexes
, IID
);
258 bool TargetTransformInfo::rewriteIntrinsicWithAddressSpace(
259 IntrinsicInst
*II
, Value
*OldV
, Value
*NewV
) const {
260 return TTIImpl
->rewriteIntrinsicWithAddressSpace(II
, OldV
, NewV
);
263 bool TargetTransformInfo::isLoweredToCall(const Function
*F
) const {
264 return TTIImpl
->isLoweredToCall(F
);
267 bool TargetTransformInfo::isHardwareLoopProfitable(
268 Loop
*L
, ScalarEvolution
&SE
, AssumptionCache
&AC
,
269 TargetLibraryInfo
*LibInfo
, HardwareLoopInfo
&HWLoopInfo
) const {
270 return TTIImpl
->isHardwareLoopProfitable(L
, SE
, AC
, LibInfo
, HWLoopInfo
);
273 void TargetTransformInfo::getUnrollingPreferences(
274 Loop
*L
, ScalarEvolution
&SE
, UnrollingPreferences
&UP
) const {
275 return TTIImpl
->getUnrollingPreferences(L
, SE
, UP
);
278 bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm
) const {
279 return TTIImpl
->isLegalAddImmediate(Imm
);
282 bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm
) const {
283 return TTIImpl
->isLegalICmpImmediate(Imm
);
286 bool TargetTransformInfo::isLegalAddressingMode(Type
*Ty
, GlobalValue
*BaseGV
,
291 Instruction
*I
) const {
292 return TTIImpl
->isLegalAddressingMode(Ty
, BaseGV
, BaseOffset
, HasBaseReg
,
293 Scale
, AddrSpace
, I
);
296 bool TargetTransformInfo::isLSRCostLess(LSRCost
&C1
, LSRCost
&C2
) const {
297 return TTIImpl
->isLSRCostLess(C1
, C2
);
300 bool TargetTransformInfo::canMacroFuseCmp() const {
301 return TTIImpl
->canMacroFuseCmp();
304 bool TargetTransformInfo::canSaveCmp(Loop
*L
, BranchInst
**BI
,
305 ScalarEvolution
*SE
, LoopInfo
*LI
,
306 DominatorTree
*DT
, AssumptionCache
*AC
,
307 TargetLibraryInfo
*LibInfo
) const {
308 return TTIImpl
->canSaveCmp(L
, BI
, SE
, LI
, DT
, AC
, LibInfo
);
311 bool TargetTransformInfo::shouldFavorPostInc() const {
312 return TTIImpl
->shouldFavorPostInc();
315 bool TargetTransformInfo::shouldFavorBackedgeIndex(const Loop
*L
) const {
316 return TTIImpl
->shouldFavorBackedgeIndex(L
);
319 bool TargetTransformInfo::isLegalMaskedStore(Type
*DataType
) const {
320 return TTIImpl
->isLegalMaskedStore(DataType
);
323 bool TargetTransformInfo::isLegalMaskedLoad(Type
*DataType
) const {
324 return TTIImpl
->isLegalMaskedLoad(DataType
);
327 bool TargetTransformInfo::isLegalNTStore(Type
*DataType
,
328 Align Alignment
) const {
329 return TTIImpl
->isLegalNTStore(DataType
, Alignment
);
332 bool TargetTransformInfo::isLegalNTLoad(Type
*DataType
, Align Alignment
) const {
333 return TTIImpl
->isLegalNTLoad(DataType
, Alignment
);
336 bool TargetTransformInfo::isLegalMaskedGather(Type
*DataType
) const {
337 return TTIImpl
->isLegalMaskedGather(DataType
);
340 bool TargetTransformInfo::isLegalMaskedScatter(Type
*DataType
) const {
341 return TTIImpl
->isLegalMaskedScatter(DataType
);
344 bool TargetTransformInfo::isLegalMaskedCompressStore(Type
*DataType
) const {
345 return TTIImpl
->isLegalMaskedCompressStore(DataType
);
348 bool TargetTransformInfo::isLegalMaskedExpandLoad(Type
*DataType
) const {
349 return TTIImpl
->isLegalMaskedExpandLoad(DataType
);
352 bool TargetTransformInfo::hasDivRemOp(Type
*DataType
, bool IsSigned
) const {
353 return TTIImpl
->hasDivRemOp(DataType
, IsSigned
);
356 bool TargetTransformInfo::hasVolatileVariant(Instruction
*I
,
357 unsigned AddrSpace
) const {
358 return TTIImpl
->hasVolatileVariant(I
, AddrSpace
);
361 bool TargetTransformInfo::prefersVectorizedAddressing() const {
362 return TTIImpl
->prefersVectorizedAddressing();
365 int TargetTransformInfo::getScalingFactorCost(Type
*Ty
, GlobalValue
*BaseGV
,
369 unsigned AddrSpace
) const {
370 int Cost
= TTIImpl
->getScalingFactorCost(Ty
, BaseGV
, BaseOffset
, HasBaseReg
,
372 assert(Cost
>= 0 && "TTI should not produce negative costs!");
376 bool TargetTransformInfo::LSRWithInstrQueries() const {
377 return TTIImpl
->LSRWithInstrQueries();
380 bool TargetTransformInfo::isTruncateFree(Type
*Ty1
, Type
*Ty2
) const {
381 return TTIImpl
->isTruncateFree(Ty1
, Ty2
);
384 bool TargetTransformInfo::isProfitableToHoist(Instruction
*I
) const {
385 return TTIImpl
->isProfitableToHoist(I
);
388 bool TargetTransformInfo::useAA() const { return TTIImpl
->useAA(); }
390 bool TargetTransformInfo::isTypeLegal(Type
*Ty
) const {
391 return TTIImpl
->isTypeLegal(Ty
);
394 bool TargetTransformInfo::shouldBuildLookupTables() const {
395 return TTIImpl
->shouldBuildLookupTables();
397 bool TargetTransformInfo::shouldBuildLookupTablesForConstant(Constant
*C
) const {
398 return TTIImpl
->shouldBuildLookupTablesForConstant(C
);
401 bool TargetTransformInfo::useColdCCForColdCall(Function
&F
) const {
402 return TTIImpl
->useColdCCForColdCall(F
);
405 unsigned TargetTransformInfo::
406 getScalarizationOverhead(Type
*Ty
, bool Insert
, bool Extract
) const {
407 return TTIImpl
->getScalarizationOverhead(Ty
, Insert
, Extract
);
410 unsigned TargetTransformInfo::
411 getOperandsScalarizationOverhead(ArrayRef
<const Value
*> Args
,
413 return TTIImpl
->getOperandsScalarizationOverhead(Args
, VF
);
416 bool TargetTransformInfo::supportsEfficientVectorElementLoadStore() const {
417 return TTIImpl
->supportsEfficientVectorElementLoadStore();
420 bool TargetTransformInfo::enableAggressiveInterleaving(bool LoopHasReductions
) const {
421 return TTIImpl
->enableAggressiveInterleaving(LoopHasReductions
);
424 TargetTransformInfo::MemCmpExpansionOptions
425 TargetTransformInfo::enableMemCmpExpansion(bool OptSize
, bool IsZeroCmp
) const {
426 return TTIImpl
->enableMemCmpExpansion(OptSize
, IsZeroCmp
);
429 bool TargetTransformInfo::enableInterleavedAccessVectorization() const {
430 return TTIImpl
->enableInterleavedAccessVectorization();
433 bool TargetTransformInfo::enableMaskedInterleavedAccessVectorization() const {
434 return TTIImpl
->enableMaskedInterleavedAccessVectorization();
437 bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const {
438 return TTIImpl
->isFPVectorizationPotentiallyUnsafe();
441 bool TargetTransformInfo::allowsMisalignedMemoryAccesses(LLVMContext
&Context
,
443 unsigned AddressSpace
,
446 return TTIImpl
->allowsMisalignedMemoryAccesses(Context
, BitWidth
, AddressSpace
,
450 TargetTransformInfo::PopcntSupportKind
451 TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit
) const {
452 return TTIImpl
->getPopcntSupport(IntTyWidthInBit
);
455 bool TargetTransformInfo::haveFastSqrt(Type
*Ty
) const {
456 return TTIImpl
->haveFastSqrt(Ty
);
459 bool TargetTransformInfo::isFCmpOrdCheaperThanFCmpZero(Type
*Ty
) const {
460 return TTIImpl
->isFCmpOrdCheaperThanFCmpZero(Ty
);
463 int TargetTransformInfo::getFPOpCost(Type
*Ty
) const {
464 int Cost
= TTIImpl
->getFPOpCost(Ty
);
465 assert(Cost
>= 0 && "TTI should not produce negative costs!");
469 int TargetTransformInfo::getIntImmCodeSizeCost(unsigned Opcode
, unsigned Idx
,
472 int Cost
= TTIImpl
->getIntImmCodeSizeCost(Opcode
, Idx
, Imm
, Ty
);
473 assert(Cost
>= 0 && "TTI should not produce negative costs!");
477 int TargetTransformInfo::getIntImmCost(const APInt
&Imm
, Type
*Ty
) const {
478 int Cost
= TTIImpl
->getIntImmCost(Imm
, Ty
);
479 assert(Cost
>= 0 && "TTI should not produce negative costs!");
483 int TargetTransformInfo::getIntImmCost(unsigned Opcode
, unsigned Idx
,
484 const APInt
&Imm
, Type
*Ty
) const {
485 int Cost
= TTIImpl
->getIntImmCost(Opcode
, Idx
, Imm
, Ty
);
486 assert(Cost
>= 0 && "TTI should not produce negative costs!");
490 int TargetTransformInfo::getIntImmCost(Intrinsic::ID IID
, unsigned Idx
,
491 const APInt
&Imm
, Type
*Ty
) const {
492 int Cost
= TTIImpl
->getIntImmCost(IID
, Idx
, Imm
, Ty
);
493 assert(Cost
>= 0 && "TTI should not produce negative costs!");
497 unsigned TargetTransformInfo::getNumberOfRegisters(bool Vector
) const {
498 return TTIImpl
->getNumberOfRegisters(Vector
);
501 unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector
) const {
502 return TTIImpl
->getRegisterBitWidth(Vector
);
505 unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const {
506 return TTIImpl
->getMinVectorRegisterBitWidth();
509 bool TargetTransformInfo::shouldMaximizeVectorBandwidth(bool OptSize
) const {
510 return TTIImpl
->shouldMaximizeVectorBandwidth(OptSize
);
513 unsigned TargetTransformInfo::getMinimumVF(unsigned ElemWidth
) const {
514 return TTIImpl
->getMinimumVF(ElemWidth
);
517 bool TargetTransformInfo::shouldConsiderAddressTypePromotion(
518 const Instruction
&I
, bool &AllowPromotionWithoutCommonHeader
) const {
519 return TTIImpl
->shouldConsiderAddressTypePromotion(
520 I
, AllowPromotionWithoutCommonHeader
);
523 unsigned TargetTransformInfo::getCacheLineSize() const {
524 return TTIImpl
->getCacheLineSize();
527 llvm::Optional
<unsigned> TargetTransformInfo::getCacheSize(CacheLevel Level
)
529 return TTIImpl
->getCacheSize(Level
);
532 llvm::Optional
<unsigned> TargetTransformInfo::getCacheAssociativity(
533 CacheLevel Level
) const {
534 return TTIImpl
->getCacheAssociativity(Level
);
537 unsigned TargetTransformInfo::getPrefetchDistance() const {
538 return TTIImpl
->getPrefetchDistance();
541 unsigned TargetTransformInfo::getMinPrefetchStride() const {
542 return TTIImpl
->getMinPrefetchStride();
545 unsigned TargetTransformInfo::getMaxPrefetchIterationsAhead() const {
546 return TTIImpl
->getMaxPrefetchIterationsAhead();
549 unsigned TargetTransformInfo::getMaxInterleaveFactor(unsigned VF
) const {
550 return TTIImpl
->getMaxInterleaveFactor(VF
);
553 TargetTransformInfo::OperandValueKind
554 TargetTransformInfo::getOperandInfo(Value
*V
, OperandValueProperties
&OpProps
) {
555 OperandValueKind OpInfo
= OK_AnyValue
;
558 if (auto *CI
= dyn_cast
<ConstantInt
>(V
)) {
559 if (CI
->getValue().isPowerOf2())
560 OpProps
= OP_PowerOf2
;
561 return OK_UniformConstantValue
;
564 // A broadcast shuffle creates a uniform value.
565 // TODO: Add support for non-zero index broadcasts.
566 // TODO: Add support for different source vector width.
567 if (auto *ShuffleInst
= dyn_cast
<ShuffleVectorInst
>(V
))
568 if (ShuffleInst
->isZeroEltSplat())
569 OpInfo
= OK_UniformValue
;
571 const Value
*Splat
= getSplatValue(V
);
573 // Check for a splat of a constant or for a non uniform vector of constants
574 // and check if the constant(s) are all powers of two.
575 if (isa
<ConstantVector
>(V
) || isa
<ConstantDataVector
>(V
)) {
576 OpInfo
= OK_NonUniformConstantValue
;
578 OpInfo
= OK_UniformConstantValue
;
579 if (auto *CI
= dyn_cast
<ConstantInt
>(Splat
))
580 if (CI
->getValue().isPowerOf2())
581 OpProps
= OP_PowerOf2
;
582 } else if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(V
)) {
583 OpProps
= OP_PowerOf2
;
584 for (unsigned I
= 0, E
= CDS
->getNumElements(); I
!= E
; ++I
) {
585 if (auto *CI
= dyn_cast
<ConstantInt
>(CDS
->getElementAsConstant(I
)))
586 if (CI
->getValue().isPowerOf2())
594 // Check for a splat of a uniform value. This is not loop aware, so return
595 // true only for the obviously uniform cases (argument, globalvalue)
596 if (Splat
&& (isa
<Argument
>(Splat
) || isa
<GlobalValue
>(Splat
)))
597 OpInfo
= OK_UniformValue
;
602 int TargetTransformInfo::getArithmeticInstrCost(
603 unsigned Opcode
, Type
*Ty
, OperandValueKind Opd1Info
,
604 OperandValueKind Opd2Info
, OperandValueProperties Opd1PropInfo
,
605 OperandValueProperties Opd2PropInfo
,
606 ArrayRef
<const Value
*> Args
) const {
607 int Cost
= TTIImpl
->getArithmeticInstrCost(Opcode
, Ty
, Opd1Info
, Opd2Info
,
608 Opd1PropInfo
, Opd2PropInfo
, Args
);
609 assert(Cost
>= 0 && "TTI should not produce negative costs!");
613 int TargetTransformInfo::getShuffleCost(ShuffleKind Kind
, Type
*Ty
, int Index
,
615 int Cost
= TTIImpl
->getShuffleCost(Kind
, Ty
, Index
, SubTp
);
616 assert(Cost
>= 0 && "TTI should not produce negative costs!");
620 int TargetTransformInfo::getCastInstrCost(unsigned Opcode
, Type
*Dst
,
621 Type
*Src
, const Instruction
*I
) const {
622 assert ((I
== nullptr || I
->getOpcode() == Opcode
) &&
623 "Opcode should reflect passed instruction.");
624 int Cost
= TTIImpl
->getCastInstrCost(Opcode
, Dst
, Src
, I
);
625 assert(Cost
>= 0 && "TTI should not produce negative costs!");
629 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode
, Type
*Dst
,
631 unsigned Index
) const {
632 int Cost
= TTIImpl
->getExtractWithExtendCost(Opcode
, Dst
, VecTy
, Index
);
633 assert(Cost
>= 0 && "TTI should not produce negative costs!");
637 int TargetTransformInfo::getCFInstrCost(unsigned Opcode
) const {
638 int Cost
= TTIImpl
->getCFInstrCost(Opcode
);
639 assert(Cost
>= 0 && "TTI should not produce negative costs!");
643 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode
, Type
*ValTy
,
644 Type
*CondTy
, const Instruction
*I
) const {
645 assert ((I
== nullptr || I
->getOpcode() == Opcode
) &&
646 "Opcode should reflect passed instruction.");
647 int Cost
= TTIImpl
->getCmpSelInstrCost(Opcode
, ValTy
, CondTy
, I
);
648 assert(Cost
>= 0 && "TTI should not produce negative costs!");
652 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode
, Type
*Val
,
653 unsigned Index
) const {
654 int Cost
= TTIImpl
->getVectorInstrCost(Opcode
, Val
, Index
);
655 assert(Cost
>= 0 && "TTI should not produce negative costs!");
659 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode
, Type
*Src
,
661 unsigned AddressSpace
,
662 const Instruction
*I
) const {
663 assert ((I
== nullptr || I
->getOpcode() == Opcode
) &&
664 "Opcode should reflect passed instruction.");
665 int Cost
= TTIImpl
->getMemoryOpCost(Opcode
, Src
, Alignment
, AddressSpace
, I
);
666 assert(Cost
>= 0 && "TTI should not produce negative costs!");
670 int TargetTransformInfo::getMaskedMemoryOpCost(unsigned Opcode
, Type
*Src
,
672 unsigned AddressSpace
) const {
674 TTIImpl
->getMaskedMemoryOpCost(Opcode
, Src
, Alignment
, AddressSpace
);
675 assert(Cost
>= 0 && "TTI should not produce negative costs!");
679 int TargetTransformInfo::getGatherScatterOpCost(unsigned Opcode
, Type
*DataTy
,
680 Value
*Ptr
, bool VariableMask
,
681 unsigned Alignment
) const {
682 int Cost
= TTIImpl
->getGatherScatterOpCost(Opcode
, DataTy
, Ptr
, VariableMask
,
684 assert(Cost
>= 0 && "TTI should not produce negative costs!");
688 int TargetTransformInfo::getInterleavedMemoryOpCost(
689 unsigned Opcode
, Type
*VecTy
, unsigned Factor
, ArrayRef
<unsigned> Indices
,
690 unsigned Alignment
, unsigned AddressSpace
, bool UseMaskForCond
,
691 bool UseMaskForGaps
) const {
692 int Cost
= TTIImpl
->getInterleavedMemoryOpCost(Opcode
, VecTy
, Factor
, Indices
,
693 Alignment
, AddressSpace
,
696 assert(Cost
>= 0 && "TTI should not produce negative costs!");
700 int TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID
, Type
*RetTy
,
701 ArrayRef
<Type
*> Tys
, FastMathFlags FMF
,
702 unsigned ScalarizationCostPassed
) const {
703 int Cost
= TTIImpl
->getIntrinsicInstrCost(ID
, RetTy
, Tys
, FMF
,
704 ScalarizationCostPassed
);
705 assert(Cost
>= 0 && "TTI should not produce negative costs!");
709 int TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID
, Type
*RetTy
,
710 ArrayRef
<Value
*> Args
, FastMathFlags FMF
, unsigned VF
) const {
711 int Cost
= TTIImpl
->getIntrinsicInstrCost(ID
, RetTy
, Args
, FMF
, VF
);
712 assert(Cost
>= 0 && "TTI should not produce negative costs!");
716 int TargetTransformInfo::getCallInstrCost(Function
*F
, Type
*RetTy
,
717 ArrayRef
<Type
*> Tys
) const {
718 int Cost
= TTIImpl
->getCallInstrCost(F
, RetTy
, Tys
);
719 assert(Cost
>= 0 && "TTI should not produce negative costs!");
723 unsigned TargetTransformInfo::getNumberOfParts(Type
*Tp
) const {
724 return TTIImpl
->getNumberOfParts(Tp
);
727 int TargetTransformInfo::getAddressComputationCost(Type
*Tp
,
729 const SCEV
*Ptr
) const {
730 int Cost
= TTIImpl
->getAddressComputationCost(Tp
, SE
, Ptr
);
731 assert(Cost
>= 0 && "TTI should not produce negative costs!");
735 int TargetTransformInfo::getMemcpyCost(const Instruction
*I
) const {
736 int Cost
= TTIImpl
->getMemcpyCost(I
);
737 assert(Cost
>= 0 && "TTI should not produce negative costs!");
741 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode
, Type
*Ty
,
742 bool IsPairwiseForm
) const {
743 int Cost
= TTIImpl
->getArithmeticReductionCost(Opcode
, Ty
, IsPairwiseForm
);
744 assert(Cost
>= 0 && "TTI should not produce negative costs!");
748 int TargetTransformInfo::getMinMaxReductionCost(Type
*Ty
, Type
*CondTy
,
750 bool IsUnsigned
) const {
752 TTIImpl
->getMinMaxReductionCost(Ty
, CondTy
, IsPairwiseForm
, IsUnsigned
);
753 assert(Cost
>= 0 && "TTI should not produce negative costs!");
758 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef
<Type
*> Tys
) const {
759 return TTIImpl
->getCostOfKeepingLiveOverCall(Tys
);
762 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst
*Inst
,
763 MemIntrinsicInfo
&Info
) const {
764 return TTIImpl
->getTgtMemIntrinsic(Inst
, Info
);
767 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const {
768 return TTIImpl
->getAtomicMemIntrinsicMaxElementSize();
771 Value
*TargetTransformInfo::getOrCreateResultFromMemIntrinsic(
772 IntrinsicInst
*Inst
, Type
*ExpectedType
) const {
773 return TTIImpl
->getOrCreateResultFromMemIntrinsic(Inst
, ExpectedType
);
776 Type
*TargetTransformInfo::getMemcpyLoopLoweringType(LLVMContext
&Context
,
779 unsigned DestAlign
) const {
780 return TTIImpl
->getMemcpyLoopLoweringType(Context
, Length
, SrcAlign
,
784 void TargetTransformInfo::getMemcpyLoopResidualLoweringType(
785 SmallVectorImpl
<Type
*> &OpsOut
, LLVMContext
&Context
,
786 unsigned RemainingBytes
, unsigned SrcAlign
, unsigned DestAlign
) const {
787 TTIImpl
->getMemcpyLoopResidualLoweringType(OpsOut
, Context
, RemainingBytes
,
788 SrcAlign
, DestAlign
);
791 bool TargetTransformInfo::areInlineCompatible(const Function
*Caller
,
792 const Function
*Callee
) const {
793 return TTIImpl
->areInlineCompatible(Caller
, Callee
);
796 bool TargetTransformInfo::areFunctionArgsABICompatible(
797 const Function
*Caller
, const Function
*Callee
,
798 SmallPtrSetImpl
<Argument
*> &Args
) const {
799 return TTIImpl
->areFunctionArgsABICompatible(Caller
, Callee
, Args
);
802 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode
,
804 return TTIImpl
->isIndexedLoadLegal(Mode
, Ty
);
807 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode
,
809 return TTIImpl
->isIndexedStoreLegal(Mode
, Ty
);
812 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS
) const {
813 return TTIImpl
->getLoadStoreVecRegBitWidth(AS
);
816 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst
*LI
) const {
817 return TTIImpl
->isLegalToVectorizeLoad(LI
);
820 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst
*SI
) const {
821 return TTIImpl
->isLegalToVectorizeStore(SI
);
824 bool TargetTransformInfo::isLegalToVectorizeLoadChain(
825 unsigned ChainSizeInBytes
, unsigned Alignment
, unsigned AddrSpace
) const {
826 return TTIImpl
->isLegalToVectorizeLoadChain(ChainSizeInBytes
, Alignment
,
830 bool TargetTransformInfo::isLegalToVectorizeStoreChain(
831 unsigned ChainSizeInBytes
, unsigned Alignment
, unsigned AddrSpace
) const {
832 return TTIImpl
->isLegalToVectorizeStoreChain(ChainSizeInBytes
, Alignment
,
836 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF
,
838 unsigned ChainSizeInBytes
,
839 VectorType
*VecTy
) const {
840 return TTIImpl
->getLoadVectorFactor(VF
, LoadSize
, ChainSizeInBytes
, VecTy
);
843 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF
,
845 unsigned ChainSizeInBytes
,
846 VectorType
*VecTy
) const {
847 return TTIImpl
->getStoreVectorFactor(VF
, StoreSize
, ChainSizeInBytes
, VecTy
);
850 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode
,
851 Type
*Ty
, ReductionFlags Flags
) const {
852 return TTIImpl
->useReductionIntrinsic(Opcode
, Ty
, Flags
);
855 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst
*II
) const {
856 return TTIImpl
->shouldExpandReduction(II
);
859 unsigned TargetTransformInfo::getGISelRematGlobalCost() const {
860 return TTIImpl
->getGISelRematGlobalCost();
863 int TargetTransformInfo::getInstructionLatency(const Instruction
*I
) const {
864 return TTIImpl
->getInstructionLatency(I
);
867 static bool matchPairwiseShuffleMask(ShuffleVectorInst
*SI
, bool IsLeft
,
869 // We don't need a shuffle if we just want to have element 0 in position 0 of
871 if (!SI
&& Level
== 0 && IsLeft
)
876 SmallVector
<int, 32> Mask(SI
->getType()->getVectorNumElements(), -1);
878 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
879 // we look at the left or right side.
880 for (unsigned i
= 0, e
= (1 << Level
), val
= !IsLeft
; i
!= e
; ++i
, val
+= 2)
883 SmallVector
<int, 16> ActualMask
= SI
->getShuffleMask();
884 return Mask
== ActualMask
;
888 /// Kind of the reduction data.
890 RK_None
, /// Not a reduction.
891 RK_Arithmetic
, /// Binary reduction data.
892 RK_MinMax
, /// Min/max reduction data.
893 RK_UnsignedMinMax
, /// Unsigned min/max reduction data.
895 /// Contains opcode + LHS/RHS parts of the reduction operations.
896 struct ReductionData
{
897 ReductionData() = delete;
898 ReductionData(ReductionKind Kind
, unsigned Opcode
, Value
*LHS
, Value
*RHS
)
899 : Opcode(Opcode
), LHS(LHS
), RHS(RHS
), Kind(Kind
) {
900 assert(Kind
!= RK_None
&& "expected binary or min/max reduction only.");
903 Value
*LHS
= nullptr;
904 Value
*RHS
= nullptr;
905 ReductionKind Kind
= RK_None
;
906 bool hasSameData(ReductionData
&RD
) const {
907 return Kind
== RD
.Kind
&& Opcode
== RD
.Opcode
;
912 static Optional
<ReductionData
> getReductionData(Instruction
*I
) {
914 if (m_BinOp(m_Value(L
), m_Value(R
)).match(I
))
915 return ReductionData(RK_Arithmetic
, I
->getOpcode(), L
, R
);
916 if (auto *SI
= dyn_cast
<SelectInst
>(I
)) {
917 if (m_SMin(m_Value(L
), m_Value(R
)).match(SI
) ||
918 m_SMax(m_Value(L
), m_Value(R
)).match(SI
) ||
919 m_OrdFMin(m_Value(L
), m_Value(R
)).match(SI
) ||
920 m_OrdFMax(m_Value(L
), m_Value(R
)).match(SI
) ||
921 m_UnordFMin(m_Value(L
), m_Value(R
)).match(SI
) ||
922 m_UnordFMax(m_Value(L
), m_Value(R
)).match(SI
)) {
923 auto *CI
= cast
<CmpInst
>(SI
->getCondition());
924 return ReductionData(RK_MinMax
, CI
->getOpcode(), L
, R
);
926 if (m_UMin(m_Value(L
), m_Value(R
)).match(SI
) ||
927 m_UMax(m_Value(L
), m_Value(R
)).match(SI
)) {
928 auto *CI
= cast
<CmpInst
>(SI
->getCondition());
929 return ReductionData(RK_UnsignedMinMax
, CI
->getOpcode(), L
, R
);
935 static ReductionKind
matchPairwiseReductionAtLevel(Instruction
*I
,
937 unsigned NumLevels
) {
938 // Match one level of pairwise operations.
939 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
940 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
941 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
942 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
943 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
947 assert(I
->getType()->isVectorTy() && "Expecting a vector type");
949 Optional
<ReductionData
> RD
= getReductionData(I
);
953 ShuffleVectorInst
*LS
= dyn_cast
<ShuffleVectorInst
>(RD
->LHS
);
956 ShuffleVectorInst
*RS
= dyn_cast
<ShuffleVectorInst
>(RD
->RHS
);
960 // On level 0 we can omit one shufflevector instruction.
961 if (!Level
&& !RS
&& !LS
)
964 // Shuffle inputs must match.
965 Value
*NextLevelOpL
= LS
? LS
->getOperand(0) : nullptr;
966 Value
*NextLevelOpR
= RS
? RS
->getOperand(0) : nullptr;
967 Value
*NextLevelOp
= nullptr;
968 if (NextLevelOpR
&& NextLevelOpL
) {
969 // If we have two shuffles their operands must match.
970 if (NextLevelOpL
!= NextLevelOpR
)
973 NextLevelOp
= NextLevelOpL
;
974 } else if (Level
== 0 && (NextLevelOpR
|| NextLevelOpL
)) {
975 // On the first level we can omit the shufflevector <0, undef,...>. So the
976 // input to the other shufflevector <1, undef> must match with one of the
977 // inputs to the current binary operation.
979 // %NextLevelOpL = shufflevector %R, <1, undef ...>
980 // %BinOp = fadd %NextLevelOpL, %R
981 if (NextLevelOpL
&& NextLevelOpL
!= RD
->RHS
)
983 else if (NextLevelOpR
&& NextLevelOpR
!= RD
->LHS
)
986 NextLevelOp
= NextLevelOpL
? RD
->RHS
: RD
->LHS
;
990 // Check that the next levels binary operation exists and matches with the
992 if (Level
+ 1 != NumLevels
) {
993 Optional
<ReductionData
> NextLevelRD
=
994 getReductionData(cast
<Instruction
>(NextLevelOp
));
995 if (!NextLevelRD
|| !RD
->hasSameData(*NextLevelRD
))
999 // Shuffle mask for pairwise operation must match.
1000 if (matchPairwiseShuffleMask(LS
, /*IsLeft=*/true, Level
)) {
1001 if (!matchPairwiseShuffleMask(RS
, /*IsLeft=*/false, Level
))
1003 } else if (matchPairwiseShuffleMask(RS
, /*IsLeft=*/true, Level
)) {
1004 if (!matchPairwiseShuffleMask(LS
, /*IsLeft=*/false, Level
))
1010 if (++Level
== NumLevels
)
1013 // Match next level.
1014 return matchPairwiseReductionAtLevel(cast
<Instruction
>(NextLevelOp
), Level
,
1018 static ReductionKind
matchPairwiseReduction(const ExtractElementInst
*ReduxRoot
,
1019 unsigned &Opcode
, Type
*&Ty
) {
1020 if (!EnableReduxCost
)
1023 // Need to extract the first element.
1024 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(ReduxRoot
->getOperand(1));
1027 Idx
= CI
->getZExtValue();
1031 auto *RdxStart
= dyn_cast
<Instruction
>(ReduxRoot
->getOperand(0));
1034 Optional
<ReductionData
> RD
= getReductionData(RdxStart
);
1038 Type
*VecTy
= RdxStart
->getType();
1039 unsigned NumVecElems
= VecTy
->getVectorNumElements();
1040 if (!isPowerOf2_32(NumVecElems
))
1043 // We look for a sequence of shuffle,shuffle,add triples like the following
1044 // that builds a pairwise reduction tree.
1047 // (X0 + X1, X2 + X3, undef, undef)
1048 // ((X0 + X1) + (X2 + X3), undef, undef, undef)
1050 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1051 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1052 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1053 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1054 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1055 // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1056 // <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
1057 // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1058 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1059 // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
1060 // %r = extractelement <4 x float> %bin.rdx8, i32 0
1061 if (matchPairwiseReductionAtLevel(RdxStart
, 0, Log2_32(NumVecElems
)) ==
1065 Opcode
= RD
->Opcode
;
1071 static std::pair
<Value
*, ShuffleVectorInst
*>
1072 getShuffleAndOtherOprd(Value
*L
, Value
*R
) {
1073 ShuffleVectorInst
*S
= nullptr;
1075 if ((S
= dyn_cast
<ShuffleVectorInst
>(L
)))
1076 return std::make_pair(R
, S
);
1078 S
= dyn_cast
<ShuffleVectorInst
>(R
);
1079 return std::make_pair(L
, S
);
1082 static ReductionKind
1083 matchVectorSplittingReduction(const ExtractElementInst
*ReduxRoot
,
1084 unsigned &Opcode
, Type
*&Ty
) {
1085 if (!EnableReduxCost
)
1088 // Need to extract the first element.
1089 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(ReduxRoot
->getOperand(1));
1092 Idx
= CI
->getZExtValue();
1096 auto *RdxStart
= dyn_cast
<Instruction
>(ReduxRoot
->getOperand(0));
1099 Optional
<ReductionData
> RD
= getReductionData(RdxStart
);
1103 Type
*VecTy
= ReduxRoot
->getOperand(0)->getType();
1104 unsigned NumVecElems
= VecTy
->getVectorNumElements();
1105 if (!isPowerOf2_32(NumVecElems
))
1108 // We look for a sequence of shuffles and adds like the following matching one
1109 // fadd, shuffle vector pair at a time.
1111 // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
1112 // <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
1113 // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
1114 // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
1115 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1116 // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
1117 // %r = extractelement <4 x float> %bin.rdx8, i32 0
1119 unsigned MaskStart
= 1;
1120 Instruction
*RdxOp
= RdxStart
;
1121 SmallVector
<int, 32> ShuffleMask(NumVecElems
, 0);
1122 unsigned NumVecElemsRemain
= NumVecElems
;
1123 while (NumVecElemsRemain
- 1) {
1124 // Check for the right reduction operation.
1127 Optional
<ReductionData
> RDLevel
= getReductionData(RdxOp
);
1128 if (!RDLevel
|| !RDLevel
->hasSameData(*RD
))
1132 ShuffleVectorInst
*Shuffle
;
1133 std::tie(NextRdxOp
, Shuffle
) =
1134 getShuffleAndOtherOprd(RDLevel
->LHS
, RDLevel
->RHS
);
1136 // Check the current reduction operation and the shuffle use the same value.
1137 if (Shuffle
== nullptr)
1139 if (Shuffle
->getOperand(0) != NextRdxOp
)
1142 // Check that shuffle masks matches.
1143 for (unsigned j
= 0; j
!= MaskStart
; ++j
)
1144 ShuffleMask
[j
] = MaskStart
+ j
;
1145 // Fill the rest of the mask with -1 for undef.
1146 std::fill(&ShuffleMask
[MaskStart
], ShuffleMask
.end(), -1);
1148 SmallVector
<int, 16> Mask
= Shuffle
->getShuffleMask();
1149 if (ShuffleMask
!= Mask
)
1152 RdxOp
= dyn_cast
<Instruction
>(NextRdxOp
);
1153 NumVecElemsRemain
/= 2;
1157 Opcode
= RD
->Opcode
;
1162 int TargetTransformInfo::getInstructionThroughput(const Instruction
*I
) const {
1163 switch (I
->getOpcode()) {
1164 case Instruction::GetElementPtr
:
1165 return getUserCost(I
);
1167 case Instruction::Ret
:
1168 case Instruction::PHI
:
1169 case Instruction::Br
: {
1170 return getCFInstrCost(I
->getOpcode());
1172 case Instruction::Add
:
1173 case Instruction::FAdd
:
1174 case Instruction::Sub
:
1175 case Instruction::FSub
:
1176 case Instruction::Mul
:
1177 case Instruction::FMul
:
1178 case Instruction::UDiv
:
1179 case Instruction::SDiv
:
1180 case Instruction::FDiv
:
1181 case Instruction::URem
:
1182 case Instruction::SRem
:
1183 case Instruction::FRem
:
1184 case Instruction::Shl
:
1185 case Instruction::LShr
:
1186 case Instruction::AShr
:
1187 case Instruction::And
:
1188 case Instruction::Or
:
1189 case Instruction::Xor
: {
1190 TargetTransformInfo::OperandValueKind Op1VK
, Op2VK
;
1191 TargetTransformInfo::OperandValueProperties Op1VP
, Op2VP
;
1192 Op1VK
= getOperandInfo(I
->getOperand(0), Op1VP
);
1193 Op2VK
= getOperandInfo(I
->getOperand(1), Op2VP
);
1194 SmallVector
<const Value
*, 2> Operands(I
->operand_values());
1195 return getArithmeticInstrCost(I
->getOpcode(), I
->getType(), Op1VK
, Op2VK
,
1196 Op1VP
, Op2VP
, Operands
);
1198 case Instruction::FNeg
: {
1199 TargetTransformInfo::OperandValueKind Op1VK
, Op2VK
;
1200 TargetTransformInfo::OperandValueProperties Op1VP
, Op2VP
;
1201 Op1VK
= getOperandInfo(I
->getOperand(0), Op1VP
);
1202 Op2VK
= OK_AnyValue
;
1204 SmallVector
<const Value
*, 2> Operands(I
->operand_values());
1205 return getArithmeticInstrCost(I
->getOpcode(), I
->getType(), Op1VK
, Op2VK
,
1206 Op1VP
, Op2VP
, Operands
);
1208 case Instruction::Select
: {
1209 const SelectInst
*SI
= cast
<SelectInst
>(I
);
1210 Type
*CondTy
= SI
->getCondition()->getType();
1211 return getCmpSelInstrCost(I
->getOpcode(), I
->getType(), CondTy
, I
);
1213 case Instruction::ICmp
:
1214 case Instruction::FCmp
: {
1215 Type
*ValTy
= I
->getOperand(0)->getType();
1216 return getCmpSelInstrCost(I
->getOpcode(), ValTy
, I
->getType(), I
);
1218 case Instruction::Store
: {
1219 const StoreInst
*SI
= cast
<StoreInst
>(I
);
1220 Type
*ValTy
= SI
->getValueOperand()->getType();
1221 return getMemoryOpCost(I
->getOpcode(), ValTy
,
1223 SI
->getPointerAddressSpace(), I
);
1225 case Instruction::Load
: {
1226 const LoadInst
*LI
= cast
<LoadInst
>(I
);
1227 return getMemoryOpCost(I
->getOpcode(), I
->getType(),
1229 LI
->getPointerAddressSpace(), I
);
1231 case Instruction::ZExt
:
1232 case Instruction::SExt
:
1233 case Instruction::FPToUI
:
1234 case Instruction::FPToSI
:
1235 case Instruction::FPExt
:
1236 case Instruction::PtrToInt
:
1237 case Instruction::IntToPtr
:
1238 case Instruction::SIToFP
:
1239 case Instruction::UIToFP
:
1240 case Instruction::Trunc
:
1241 case Instruction::FPTrunc
:
1242 case Instruction::BitCast
:
1243 case Instruction::AddrSpaceCast
: {
1244 Type
*SrcTy
= I
->getOperand(0)->getType();
1245 return getCastInstrCost(I
->getOpcode(), I
->getType(), SrcTy
, I
);
1247 case Instruction::ExtractElement
: {
1248 const ExtractElementInst
* EEI
= cast
<ExtractElementInst
>(I
);
1249 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(I
->getOperand(1));
1252 Idx
= CI
->getZExtValue();
1254 // Try to match a reduction sequence (series of shufflevector and vector
1255 // adds followed by a extractelement).
1256 unsigned ReduxOpCode
;
1259 switch (matchVectorSplittingReduction(EEI
, ReduxOpCode
, ReduxType
)) {
1261 return getArithmeticReductionCost(ReduxOpCode
, ReduxType
,
1262 /*IsPairwiseForm=*/false);
1264 return getMinMaxReductionCost(
1265 ReduxType
, CmpInst::makeCmpResultType(ReduxType
),
1266 /*IsPairwiseForm=*/false, /*IsUnsigned=*/false);
1267 case RK_UnsignedMinMax
:
1268 return getMinMaxReductionCost(
1269 ReduxType
, CmpInst::makeCmpResultType(ReduxType
),
1270 /*IsPairwiseForm=*/false, /*IsUnsigned=*/true);
1275 switch (matchPairwiseReduction(EEI
, ReduxOpCode
, ReduxType
)) {
1277 return getArithmeticReductionCost(ReduxOpCode
, ReduxType
,
1278 /*IsPairwiseForm=*/true);
1280 return getMinMaxReductionCost(
1281 ReduxType
, CmpInst::makeCmpResultType(ReduxType
),
1282 /*IsPairwiseForm=*/true, /*IsUnsigned=*/false);
1283 case RK_UnsignedMinMax
:
1284 return getMinMaxReductionCost(
1285 ReduxType
, CmpInst::makeCmpResultType(ReduxType
),
1286 /*IsPairwiseForm=*/true, /*IsUnsigned=*/true);
1291 return getVectorInstrCost(I
->getOpcode(),
1292 EEI
->getOperand(0)->getType(), Idx
);
1294 case Instruction::InsertElement
: {
1295 const InsertElementInst
* IE
= cast
<InsertElementInst
>(I
);
1296 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(IE
->getOperand(2));
1299 Idx
= CI
->getZExtValue();
1300 return getVectorInstrCost(I
->getOpcode(),
1301 IE
->getType(), Idx
);
1303 case Instruction::ExtractValue
:
1304 return 0; // Model all ExtractValue nodes as free.
1305 case Instruction::ShuffleVector
: {
1306 const ShuffleVectorInst
*Shuffle
= cast
<ShuffleVectorInst
>(I
);
1307 Type
*Ty
= Shuffle
->getType();
1308 Type
*SrcTy
= Shuffle
->getOperand(0)->getType();
1310 // TODO: Identify and add costs for insert subvector, etc.
1312 if (Shuffle
->isExtractSubvectorMask(SubIndex
))
1313 return TTIImpl
->getShuffleCost(SK_ExtractSubvector
, SrcTy
, SubIndex
, Ty
);
1315 if (Shuffle
->changesLength())
1318 if (Shuffle
->isIdentity())
1321 if (Shuffle
->isReverse())
1322 return TTIImpl
->getShuffleCost(SK_Reverse
, Ty
, 0, nullptr);
1324 if (Shuffle
->isSelect())
1325 return TTIImpl
->getShuffleCost(SK_Select
, Ty
, 0, nullptr);
1327 if (Shuffle
->isTranspose())
1328 return TTIImpl
->getShuffleCost(SK_Transpose
, Ty
, 0, nullptr);
1330 if (Shuffle
->isZeroEltSplat())
1331 return TTIImpl
->getShuffleCost(SK_Broadcast
, Ty
, 0, nullptr);
1333 if (Shuffle
->isSingleSource())
1334 return TTIImpl
->getShuffleCost(SK_PermuteSingleSrc
, Ty
, 0, nullptr);
1336 return TTIImpl
->getShuffleCost(SK_PermuteTwoSrc
, Ty
, 0, nullptr);
1338 case Instruction::Call
:
1339 if (const IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(I
)) {
1340 SmallVector
<Value
*, 4> Args(II
->arg_operands());
1343 if (auto *FPMO
= dyn_cast
<FPMathOperator
>(II
))
1344 FMF
= FPMO
->getFastMathFlags();
1346 return getIntrinsicInstrCost(II
->getIntrinsicID(), II
->getType(),
1351 // We don't have any information on this instruction.
1356 TargetTransformInfo::Concept::~Concept() {}
1358 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI
) {}
1360 TargetIRAnalysis::TargetIRAnalysis(
1361 std::function
<Result(const Function
&)> TTICallback
)
1362 : TTICallback(std::move(TTICallback
)) {}
1364 TargetIRAnalysis::Result
TargetIRAnalysis::run(const Function
&F
,
1365 FunctionAnalysisManager
&) {
1366 return TTICallback(F
);
1369 AnalysisKey
TargetIRAnalysis::Key
;
1371 TargetIRAnalysis::Result
TargetIRAnalysis::getDefaultTTI(const Function
&F
) {
1372 return Result(F
.getParent()->getDataLayout());
1375 // Register the basic pass.
1376 INITIALIZE_PASS(TargetTransformInfoWrapperPass
, "tti",
1377 "Target Transform Information", false, true)
1378 char TargetTransformInfoWrapperPass::ID
= 0;
1380 void TargetTransformInfoWrapperPass::anchor() {}
1382 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass()
1383 : ImmutablePass(ID
) {
1384 initializeTargetTransformInfoWrapperPassPass(
1385 *PassRegistry::getPassRegistry());
1388 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass(
1389 TargetIRAnalysis TIRA
)
1390 : ImmutablePass(ID
), TIRA(std::move(TIRA
)) {
1391 initializeTargetTransformInfoWrapperPassPass(
1392 *PassRegistry::getPassRegistry());
1395 TargetTransformInfo
&TargetTransformInfoWrapperPass::getTTI(const Function
&F
) {
1396 FunctionAnalysisManager DummyFAM
;
1397 TTI
= TIRA
.run(F
, DummyFAM
);
1402 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA
) {
1403 return new TargetTransformInfoWrapperPass(std::move(TIRA
));