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/DataLayout.h"
13 #include "llvm/IR/Instruction.h"
14 #include "llvm/IR/Instructions.h"
15 #include "llvm/IR/IntrinsicInst.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/IR/Operator.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Analysis/CFG.h"
22 #include "llvm/Analysis/LoopIterator.h"
26 using namespace PatternMatch
;
28 #define DEBUG_TYPE "tti"
30 static cl::opt
<bool> EnableReduxCost("costmodel-reduxcost", cl::init(false),
32 cl::desc("Recognize reduction patterns."));
35 /// No-op implementation of the TTI interface using the utility base
38 /// This is used when no target specific information is available.
39 struct NoTTIImpl
: TargetTransformInfoImplCRTPBase
<NoTTIImpl
> {
40 explicit NoTTIImpl(const DataLayout
&DL
)
41 : TargetTransformInfoImplCRTPBase
<NoTTIImpl
>(DL
) {}
45 bool HardwareLoopInfo::canAnalyze(LoopInfo
&LI
) {
46 // If the loop has irreducible control flow, it can not be converted to
48 LoopBlocksRPO
RPOT(L
);
50 if (containsIrreducibleCFG
<const BasicBlock
*>(RPOT
, LI
))
55 bool HardwareLoopInfo::isHardwareLoopCandidate(ScalarEvolution
&SE
,
56 LoopInfo
&LI
, DominatorTree
&DT
,
58 bool ForceHardwareLoopPHI
) {
59 SmallVector
<BasicBlock
*, 4> ExitingBlocks
;
60 L
->getExitingBlocks(ExitingBlocks
);
62 for (SmallVectorImpl
<BasicBlock
*>::iterator I
= ExitingBlocks
.begin(),
63 IE
= ExitingBlocks
.end();
67 // If we pass the updated counter back through a phi, we need to know
68 // which latch the updated value will be coming from.
69 if (!L
->isLoopLatch(BB
)) {
70 if (ForceHardwareLoopPHI
|| CounterInReg
)
74 const SCEV
*EC
= SE
.getExitCount(L
, BB
);
75 if (isa
<SCEVCouldNotCompute
>(EC
))
77 if (const SCEVConstant
*ConstEC
= dyn_cast
<SCEVConstant
>(EC
)) {
78 if (ConstEC
->getValue()->isZero())
80 } else if (!SE
.isLoopInvariant(EC
, L
))
83 if (SE
.getTypeSizeInBits(EC
->getType()) > CountType
->getBitWidth())
86 // If this exiting block is contained in a nested loop, it is not eligible
87 // for insertion of the branch-and-decrement since the inner loop would
88 // end up messing up the value in the CTR.
89 if (!IsNestingLegal
&& LI
.getLoopFor(BB
) != L
&& !ForceNestedLoop
)
92 // We now have a loop-invariant count of loop iterations (which is not the
93 // constant zero) for which we know that this loop will not exit via this
96 // We need to make sure that this block will run on every loop iteration.
97 // For this to be true, we must dominate all blocks with backedges. Such
98 // blocks are in-loop predecessors to the header block.
99 bool NotAlways
= false;
100 for (pred_iterator PI
= pred_begin(L
->getHeader()),
101 PIE
= pred_end(L
->getHeader());
103 if (!L
->contains(*PI
))
106 if (!DT
.dominates(*I
, *PI
)) {
115 // Make sure this blocks ends with a conditional branch.
116 Instruction
*TI
= BB
->getTerminator();
120 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
)) {
121 if (!BI
->isConditional())
128 // Note that this block may not be the loop latch block, even if the loop
129 // has a latch block.
140 TargetTransformInfo::TargetTransformInfo(const DataLayout
&DL
)
141 : TTIImpl(new Model
<NoTTIImpl
>(NoTTIImpl(DL
))) {}
143 TargetTransformInfo::~TargetTransformInfo() {}
145 TargetTransformInfo::TargetTransformInfo(TargetTransformInfo
&&Arg
)
146 : TTIImpl(std::move(Arg
.TTIImpl
)) {}
148 TargetTransformInfo
&TargetTransformInfo::operator=(TargetTransformInfo
&&RHS
) {
149 TTIImpl
= std::move(RHS
.TTIImpl
);
153 int TargetTransformInfo::getOperationCost(unsigned Opcode
, Type
*Ty
,
155 int Cost
= TTIImpl
->getOperationCost(Opcode
, Ty
, OpTy
);
156 assert(Cost
>= 0 && "TTI should not produce negative costs!");
160 int TargetTransformInfo::getCallCost(FunctionType
*FTy
, int NumArgs
,
161 const User
*U
) const {
162 int Cost
= TTIImpl
->getCallCost(FTy
, NumArgs
, U
);
163 assert(Cost
>= 0 && "TTI should not produce negative costs!");
167 int TargetTransformInfo::getCallCost(const Function
*F
,
168 ArrayRef
<const Value
*> Arguments
,
169 const User
*U
) const {
170 int Cost
= TTIImpl
->getCallCost(F
, Arguments
, U
);
171 assert(Cost
>= 0 && "TTI should not produce negative costs!");
175 unsigned TargetTransformInfo::getInliningThresholdMultiplier() const {
176 return TTIImpl
->getInliningThresholdMultiplier();
179 int TargetTransformInfo::getInlinerVectorBonusPercent() const {
180 return TTIImpl
->getInlinerVectorBonusPercent();
183 int TargetTransformInfo::getGEPCost(Type
*PointeeType
, const Value
*Ptr
,
184 ArrayRef
<const Value
*> Operands
) const {
185 return TTIImpl
->getGEPCost(PointeeType
, Ptr
, Operands
);
188 int TargetTransformInfo::getExtCost(const Instruction
*I
,
189 const Value
*Src
) const {
190 return TTIImpl
->getExtCost(I
, Src
);
193 int TargetTransformInfo::getIntrinsicCost(
194 Intrinsic::ID IID
, Type
*RetTy
, ArrayRef
<const Value
*> Arguments
,
195 const User
*U
) const {
196 int Cost
= TTIImpl
->getIntrinsicCost(IID
, RetTy
, Arguments
, U
);
197 assert(Cost
>= 0 && "TTI should not produce negative costs!");
202 TargetTransformInfo::getEstimatedNumberOfCaseClusters(const SwitchInst
&SI
,
203 unsigned &JTSize
) const {
204 return TTIImpl
->getEstimatedNumberOfCaseClusters(SI
, JTSize
);
207 int TargetTransformInfo::getUserCost(const User
*U
,
208 ArrayRef
<const Value
*> Operands
) const {
209 int Cost
= TTIImpl
->getUserCost(U
, Operands
);
210 assert(Cost
>= 0 && "TTI should not produce negative costs!");
214 bool TargetTransformInfo::hasBranchDivergence() const {
215 return TTIImpl
->hasBranchDivergence();
218 bool TargetTransformInfo::isSourceOfDivergence(const Value
*V
) const {
219 return TTIImpl
->isSourceOfDivergence(V
);
222 bool llvm::TargetTransformInfo::isAlwaysUniform(const Value
*V
) const {
223 return TTIImpl
->isAlwaysUniform(V
);
226 unsigned TargetTransformInfo::getFlatAddressSpace() const {
227 return TTIImpl
->getFlatAddressSpace();
230 bool TargetTransformInfo::collectFlatAddressOperands(
231 SmallVectorImpl
<int> &OpIndexes
, Intrinsic::ID IID
) const {
232 return TTIImpl
->collectFlatAddressOperands(OpIndexes
, IID
);
235 bool TargetTransformInfo::rewriteIntrinsicWithAddressSpace(
236 IntrinsicInst
*II
, Value
*OldV
, Value
*NewV
) const {
237 return TTIImpl
->rewriteIntrinsicWithAddressSpace(II
, OldV
, NewV
);
240 bool TargetTransformInfo::isLoweredToCall(const Function
*F
) const {
241 return TTIImpl
->isLoweredToCall(F
);
244 bool TargetTransformInfo::isHardwareLoopProfitable(
245 Loop
*L
, ScalarEvolution
&SE
, AssumptionCache
&AC
,
246 TargetLibraryInfo
*LibInfo
, HardwareLoopInfo
&HWLoopInfo
) const {
247 return TTIImpl
->isHardwareLoopProfitable(L
, SE
, AC
, LibInfo
, HWLoopInfo
);
250 void TargetTransformInfo::getUnrollingPreferences(
251 Loop
*L
, ScalarEvolution
&SE
, UnrollingPreferences
&UP
) const {
252 return TTIImpl
->getUnrollingPreferences(L
, SE
, UP
);
255 bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm
) const {
256 return TTIImpl
->isLegalAddImmediate(Imm
);
259 bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm
) const {
260 return TTIImpl
->isLegalICmpImmediate(Imm
);
263 bool TargetTransformInfo::isLegalAddressingMode(Type
*Ty
, GlobalValue
*BaseGV
,
268 Instruction
*I
) const {
269 return TTIImpl
->isLegalAddressingMode(Ty
, BaseGV
, BaseOffset
, HasBaseReg
,
270 Scale
, AddrSpace
, I
);
273 bool TargetTransformInfo::isLSRCostLess(LSRCost
&C1
, LSRCost
&C2
) const {
274 return TTIImpl
->isLSRCostLess(C1
, C2
);
277 bool TargetTransformInfo::canMacroFuseCmp() const {
278 return TTIImpl
->canMacroFuseCmp();
281 bool TargetTransformInfo::canSaveCmp(Loop
*L
, BranchInst
**BI
,
282 ScalarEvolution
*SE
, LoopInfo
*LI
,
283 DominatorTree
*DT
, AssumptionCache
*AC
,
284 TargetLibraryInfo
*LibInfo
) const {
285 return TTIImpl
->canSaveCmp(L
, BI
, SE
, LI
, DT
, AC
, LibInfo
);
288 bool TargetTransformInfo::shouldFavorPostInc() const {
289 return TTIImpl
->shouldFavorPostInc();
292 bool TargetTransformInfo::shouldFavorBackedgeIndex(const Loop
*L
) const {
293 return TTIImpl
->shouldFavorBackedgeIndex(L
);
296 bool TargetTransformInfo::isLegalMaskedStore(Type
*DataType
) const {
297 return TTIImpl
->isLegalMaskedStore(DataType
);
300 bool TargetTransformInfo::isLegalMaskedLoad(Type
*DataType
) const {
301 return TTIImpl
->isLegalMaskedLoad(DataType
);
304 bool TargetTransformInfo::isLegalNTStore(Type
*DataType
,
305 unsigned Alignment
) const {
306 return TTIImpl
->isLegalNTStore(DataType
, Alignment
);
309 bool TargetTransformInfo::isLegalNTLoad(Type
*DataType
,
310 unsigned Alignment
) const {
311 return TTIImpl
->isLegalNTLoad(DataType
, Alignment
);
314 bool TargetTransformInfo::isLegalMaskedGather(Type
*DataType
) const {
315 return TTIImpl
->isLegalMaskedGather(DataType
);
318 bool TargetTransformInfo::isLegalMaskedScatter(Type
*DataType
) const {
319 return TTIImpl
->isLegalMaskedScatter(DataType
);
322 bool TargetTransformInfo::isLegalMaskedCompressStore(Type
*DataType
) const {
323 return TTIImpl
->isLegalMaskedCompressStore(DataType
);
326 bool TargetTransformInfo::isLegalMaskedExpandLoad(Type
*DataType
) const {
327 return TTIImpl
->isLegalMaskedExpandLoad(DataType
);
330 bool TargetTransformInfo::hasDivRemOp(Type
*DataType
, bool IsSigned
) const {
331 return TTIImpl
->hasDivRemOp(DataType
, IsSigned
);
334 bool TargetTransformInfo::hasVolatileVariant(Instruction
*I
,
335 unsigned AddrSpace
) const {
336 return TTIImpl
->hasVolatileVariant(I
, AddrSpace
);
339 bool TargetTransformInfo::prefersVectorizedAddressing() const {
340 return TTIImpl
->prefersVectorizedAddressing();
343 int TargetTransformInfo::getScalingFactorCost(Type
*Ty
, GlobalValue
*BaseGV
,
347 unsigned AddrSpace
) const {
348 int Cost
= TTIImpl
->getScalingFactorCost(Ty
, BaseGV
, BaseOffset
, HasBaseReg
,
350 assert(Cost
>= 0 && "TTI should not produce negative costs!");
354 bool TargetTransformInfo::LSRWithInstrQueries() const {
355 return TTIImpl
->LSRWithInstrQueries();
358 bool TargetTransformInfo::isTruncateFree(Type
*Ty1
, Type
*Ty2
) const {
359 return TTIImpl
->isTruncateFree(Ty1
, Ty2
);
362 bool TargetTransformInfo::isProfitableToHoist(Instruction
*I
) const {
363 return TTIImpl
->isProfitableToHoist(I
);
366 bool TargetTransformInfo::useAA() const { return TTIImpl
->useAA(); }
368 bool TargetTransformInfo::isTypeLegal(Type
*Ty
) const {
369 return TTIImpl
->isTypeLegal(Ty
);
372 unsigned TargetTransformInfo::getJumpBufAlignment() const {
373 return TTIImpl
->getJumpBufAlignment();
376 unsigned TargetTransformInfo::getJumpBufSize() const {
377 return TTIImpl
->getJumpBufSize();
380 bool TargetTransformInfo::shouldBuildLookupTables() const {
381 return TTIImpl
->shouldBuildLookupTables();
383 bool TargetTransformInfo::shouldBuildLookupTablesForConstant(Constant
*C
) const {
384 return TTIImpl
->shouldBuildLookupTablesForConstant(C
);
387 bool TargetTransformInfo::useColdCCForColdCall(Function
&F
) const {
388 return TTIImpl
->useColdCCForColdCall(F
);
391 unsigned TargetTransformInfo::
392 getScalarizationOverhead(Type
*Ty
, bool Insert
, bool Extract
) const {
393 return TTIImpl
->getScalarizationOverhead(Ty
, Insert
, Extract
);
396 unsigned TargetTransformInfo::
397 getOperandsScalarizationOverhead(ArrayRef
<const Value
*> Args
,
399 return TTIImpl
->getOperandsScalarizationOverhead(Args
, VF
);
402 bool TargetTransformInfo::supportsEfficientVectorElementLoadStore() const {
403 return TTIImpl
->supportsEfficientVectorElementLoadStore();
406 bool TargetTransformInfo::enableAggressiveInterleaving(bool LoopHasReductions
) const {
407 return TTIImpl
->enableAggressiveInterleaving(LoopHasReductions
);
410 TargetTransformInfo::MemCmpExpansionOptions
411 TargetTransformInfo::enableMemCmpExpansion(bool OptSize
, bool IsZeroCmp
) const {
412 return TTIImpl
->enableMemCmpExpansion(OptSize
, IsZeroCmp
);
415 bool TargetTransformInfo::enableInterleavedAccessVectorization() const {
416 return TTIImpl
->enableInterleavedAccessVectorization();
419 bool TargetTransformInfo::enableMaskedInterleavedAccessVectorization() const {
420 return TTIImpl
->enableMaskedInterleavedAccessVectorization();
423 bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const {
424 return TTIImpl
->isFPVectorizationPotentiallyUnsafe();
427 bool TargetTransformInfo::allowsMisalignedMemoryAccesses(LLVMContext
&Context
,
429 unsigned AddressSpace
,
432 return TTIImpl
->allowsMisalignedMemoryAccesses(Context
, BitWidth
, AddressSpace
,
436 TargetTransformInfo::PopcntSupportKind
437 TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit
) const {
438 return TTIImpl
->getPopcntSupport(IntTyWidthInBit
);
441 bool TargetTransformInfo::haveFastSqrt(Type
*Ty
) const {
442 return TTIImpl
->haveFastSqrt(Ty
);
445 bool TargetTransformInfo::isFCmpOrdCheaperThanFCmpZero(Type
*Ty
) const {
446 return TTIImpl
->isFCmpOrdCheaperThanFCmpZero(Ty
);
449 int TargetTransformInfo::getFPOpCost(Type
*Ty
) const {
450 int Cost
= TTIImpl
->getFPOpCost(Ty
);
451 assert(Cost
>= 0 && "TTI should not produce negative costs!");
455 int TargetTransformInfo::getIntImmCodeSizeCost(unsigned Opcode
, unsigned Idx
,
458 int Cost
= TTIImpl
->getIntImmCodeSizeCost(Opcode
, Idx
, Imm
, Ty
);
459 assert(Cost
>= 0 && "TTI should not produce negative costs!");
463 int TargetTransformInfo::getIntImmCost(const APInt
&Imm
, Type
*Ty
) const {
464 int Cost
= TTIImpl
->getIntImmCost(Imm
, Ty
);
465 assert(Cost
>= 0 && "TTI should not produce negative costs!");
469 int TargetTransformInfo::getIntImmCost(unsigned Opcode
, unsigned Idx
,
470 const APInt
&Imm
, Type
*Ty
) const {
471 int Cost
= TTIImpl
->getIntImmCost(Opcode
, Idx
, Imm
, Ty
);
472 assert(Cost
>= 0 && "TTI should not produce negative costs!");
476 int TargetTransformInfo::getIntImmCost(Intrinsic::ID IID
, unsigned Idx
,
477 const APInt
&Imm
, Type
*Ty
) const {
478 int Cost
= TTIImpl
->getIntImmCost(IID
, Idx
, Imm
, Ty
);
479 assert(Cost
>= 0 && "TTI should not produce negative costs!");
483 unsigned TargetTransformInfo::getNumberOfRegisters(bool Vector
) const {
484 return TTIImpl
->getNumberOfRegisters(Vector
);
487 unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector
) const {
488 return TTIImpl
->getRegisterBitWidth(Vector
);
491 unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const {
492 return TTIImpl
->getMinVectorRegisterBitWidth();
495 bool TargetTransformInfo::shouldMaximizeVectorBandwidth(bool OptSize
) const {
496 return TTIImpl
->shouldMaximizeVectorBandwidth(OptSize
);
499 unsigned TargetTransformInfo::getMinimumVF(unsigned ElemWidth
) const {
500 return TTIImpl
->getMinimumVF(ElemWidth
);
503 bool TargetTransformInfo::shouldConsiderAddressTypePromotion(
504 const Instruction
&I
, bool &AllowPromotionWithoutCommonHeader
) const {
505 return TTIImpl
->shouldConsiderAddressTypePromotion(
506 I
, AllowPromotionWithoutCommonHeader
);
509 unsigned TargetTransformInfo::getCacheLineSize() const {
510 return TTIImpl
->getCacheLineSize();
513 llvm::Optional
<unsigned> TargetTransformInfo::getCacheSize(CacheLevel Level
)
515 return TTIImpl
->getCacheSize(Level
);
518 llvm::Optional
<unsigned> TargetTransformInfo::getCacheAssociativity(
519 CacheLevel Level
) const {
520 return TTIImpl
->getCacheAssociativity(Level
);
523 unsigned TargetTransformInfo::getPrefetchDistance() const {
524 return TTIImpl
->getPrefetchDistance();
527 unsigned TargetTransformInfo::getMinPrefetchStride() const {
528 return TTIImpl
->getMinPrefetchStride();
531 unsigned TargetTransformInfo::getMaxPrefetchIterationsAhead() const {
532 return TTIImpl
->getMaxPrefetchIterationsAhead();
535 unsigned TargetTransformInfo::getMaxInterleaveFactor(unsigned VF
) const {
536 return TTIImpl
->getMaxInterleaveFactor(VF
);
539 TargetTransformInfo::OperandValueKind
540 TargetTransformInfo::getOperandInfo(Value
*V
, OperandValueProperties
&OpProps
) {
541 OperandValueKind OpInfo
= OK_AnyValue
;
544 if (auto *CI
= dyn_cast
<ConstantInt
>(V
)) {
545 if (CI
->getValue().isPowerOf2())
546 OpProps
= OP_PowerOf2
;
547 return OK_UniformConstantValue
;
550 // A broadcast shuffle creates a uniform value.
551 // TODO: Add support for non-zero index broadcasts.
552 // TODO: Add support for different source vector width.
553 if (auto *ShuffleInst
= dyn_cast
<ShuffleVectorInst
>(V
))
554 if (ShuffleInst
->isZeroEltSplat())
555 OpInfo
= OK_UniformValue
;
557 const Value
*Splat
= getSplatValue(V
);
559 // Check for a splat of a constant or for a non uniform vector of constants
560 // and check if the constant(s) are all powers of two.
561 if (isa
<ConstantVector
>(V
) || isa
<ConstantDataVector
>(V
)) {
562 OpInfo
= OK_NonUniformConstantValue
;
564 OpInfo
= OK_UniformConstantValue
;
565 if (auto *CI
= dyn_cast
<ConstantInt
>(Splat
))
566 if (CI
->getValue().isPowerOf2())
567 OpProps
= OP_PowerOf2
;
568 } else if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(V
)) {
569 OpProps
= OP_PowerOf2
;
570 for (unsigned I
= 0, E
= CDS
->getNumElements(); I
!= E
; ++I
) {
571 if (auto *CI
= dyn_cast
<ConstantInt
>(CDS
->getElementAsConstant(I
)))
572 if (CI
->getValue().isPowerOf2())
580 // Check for a splat of a uniform value. This is not loop aware, so return
581 // true only for the obviously uniform cases (argument, globalvalue)
582 if (Splat
&& (isa
<Argument
>(Splat
) || isa
<GlobalValue
>(Splat
)))
583 OpInfo
= OK_UniformValue
;
588 int TargetTransformInfo::getArithmeticInstrCost(
589 unsigned Opcode
, Type
*Ty
, OperandValueKind Opd1Info
,
590 OperandValueKind Opd2Info
, OperandValueProperties Opd1PropInfo
,
591 OperandValueProperties Opd2PropInfo
,
592 ArrayRef
<const Value
*> Args
) const {
593 int Cost
= TTIImpl
->getArithmeticInstrCost(Opcode
, Ty
, Opd1Info
, Opd2Info
,
594 Opd1PropInfo
, Opd2PropInfo
, Args
);
595 assert(Cost
>= 0 && "TTI should not produce negative costs!");
599 int TargetTransformInfo::getShuffleCost(ShuffleKind Kind
, Type
*Ty
, int Index
,
601 int Cost
= TTIImpl
->getShuffleCost(Kind
, Ty
, Index
, SubTp
);
602 assert(Cost
>= 0 && "TTI should not produce negative costs!");
606 int TargetTransformInfo::getCastInstrCost(unsigned Opcode
, Type
*Dst
,
607 Type
*Src
, const Instruction
*I
) const {
608 assert ((I
== nullptr || I
->getOpcode() == Opcode
) &&
609 "Opcode should reflect passed instruction.");
610 int Cost
= TTIImpl
->getCastInstrCost(Opcode
, Dst
, Src
, I
);
611 assert(Cost
>= 0 && "TTI should not produce negative costs!");
615 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode
, Type
*Dst
,
617 unsigned Index
) const {
618 int Cost
= TTIImpl
->getExtractWithExtendCost(Opcode
, Dst
, VecTy
, Index
);
619 assert(Cost
>= 0 && "TTI should not produce negative costs!");
623 int TargetTransformInfo::getCFInstrCost(unsigned Opcode
) const {
624 int Cost
= TTIImpl
->getCFInstrCost(Opcode
);
625 assert(Cost
>= 0 && "TTI should not produce negative costs!");
629 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode
, Type
*ValTy
,
630 Type
*CondTy
, const Instruction
*I
) const {
631 assert ((I
== nullptr || I
->getOpcode() == Opcode
) &&
632 "Opcode should reflect passed instruction.");
633 int Cost
= TTIImpl
->getCmpSelInstrCost(Opcode
, ValTy
, CondTy
, I
);
634 assert(Cost
>= 0 && "TTI should not produce negative costs!");
638 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode
, Type
*Val
,
639 unsigned Index
) const {
640 int Cost
= TTIImpl
->getVectorInstrCost(Opcode
, Val
, Index
);
641 assert(Cost
>= 0 && "TTI should not produce negative costs!");
645 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode
, Type
*Src
,
647 unsigned AddressSpace
,
648 const Instruction
*I
) const {
649 assert ((I
== nullptr || I
->getOpcode() == Opcode
) &&
650 "Opcode should reflect passed instruction.");
651 int Cost
= TTIImpl
->getMemoryOpCost(Opcode
, Src
, Alignment
, AddressSpace
, I
);
652 assert(Cost
>= 0 && "TTI should not produce negative costs!");
656 int TargetTransformInfo::getMaskedMemoryOpCost(unsigned Opcode
, Type
*Src
,
658 unsigned AddressSpace
) const {
660 TTIImpl
->getMaskedMemoryOpCost(Opcode
, Src
, Alignment
, AddressSpace
);
661 assert(Cost
>= 0 && "TTI should not produce negative costs!");
665 int TargetTransformInfo::getGatherScatterOpCost(unsigned Opcode
, Type
*DataTy
,
666 Value
*Ptr
, bool VariableMask
,
667 unsigned Alignment
) const {
668 int Cost
= TTIImpl
->getGatherScatterOpCost(Opcode
, DataTy
, Ptr
, VariableMask
,
670 assert(Cost
>= 0 && "TTI should not produce negative costs!");
674 int TargetTransformInfo::getInterleavedMemoryOpCost(
675 unsigned Opcode
, Type
*VecTy
, unsigned Factor
, ArrayRef
<unsigned> Indices
,
676 unsigned Alignment
, unsigned AddressSpace
, bool UseMaskForCond
,
677 bool UseMaskForGaps
) const {
678 int Cost
= TTIImpl
->getInterleavedMemoryOpCost(Opcode
, VecTy
, Factor
, Indices
,
679 Alignment
, AddressSpace
,
682 assert(Cost
>= 0 && "TTI should not produce negative costs!");
686 int TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID
, Type
*RetTy
,
687 ArrayRef
<Type
*> Tys
, FastMathFlags FMF
,
688 unsigned ScalarizationCostPassed
) const {
689 int Cost
= TTIImpl
->getIntrinsicInstrCost(ID
, RetTy
, Tys
, FMF
,
690 ScalarizationCostPassed
);
691 assert(Cost
>= 0 && "TTI should not produce negative costs!");
695 int TargetTransformInfo::getIntrinsicInstrCost(Intrinsic::ID ID
, Type
*RetTy
,
696 ArrayRef
<Value
*> Args
, FastMathFlags FMF
, unsigned VF
) const {
697 int Cost
= TTIImpl
->getIntrinsicInstrCost(ID
, RetTy
, Args
, FMF
, VF
);
698 assert(Cost
>= 0 && "TTI should not produce negative costs!");
702 int TargetTransformInfo::getCallInstrCost(Function
*F
, Type
*RetTy
,
703 ArrayRef
<Type
*> Tys
) const {
704 int Cost
= TTIImpl
->getCallInstrCost(F
, RetTy
, Tys
);
705 assert(Cost
>= 0 && "TTI should not produce negative costs!");
709 unsigned TargetTransformInfo::getNumberOfParts(Type
*Tp
) const {
710 return TTIImpl
->getNumberOfParts(Tp
);
713 int TargetTransformInfo::getAddressComputationCost(Type
*Tp
,
715 const SCEV
*Ptr
) const {
716 int Cost
= TTIImpl
->getAddressComputationCost(Tp
, SE
, Ptr
);
717 assert(Cost
>= 0 && "TTI should not produce negative costs!");
721 int TargetTransformInfo::getMemcpyCost(const Instruction
*I
) const {
722 int Cost
= TTIImpl
->getMemcpyCost(I
);
723 assert(Cost
>= 0 && "TTI should not produce negative costs!");
727 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode
, Type
*Ty
,
728 bool IsPairwiseForm
) const {
729 int Cost
= TTIImpl
->getArithmeticReductionCost(Opcode
, Ty
, IsPairwiseForm
);
730 assert(Cost
>= 0 && "TTI should not produce negative costs!");
734 int TargetTransformInfo::getMinMaxReductionCost(Type
*Ty
, Type
*CondTy
,
736 bool IsUnsigned
) const {
738 TTIImpl
->getMinMaxReductionCost(Ty
, CondTy
, IsPairwiseForm
, IsUnsigned
);
739 assert(Cost
>= 0 && "TTI should not produce negative costs!");
744 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef
<Type
*> Tys
) const {
745 return TTIImpl
->getCostOfKeepingLiveOverCall(Tys
);
748 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst
*Inst
,
749 MemIntrinsicInfo
&Info
) const {
750 return TTIImpl
->getTgtMemIntrinsic(Inst
, Info
);
753 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const {
754 return TTIImpl
->getAtomicMemIntrinsicMaxElementSize();
757 Value
*TargetTransformInfo::getOrCreateResultFromMemIntrinsic(
758 IntrinsicInst
*Inst
, Type
*ExpectedType
) const {
759 return TTIImpl
->getOrCreateResultFromMemIntrinsic(Inst
, ExpectedType
);
762 Type
*TargetTransformInfo::getMemcpyLoopLoweringType(LLVMContext
&Context
,
765 unsigned DestAlign
) const {
766 return TTIImpl
->getMemcpyLoopLoweringType(Context
, Length
, SrcAlign
,
770 void TargetTransformInfo::getMemcpyLoopResidualLoweringType(
771 SmallVectorImpl
<Type
*> &OpsOut
, LLVMContext
&Context
,
772 unsigned RemainingBytes
, unsigned SrcAlign
, unsigned DestAlign
) const {
773 TTIImpl
->getMemcpyLoopResidualLoweringType(OpsOut
, Context
, RemainingBytes
,
774 SrcAlign
, DestAlign
);
777 bool TargetTransformInfo::areInlineCompatible(const Function
*Caller
,
778 const Function
*Callee
) const {
779 return TTIImpl
->areInlineCompatible(Caller
, Callee
);
782 bool TargetTransformInfo::areFunctionArgsABICompatible(
783 const Function
*Caller
, const Function
*Callee
,
784 SmallPtrSetImpl
<Argument
*> &Args
) const {
785 return TTIImpl
->areFunctionArgsABICompatible(Caller
, Callee
, Args
);
788 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode
,
790 return TTIImpl
->isIndexedLoadLegal(Mode
, Ty
);
793 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode
,
795 return TTIImpl
->isIndexedStoreLegal(Mode
, Ty
);
798 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS
) const {
799 return TTIImpl
->getLoadStoreVecRegBitWidth(AS
);
802 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst
*LI
) const {
803 return TTIImpl
->isLegalToVectorizeLoad(LI
);
806 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst
*SI
) const {
807 return TTIImpl
->isLegalToVectorizeStore(SI
);
810 bool TargetTransformInfo::isLegalToVectorizeLoadChain(
811 unsigned ChainSizeInBytes
, unsigned Alignment
, unsigned AddrSpace
) const {
812 return TTIImpl
->isLegalToVectorizeLoadChain(ChainSizeInBytes
, Alignment
,
816 bool TargetTransformInfo::isLegalToVectorizeStoreChain(
817 unsigned ChainSizeInBytes
, unsigned Alignment
, unsigned AddrSpace
) const {
818 return TTIImpl
->isLegalToVectorizeStoreChain(ChainSizeInBytes
, Alignment
,
822 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF
,
824 unsigned ChainSizeInBytes
,
825 VectorType
*VecTy
) const {
826 return TTIImpl
->getLoadVectorFactor(VF
, LoadSize
, ChainSizeInBytes
, VecTy
);
829 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF
,
831 unsigned ChainSizeInBytes
,
832 VectorType
*VecTy
) const {
833 return TTIImpl
->getStoreVectorFactor(VF
, StoreSize
, ChainSizeInBytes
, VecTy
);
836 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode
,
837 Type
*Ty
, ReductionFlags Flags
) const {
838 return TTIImpl
->useReductionIntrinsic(Opcode
, Ty
, Flags
);
841 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst
*II
) const {
842 return TTIImpl
->shouldExpandReduction(II
);
845 unsigned TargetTransformInfo::getGISelRematGlobalCost() const {
846 return TTIImpl
->getGISelRematGlobalCost();
849 int TargetTransformInfo::getInstructionLatency(const Instruction
*I
) const {
850 return TTIImpl
->getInstructionLatency(I
);
853 static bool matchPairwiseShuffleMask(ShuffleVectorInst
*SI
, bool IsLeft
,
855 // We don't need a shuffle if we just want to have element 0 in position 0 of
857 if (!SI
&& Level
== 0 && IsLeft
)
862 SmallVector
<int, 32> Mask(SI
->getType()->getVectorNumElements(), -1);
864 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
865 // we look at the left or right side.
866 for (unsigned i
= 0, e
= (1 << Level
), val
= !IsLeft
; i
!= e
; ++i
, val
+= 2)
869 SmallVector
<int, 16> ActualMask
= SI
->getShuffleMask();
870 return Mask
== ActualMask
;
874 /// Kind of the reduction data.
876 RK_None
, /// Not a reduction.
877 RK_Arithmetic
, /// Binary reduction data.
878 RK_MinMax
, /// Min/max reduction data.
879 RK_UnsignedMinMax
, /// Unsigned min/max reduction data.
881 /// Contains opcode + LHS/RHS parts of the reduction operations.
882 struct ReductionData
{
883 ReductionData() = delete;
884 ReductionData(ReductionKind Kind
, unsigned Opcode
, Value
*LHS
, Value
*RHS
)
885 : Opcode(Opcode
), LHS(LHS
), RHS(RHS
), Kind(Kind
) {
886 assert(Kind
!= RK_None
&& "expected binary or min/max reduction only.");
889 Value
*LHS
= nullptr;
890 Value
*RHS
= nullptr;
891 ReductionKind Kind
= RK_None
;
892 bool hasSameData(ReductionData
&RD
) const {
893 return Kind
== RD
.Kind
&& Opcode
== RD
.Opcode
;
898 static Optional
<ReductionData
> getReductionData(Instruction
*I
) {
900 if (m_BinOp(m_Value(L
), m_Value(R
)).match(I
))
901 return ReductionData(RK_Arithmetic
, I
->getOpcode(), L
, R
);
902 if (auto *SI
= dyn_cast
<SelectInst
>(I
)) {
903 if (m_SMin(m_Value(L
), m_Value(R
)).match(SI
) ||
904 m_SMax(m_Value(L
), m_Value(R
)).match(SI
) ||
905 m_OrdFMin(m_Value(L
), m_Value(R
)).match(SI
) ||
906 m_OrdFMax(m_Value(L
), m_Value(R
)).match(SI
) ||
907 m_UnordFMin(m_Value(L
), m_Value(R
)).match(SI
) ||
908 m_UnordFMax(m_Value(L
), m_Value(R
)).match(SI
)) {
909 auto *CI
= cast
<CmpInst
>(SI
->getCondition());
910 return ReductionData(RK_MinMax
, CI
->getOpcode(), L
, R
);
912 if (m_UMin(m_Value(L
), m_Value(R
)).match(SI
) ||
913 m_UMax(m_Value(L
), m_Value(R
)).match(SI
)) {
914 auto *CI
= cast
<CmpInst
>(SI
->getCondition());
915 return ReductionData(RK_UnsignedMinMax
, CI
->getOpcode(), L
, R
);
921 static ReductionKind
matchPairwiseReductionAtLevel(Instruction
*I
,
923 unsigned NumLevels
) {
924 // Match one level of pairwise operations.
925 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
926 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
927 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
928 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
929 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
933 assert(I
->getType()->isVectorTy() && "Expecting a vector type");
935 Optional
<ReductionData
> RD
= getReductionData(I
);
939 ShuffleVectorInst
*LS
= dyn_cast
<ShuffleVectorInst
>(RD
->LHS
);
942 ShuffleVectorInst
*RS
= dyn_cast
<ShuffleVectorInst
>(RD
->RHS
);
946 // On level 0 we can omit one shufflevector instruction.
947 if (!Level
&& !RS
&& !LS
)
950 // Shuffle inputs must match.
951 Value
*NextLevelOpL
= LS
? LS
->getOperand(0) : nullptr;
952 Value
*NextLevelOpR
= RS
? RS
->getOperand(0) : nullptr;
953 Value
*NextLevelOp
= nullptr;
954 if (NextLevelOpR
&& NextLevelOpL
) {
955 // If we have two shuffles their operands must match.
956 if (NextLevelOpL
!= NextLevelOpR
)
959 NextLevelOp
= NextLevelOpL
;
960 } else if (Level
== 0 && (NextLevelOpR
|| NextLevelOpL
)) {
961 // On the first level we can omit the shufflevector <0, undef,...>. So the
962 // input to the other shufflevector <1, undef> must match with one of the
963 // inputs to the current binary operation.
965 // %NextLevelOpL = shufflevector %R, <1, undef ...>
966 // %BinOp = fadd %NextLevelOpL, %R
967 if (NextLevelOpL
&& NextLevelOpL
!= RD
->RHS
)
969 else if (NextLevelOpR
&& NextLevelOpR
!= RD
->LHS
)
972 NextLevelOp
= NextLevelOpL
? RD
->RHS
: RD
->LHS
;
976 // Check that the next levels binary operation exists and matches with the
978 if (Level
+ 1 != NumLevels
) {
979 Optional
<ReductionData
> NextLevelRD
=
980 getReductionData(cast
<Instruction
>(NextLevelOp
));
981 if (!NextLevelRD
|| !RD
->hasSameData(*NextLevelRD
))
985 // Shuffle mask for pairwise operation must match.
986 if (matchPairwiseShuffleMask(LS
, /*IsLeft=*/true, Level
)) {
987 if (!matchPairwiseShuffleMask(RS
, /*IsLeft=*/false, Level
))
989 } else if (matchPairwiseShuffleMask(RS
, /*IsLeft=*/true, Level
)) {
990 if (!matchPairwiseShuffleMask(LS
, /*IsLeft=*/false, Level
))
996 if (++Level
== NumLevels
)
1000 return matchPairwiseReductionAtLevel(cast
<Instruction
>(NextLevelOp
), Level
,
1004 static ReductionKind
matchPairwiseReduction(const ExtractElementInst
*ReduxRoot
,
1005 unsigned &Opcode
, Type
*&Ty
) {
1006 if (!EnableReduxCost
)
1009 // Need to extract the first element.
1010 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(ReduxRoot
->getOperand(1));
1013 Idx
= CI
->getZExtValue();
1017 auto *RdxStart
= dyn_cast
<Instruction
>(ReduxRoot
->getOperand(0));
1020 Optional
<ReductionData
> RD
= getReductionData(RdxStart
);
1024 Type
*VecTy
= RdxStart
->getType();
1025 unsigned NumVecElems
= VecTy
->getVectorNumElements();
1026 if (!isPowerOf2_32(NumVecElems
))
1029 // We look for a sequence of shuffle,shuffle,add triples like the following
1030 // that builds a pairwise reduction tree.
1033 // (X0 + X1, X2 + X3, undef, undef)
1034 // ((X0 + X1) + (X2 + X3), undef, undef, undef)
1036 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1037 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1038 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1039 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1040 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1041 // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1042 // <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
1043 // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1044 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1045 // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
1046 // %r = extractelement <4 x float> %bin.rdx8, i32 0
1047 if (matchPairwiseReductionAtLevel(RdxStart
, 0, Log2_32(NumVecElems
)) ==
1051 Opcode
= RD
->Opcode
;
1057 static std::pair
<Value
*, ShuffleVectorInst
*>
1058 getShuffleAndOtherOprd(Value
*L
, Value
*R
) {
1059 ShuffleVectorInst
*S
= nullptr;
1061 if ((S
= dyn_cast
<ShuffleVectorInst
>(L
)))
1062 return std::make_pair(R
, S
);
1064 S
= dyn_cast
<ShuffleVectorInst
>(R
);
1065 return std::make_pair(L
, S
);
1068 static ReductionKind
1069 matchVectorSplittingReduction(const ExtractElementInst
*ReduxRoot
,
1070 unsigned &Opcode
, Type
*&Ty
) {
1071 if (!EnableReduxCost
)
1074 // Need to extract the first element.
1075 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(ReduxRoot
->getOperand(1));
1078 Idx
= CI
->getZExtValue();
1082 auto *RdxStart
= dyn_cast
<Instruction
>(ReduxRoot
->getOperand(0));
1085 Optional
<ReductionData
> RD
= getReductionData(RdxStart
);
1089 Type
*VecTy
= ReduxRoot
->getOperand(0)->getType();
1090 unsigned NumVecElems
= VecTy
->getVectorNumElements();
1091 if (!isPowerOf2_32(NumVecElems
))
1094 // We look for a sequence of shuffles and adds like the following matching one
1095 // fadd, shuffle vector pair at a time.
1097 // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
1098 // <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
1099 // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
1100 // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
1101 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1102 // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
1103 // %r = extractelement <4 x float> %bin.rdx8, i32 0
1105 unsigned MaskStart
= 1;
1106 Instruction
*RdxOp
= RdxStart
;
1107 SmallVector
<int, 32> ShuffleMask(NumVecElems
, 0);
1108 unsigned NumVecElemsRemain
= NumVecElems
;
1109 while (NumVecElemsRemain
- 1) {
1110 // Check for the right reduction operation.
1113 Optional
<ReductionData
> RDLevel
= getReductionData(RdxOp
);
1114 if (!RDLevel
|| !RDLevel
->hasSameData(*RD
))
1118 ShuffleVectorInst
*Shuffle
;
1119 std::tie(NextRdxOp
, Shuffle
) =
1120 getShuffleAndOtherOprd(RDLevel
->LHS
, RDLevel
->RHS
);
1122 // Check the current reduction operation and the shuffle use the same value.
1123 if (Shuffle
== nullptr)
1125 if (Shuffle
->getOperand(0) != NextRdxOp
)
1128 // Check that shuffle masks matches.
1129 for (unsigned j
= 0; j
!= MaskStart
; ++j
)
1130 ShuffleMask
[j
] = MaskStart
+ j
;
1131 // Fill the rest of the mask with -1 for undef.
1132 std::fill(&ShuffleMask
[MaskStart
], ShuffleMask
.end(), -1);
1134 SmallVector
<int, 16> Mask
= Shuffle
->getShuffleMask();
1135 if (ShuffleMask
!= Mask
)
1138 RdxOp
= dyn_cast
<Instruction
>(NextRdxOp
);
1139 NumVecElemsRemain
/= 2;
1143 Opcode
= RD
->Opcode
;
1148 int TargetTransformInfo::getInstructionThroughput(const Instruction
*I
) const {
1149 switch (I
->getOpcode()) {
1150 case Instruction::GetElementPtr
:
1151 return getUserCost(I
);
1153 case Instruction::Ret
:
1154 case Instruction::PHI
:
1155 case Instruction::Br
: {
1156 return getCFInstrCost(I
->getOpcode());
1158 case Instruction::Add
:
1159 case Instruction::FAdd
:
1160 case Instruction::Sub
:
1161 case Instruction::FSub
:
1162 case Instruction::Mul
:
1163 case Instruction::FMul
:
1164 case Instruction::UDiv
:
1165 case Instruction::SDiv
:
1166 case Instruction::FDiv
:
1167 case Instruction::URem
:
1168 case Instruction::SRem
:
1169 case Instruction::FRem
:
1170 case Instruction::Shl
:
1171 case Instruction::LShr
:
1172 case Instruction::AShr
:
1173 case Instruction::And
:
1174 case Instruction::Or
:
1175 case Instruction::Xor
: {
1176 TargetTransformInfo::OperandValueKind Op1VK
, Op2VK
;
1177 TargetTransformInfo::OperandValueProperties Op1VP
, Op2VP
;
1178 Op1VK
= getOperandInfo(I
->getOperand(0), Op1VP
);
1179 Op2VK
= getOperandInfo(I
->getOperand(1), Op2VP
);
1180 SmallVector
<const Value
*, 2> Operands(I
->operand_values());
1181 return getArithmeticInstrCost(I
->getOpcode(), I
->getType(), Op1VK
, Op2VK
,
1182 Op1VP
, Op2VP
, Operands
);
1184 case Instruction::FNeg
: {
1185 TargetTransformInfo::OperandValueKind Op1VK
, Op2VK
;
1186 TargetTransformInfo::OperandValueProperties Op1VP
, Op2VP
;
1187 Op1VK
= getOperandInfo(I
->getOperand(0), Op1VP
);
1188 Op2VK
= OK_AnyValue
;
1190 SmallVector
<const Value
*, 2> Operands(I
->operand_values());
1191 return getArithmeticInstrCost(I
->getOpcode(), I
->getType(), Op1VK
, Op2VK
,
1192 Op1VP
, Op2VP
, Operands
);
1194 case Instruction::Select
: {
1195 const SelectInst
*SI
= cast
<SelectInst
>(I
);
1196 Type
*CondTy
= SI
->getCondition()->getType();
1197 return getCmpSelInstrCost(I
->getOpcode(), I
->getType(), CondTy
, I
);
1199 case Instruction::ICmp
:
1200 case Instruction::FCmp
: {
1201 Type
*ValTy
= I
->getOperand(0)->getType();
1202 return getCmpSelInstrCost(I
->getOpcode(), ValTy
, I
->getType(), I
);
1204 case Instruction::Store
: {
1205 const StoreInst
*SI
= cast
<StoreInst
>(I
);
1206 Type
*ValTy
= SI
->getValueOperand()->getType();
1207 return getMemoryOpCost(I
->getOpcode(), ValTy
,
1209 SI
->getPointerAddressSpace(), I
);
1211 case Instruction::Load
: {
1212 const LoadInst
*LI
= cast
<LoadInst
>(I
);
1213 return getMemoryOpCost(I
->getOpcode(), I
->getType(),
1215 LI
->getPointerAddressSpace(), I
);
1217 case Instruction::ZExt
:
1218 case Instruction::SExt
:
1219 case Instruction::FPToUI
:
1220 case Instruction::FPToSI
:
1221 case Instruction::FPExt
:
1222 case Instruction::PtrToInt
:
1223 case Instruction::IntToPtr
:
1224 case Instruction::SIToFP
:
1225 case Instruction::UIToFP
:
1226 case Instruction::Trunc
:
1227 case Instruction::FPTrunc
:
1228 case Instruction::BitCast
:
1229 case Instruction::AddrSpaceCast
: {
1230 Type
*SrcTy
= I
->getOperand(0)->getType();
1231 return getCastInstrCost(I
->getOpcode(), I
->getType(), SrcTy
, I
);
1233 case Instruction::ExtractElement
: {
1234 const ExtractElementInst
* EEI
= cast
<ExtractElementInst
>(I
);
1235 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(I
->getOperand(1));
1238 Idx
= CI
->getZExtValue();
1240 // Try to match a reduction sequence (series of shufflevector and vector
1241 // adds followed by a extractelement).
1242 unsigned ReduxOpCode
;
1245 switch (matchVectorSplittingReduction(EEI
, ReduxOpCode
, ReduxType
)) {
1247 return getArithmeticReductionCost(ReduxOpCode
, ReduxType
,
1248 /*IsPairwiseForm=*/false);
1250 return getMinMaxReductionCost(
1251 ReduxType
, CmpInst::makeCmpResultType(ReduxType
),
1252 /*IsPairwiseForm=*/false, /*IsUnsigned=*/false);
1253 case RK_UnsignedMinMax
:
1254 return getMinMaxReductionCost(
1255 ReduxType
, CmpInst::makeCmpResultType(ReduxType
),
1256 /*IsPairwiseForm=*/false, /*IsUnsigned=*/true);
1261 switch (matchPairwiseReduction(EEI
, ReduxOpCode
, ReduxType
)) {
1263 return getArithmeticReductionCost(ReduxOpCode
, ReduxType
,
1264 /*IsPairwiseForm=*/true);
1266 return getMinMaxReductionCost(
1267 ReduxType
, CmpInst::makeCmpResultType(ReduxType
),
1268 /*IsPairwiseForm=*/true, /*IsUnsigned=*/false);
1269 case RK_UnsignedMinMax
:
1270 return getMinMaxReductionCost(
1271 ReduxType
, CmpInst::makeCmpResultType(ReduxType
),
1272 /*IsPairwiseForm=*/true, /*IsUnsigned=*/true);
1277 return getVectorInstrCost(I
->getOpcode(),
1278 EEI
->getOperand(0)->getType(), Idx
);
1280 case Instruction::InsertElement
: {
1281 const InsertElementInst
* IE
= cast
<InsertElementInst
>(I
);
1282 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(IE
->getOperand(2));
1285 Idx
= CI
->getZExtValue();
1286 return getVectorInstrCost(I
->getOpcode(),
1287 IE
->getType(), Idx
);
1289 case Instruction::ExtractValue
:
1290 return 0; // Model all ExtractValue nodes as free.
1291 case Instruction::ShuffleVector
: {
1292 const ShuffleVectorInst
*Shuffle
= cast
<ShuffleVectorInst
>(I
);
1293 Type
*Ty
= Shuffle
->getType();
1294 Type
*SrcTy
= Shuffle
->getOperand(0)->getType();
1296 // TODO: Identify and add costs for insert subvector, etc.
1298 if (Shuffle
->isExtractSubvectorMask(SubIndex
))
1299 return TTIImpl
->getShuffleCost(SK_ExtractSubvector
, SrcTy
, SubIndex
, Ty
);
1301 if (Shuffle
->changesLength())
1304 if (Shuffle
->isIdentity())
1307 if (Shuffle
->isReverse())
1308 return TTIImpl
->getShuffleCost(SK_Reverse
, Ty
, 0, nullptr);
1310 if (Shuffle
->isSelect())
1311 return TTIImpl
->getShuffleCost(SK_Select
, Ty
, 0, nullptr);
1313 if (Shuffle
->isTranspose())
1314 return TTIImpl
->getShuffleCost(SK_Transpose
, Ty
, 0, nullptr);
1316 if (Shuffle
->isZeroEltSplat())
1317 return TTIImpl
->getShuffleCost(SK_Broadcast
, Ty
, 0, nullptr);
1319 if (Shuffle
->isSingleSource())
1320 return TTIImpl
->getShuffleCost(SK_PermuteSingleSrc
, Ty
, 0, nullptr);
1322 return TTIImpl
->getShuffleCost(SK_PermuteTwoSrc
, Ty
, 0, nullptr);
1324 case Instruction::Call
:
1325 if (const IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(I
)) {
1326 SmallVector
<Value
*, 4> Args(II
->arg_operands());
1329 if (auto *FPMO
= dyn_cast
<FPMathOperator
>(II
))
1330 FMF
= FPMO
->getFastMathFlags();
1332 return getIntrinsicInstrCost(II
->getIntrinsicID(), II
->getType(),
1337 // We don't have any information on this instruction.
1342 TargetTransformInfo::Concept::~Concept() {}
1344 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI
) {}
1346 TargetIRAnalysis::TargetIRAnalysis(
1347 std::function
<Result(const Function
&)> TTICallback
)
1348 : TTICallback(std::move(TTICallback
)) {}
1350 TargetIRAnalysis::Result
TargetIRAnalysis::run(const Function
&F
,
1351 FunctionAnalysisManager
&) {
1352 return TTICallback(F
);
1355 AnalysisKey
TargetIRAnalysis::Key
;
1357 TargetIRAnalysis::Result
TargetIRAnalysis::getDefaultTTI(const Function
&F
) {
1358 return Result(F
.getParent()->getDataLayout());
1361 // Register the basic pass.
1362 INITIALIZE_PASS(TargetTransformInfoWrapperPass
, "tti",
1363 "Target Transform Information", false, true)
1364 char TargetTransformInfoWrapperPass::ID
= 0;
1366 void TargetTransformInfoWrapperPass::anchor() {}
1368 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass()
1369 : ImmutablePass(ID
) {
1370 initializeTargetTransformInfoWrapperPassPass(
1371 *PassRegistry::getPassRegistry());
1374 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass(
1375 TargetIRAnalysis TIRA
)
1376 : ImmutablePass(ID
), TIRA(std::move(TIRA
)) {
1377 initializeTargetTransformInfoWrapperPassPass(
1378 *PassRegistry::getPassRegistry());
1381 TargetTransformInfo
&TargetTransformInfoWrapperPass::getTTI(const Function
&F
) {
1382 FunctionAnalysisManager DummyFAM
;
1383 TTI
= TIRA
.run(F
, DummyFAM
);
1388 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA
) {
1389 return new TargetTransformInfoWrapperPass(std::move(TIRA
));