1 //===- llvm/Analysis/TargetTransformInfo.cpp ------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Analysis/TargetTransformInfo.h" 10 #include "llvm/Analysis/CFG.h" 11 #include "llvm/Analysis/LoopIterator.h" 12 #include "llvm/Analysis/TargetTransformInfoImpl.h" 13 #include "llvm/IR/CFG.h" 14 #include "llvm/IR/DataLayout.h" 15 #include "llvm/IR/Dominators.h" 16 #include "llvm/IR/Instruction.h" 17 #include "llvm/IR/Instructions.h" 18 #include "llvm/IR/IntrinsicInst.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/IR/Operator.h" 21 #include "llvm/IR/PatternMatch.h" 22 #include "llvm/InitializePasses.h" 23 #include "llvm/Support/CommandLine.h" 24 #include "llvm/Support/ErrorHandling.h" 25 #include <utility> 26 27 using namespace llvm; 28 using namespace PatternMatch; 29 30 #define DEBUG_TYPE "tti" 31 32 static cl::opt<bool> EnableReduxCost("costmodel-reduxcost", cl::init(false), 33 cl::Hidden, 34 cl::desc("Recognize reduction patterns.")); 35 36 namespace { 37 /// No-op implementation of the TTI interface using the utility base 38 /// classes. 39 /// 40 /// This is used when no target specific information is available. 41 struct NoTTIImpl : TargetTransformInfoImplCRTPBase<NoTTIImpl> { 42 explicit NoTTIImpl(const DataLayout &DL) 43 : TargetTransformInfoImplCRTPBase<NoTTIImpl>(DL) {} 44 }; 45 } // namespace 46 47 bool HardwareLoopInfo::canAnalyze(LoopInfo &LI) { 48 // If the loop has irreducible control flow, it can not be converted to 49 // Hardware loop. 50 LoopBlocksRPO RPOT(L); 51 RPOT.perform(&LI); 52 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI)) 53 return false; 54 return true; 55 } 56 57 IntrinsicCostAttributes::IntrinsicCostAttributes(const IntrinsicInst &I) : 58 II(&I), RetTy(I.getType()), IID(I.getIntrinsicID()) { 59 60 FunctionType *FTy = I.getCalledFunction()->getFunctionType(); 61 ParamTys.insert(ParamTys.begin(), FTy->param_begin(), FTy->param_end()); 62 Arguments.insert(Arguments.begin(), I.arg_begin(), I.arg_end()); 63 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 64 FMF = FPMO->getFastMathFlags(); 65 } 66 67 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, 68 const CallBase &CI) : 69 II(dyn_cast<IntrinsicInst>(&CI)), RetTy(CI.getType()), IID(Id) { 70 71 if (const auto *FPMO = dyn_cast<FPMathOperator>(&CI)) 72 FMF = FPMO->getFastMathFlags(); 73 74 Arguments.insert(Arguments.begin(), CI.arg_begin(), CI.arg_end()); 75 FunctionType *FTy = 76 CI.getCalledFunction()->getFunctionType(); 77 ParamTys.insert(ParamTys.begin(), FTy->param_begin(), FTy->param_end()); 78 } 79 80 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, 81 const CallBase &CI, 82 ElementCount Factor) 83 : RetTy(CI.getType()), IID(Id), VF(Factor) { 84 85 assert(!Factor.isScalable() && "Scalable vectors are not yet supported"); 86 if (auto *FPMO = dyn_cast<FPMathOperator>(&CI)) 87 FMF = FPMO->getFastMathFlags(); 88 89 Arguments.insert(Arguments.begin(), CI.arg_begin(), CI.arg_end()); 90 FunctionType *FTy = 91 CI.getCalledFunction()->getFunctionType(); 92 ParamTys.insert(ParamTys.begin(), FTy->param_begin(), FTy->param_end()); 93 } 94 95 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, 96 const CallBase &CI, 97 ElementCount Factor, 98 unsigned ScalarCost) 99 : RetTy(CI.getType()), IID(Id), VF(Factor), ScalarizationCost(ScalarCost) { 100 101 if (const auto *FPMO = dyn_cast<FPMathOperator>(&CI)) 102 FMF = FPMO->getFastMathFlags(); 103 104 Arguments.insert(Arguments.begin(), CI.arg_begin(), CI.arg_end()); 105 FunctionType *FTy = 106 CI.getCalledFunction()->getFunctionType(); 107 ParamTys.insert(ParamTys.begin(), FTy->param_begin(), FTy->param_end()); 108 } 109 110 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy, 111 ArrayRef<Type *> Tys, 112 FastMathFlags Flags) : 113 RetTy(RTy), IID(Id), FMF(Flags) { 114 ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end()); 115 } 116 117 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy, 118 ArrayRef<Type *> Tys, 119 FastMathFlags Flags, 120 unsigned ScalarCost) : 121 RetTy(RTy), IID(Id), FMF(Flags), ScalarizationCost(ScalarCost) { 122 ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end()); 123 } 124 125 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy, 126 ArrayRef<Type *> Tys, 127 FastMathFlags Flags, 128 unsigned ScalarCost, 129 const IntrinsicInst *I) : 130 II(I), RetTy(RTy), IID(Id), FMF(Flags), ScalarizationCost(ScalarCost) { 131 ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end()); 132 } 133 134 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy, 135 ArrayRef<Type *> Tys) : 136 RetTy(RTy), IID(Id) { 137 ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end()); 138 } 139 140 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *Ty, 141 ArrayRef<const Value *> Args) 142 : RetTy(Ty), IID(Id) { 143 144 Arguments.insert(Arguments.begin(), Args.begin(), Args.end()); 145 ParamTys.reserve(Arguments.size()); 146 for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx) 147 ParamTys.push_back(Arguments[Idx]->getType()); 148 } 149 150 bool HardwareLoopInfo::isHardwareLoopCandidate(ScalarEvolution &SE, 151 LoopInfo &LI, DominatorTree &DT, 152 bool ForceNestedLoop, 153 bool ForceHardwareLoopPHI) { 154 SmallVector<BasicBlock *, 4> ExitingBlocks; 155 L->getExitingBlocks(ExitingBlocks); 156 157 for (BasicBlock *BB : ExitingBlocks) { 158 // If we pass the updated counter back through a phi, we need to know 159 // which latch the updated value will be coming from. 160 if (!L->isLoopLatch(BB)) { 161 if (ForceHardwareLoopPHI || CounterInReg) 162 continue; 163 } 164 165 const SCEV *EC = SE.getExitCount(L, BB); 166 if (isa<SCEVCouldNotCompute>(EC)) 167 continue; 168 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) { 169 if (ConstEC->getValue()->isZero()) 170 continue; 171 } else if (!SE.isLoopInvariant(EC, L)) 172 continue; 173 174 if (SE.getTypeSizeInBits(EC->getType()) > CountType->getBitWidth()) 175 continue; 176 177 // If this exiting block is contained in a nested loop, it is not eligible 178 // for insertion of the branch-and-decrement since the inner loop would 179 // end up messing up the value in the CTR. 180 if (!IsNestingLegal && LI.getLoopFor(BB) != L && !ForceNestedLoop) 181 continue; 182 183 // We now have a loop-invariant count of loop iterations (which is not the 184 // constant zero) for which we know that this loop will not exit via this 185 // existing block. 186 187 // We need to make sure that this block will run on every loop iteration. 188 // For this to be true, we must dominate all blocks with backedges. Such 189 // blocks are in-loop predecessors to the header block. 190 bool NotAlways = false; 191 for (BasicBlock *Pred : predecessors(L->getHeader())) { 192 if (!L->contains(Pred)) 193 continue; 194 195 if (!DT.dominates(BB, Pred)) { 196 NotAlways = true; 197 break; 198 } 199 } 200 201 if (NotAlways) 202 continue; 203 204 // Make sure this blocks ends with a conditional branch. 205 Instruction *TI = BB->getTerminator(); 206 if (!TI) 207 continue; 208 209 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 210 if (!BI->isConditional()) 211 continue; 212 213 ExitBranch = BI; 214 } else 215 continue; 216 217 // Note that this block may not be the loop latch block, even if the loop 218 // has a latch block. 219 ExitBlock = BB; 220 ExitCount = EC; 221 222 break; 223 } 224 225 if (!ExitBlock) 226 return false; 227 return true; 228 } 229 230 TargetTransformInfo::TargetTransformInfo(const DataLayout &DL) 231 : TTIImpl(new Model<NoTTIImpl>(NoTTIImpl(DL))) {} 232 233 TargetTransformInfo::~TargetTransformInfo() {} 234 235 TargetTransformInfo::TargetTransformInfo(TargetTransformInfo &&Arg) 236 : TTIImpl(std::move(Arg.TTIImpl)) {} 237 238 TargetTransformInfo &TargetTransformInfo::operator=(TargetTransformInfo &&RHS) { 239 TTIImpl = std::move(RHS.TTIImpl); 240 return *this; 241 } 242 243 unsigned TargetTransformInfo::getInliningThresholdMultiplier() const { 244 return TTIImpl->getInliningThresholdMultiplier(); 245 } 246 247 unsigned 248 TargetTransformInfo::adjustInliningThreshold(const CallBase *CB) const { 249 return TTIImpl->adjustInliningThreshold(CB); 250 } 251 252 int TargetTransformInfo::getInlinerVectorBonusPercent() const { 253 return TTIImpl->getInlinerVectorBonusPercent(); 254 } 255 256 int TargetTransformInfo::getGEPCost(Type *PointeeType, const Value *Ptr, 257 ArrayRef<const Value *> Operands, 258 TTI::TargetCostKind CostKind) const { 259 return TTIImpl->getGEPCost(PointeeType, Ptr, Operands, CostKind); 260 } 261 262 unsigned TargetTransformInfo::getEstimatedNumberOfCaseClusters( 263 const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, 264 BlockFrequencyInfo *BFI) const { 265 return TTIImpl->getEstimatedNumberOfCaseClusters(SI, JTSize, PSI, BFI); 266 } 267 268 int TargetTransformInfo::getUserCost(const User *U, 269 ArrayRef<const Value *> Operands, 270 enum TargetCostKind CostKind) const { 271 int Cost = TTIImpl->getUserCost(U, Operands, CostKind); 272 assert((CostKind == TTI::TCK_RecipThroughput || Cost >= 0) && 273 "TTI should not produce negative costs!"); 274 return Cost; 275 } 276 277 bool TargetTransformInfo::hasBranchDivergence() const { 278 return TTIImpl->hasBranchDivergence(); 279 } 280 281 bool TargetTransformInfo::useGPUDivergenceAnalysis() const { 282 return TTIImpl->useGPUDivergenceAnalysis(); 283 } 284 285 bool TargetTransformInfo::isSourceOfDivergence(const Value *V) const { 286 return TTIImpl->isSourceOfDivergence(V); 287 } 288 289 bool llvm::TargetTransformInfo::isAlwaysUniform(const Value *V) const { 290 return TTIImpl->isAlwaysUniform(V); 291 } 292 293 unsigned TargetTransformInfo::getFlatAddressSpace() const { 294 return TTIImpl->getFlatAddressSpace(); 295 } 296 297 bool TargetTransformInfo::collectFlatAddressOperands( 298 SmallVectorImpl<int> &OpIndexes, Intrinsic::ID IID) const { 299 return TTIImpl->collectFlatAddressOperands(OpIndexes, IID); 300 } 301 302 bool TargetTransformInfo::isNoopAddrSpaceCast(unsigned FromAS, 303 unsigned ToAS) const { 304 return TTIImpl->isNoopAddrSpaceCast(FromAS, ToAS); 305 } 306 307 unsigned TargetTransformInfo::getAssumedAddrSpace(const Value *V) const { 308 return TTIImpl->getAssumedAddrSpace(V); 309 } 310 311 Value *TargetTransformInfo::rewriteIntrinsicWithAddressSpace( 312 IntrinsicInst *II, Value *OldV, Value *NewV) const { 313 return TTIImpl->rewriteIntrinsicWithAddressSpace(II, OldV, NewV); 314 } 315 316 bool TargetTransformInfo::isLoweredToCall(const Function *F) const { 317 return TTIImpl->isLoweredToCall(F); 318 } 319 320 bool TargetTransformInfo::isHardwareLoopProfitable( 321 Loop *L, ScalarEvolution &SE, AssumptionCache &AC, 322 TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const { 323 return TTIImpl->isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo); 324 } 325 326 bool TargetTransformInfo::preferPredicateOverEpilogue( 327 Loop *L, LoopInfo *LI, ScalarEvolution &SE, AssumptionCache &AC, 328 TargetLibraryInfo *TLI, DominatorTree *DT, 329 const LoopAccessInfo *LAI) const { 330 return TTIImpl->preferPredicateOverEpilogue(L, LI, SE, AC, TLI, DT, LAI); 331 } 332 333 bool TargetTransformInfo::emitGetActiveLaneMask() const { 334 return TTIImpl->emitGetActiveLaneMask(); 335 } 336 337 Optional<Instruction *> 338 TargetTransformInfo::instCombineIntrinsic(InstCombiner &IC, 339 IntrinsicInst &II) const { 340 return TTIImpl->instCombineIntrinsic(IC, II); 341 } 342 343 Optional<Value *> TargetTransformInfo::simplifyDemandedUseBitsIntrinsic( 344 InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, 345 bool &KnownBitsComputed) const { 346 return TTIImpl->simplifyDemandedUseBitsIntrinsic(IC, II, DemandedMask, Known, 347 KnownBitsComputed); 348 } 349 350 Optional<Value *> TargetTransformInfo::simplifyDemandedVectorEltsIntrinsic( 351 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, 352 APInt &UndefElts2, APInt &UndefElts3, 353 std::function<void(Instruction *, unsigned, APInt, APInt &)> 354 SimplifyAndSetOp) const { 355 return TTIImpl->simplifyDemandedVectorEltsIntrinsic( 356 IC, II, DemandedElts, UndefElts, UndefElts2, UndefElts3, 357 SimplifyAndSetOp); 358 } 359 360 void TargetTransformInfo::getUnrollingPreferences( 361 Loop *L, ScalarEvolution &SE, UnrollingPreferences &UP) const { 362 return TTIImpl->getUnrollingPreferences(L, SE, UP); 363 } 364 365 void TargetTransformInfo::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 366 PeelingPreferences &PP) const { 367 return TTIImpl->getPeelingPreferences(L, SE, PP); 368 } 369 370 bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm) const { 371 return TTIImpl->isLegalAddImmediate(Imm); 372 } 373 374 bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm) const { 375 return TTIImpl->isLegalICmpImmediate(Imm); 376 } 377 378 bool TargetTransformInfo::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, 379 int64_t BaseOffset, 380 bool HasBaseReg, int64_t Scale, 381 unsigned AddrSpace, 382 Instruction *I) const { 383 return TTIImpl->isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg, 384 Scale, AddrSpace, I); 385 } 386 387 bool TargetTransformInfo::isLSRCostLess(LSRCost &C1, LSRCost &C2) const { 388 return TTIImpl->isLSRCostLess(C1, C2); 389 } 390 391 bool TargetTransformInfo::isNumRegsMajorCostOfLSR() const { 392 return TTIImpl->isNumRegsMajorCostOfLSR(); 393 } 394 395 bool TargetTransformInfo::isProfitableLSRChainElement(Instruction *I) const { 396 return TTIImpl->isProfitableLSRChainElement(I); 397 } 398 399 bool TargetTransformInfo::canMacroFuseCmp() const { 400 return TTIImpl->canMacroFuseCmp(); 401 } 402 403 bool TargetTransformInfo::canSaveCmp(Loop *L, BranchInst **BI, 404 ScalarEvolution *SE, LoopInfo *LI, 405 DominatorTree *DT, AssumptionCache *AC, 406 TargetLibraryInfo *LibInfo) const { 407 return TTIImpl->canSaveCmp(L, BI, SE, LI, DT, AC, LibInfo); 408 } 409 410 bool TargetTransformInfo::shouldFavorPostInc() const { 411 return TTIImpl->shouldFavorPostInc(); 412 } 413 414 bool TargetTransformInfo::shouldFavorBackedgeIndex(const Loop *L) const { 415 return TTIImpl->shouldFavorBackedgeIndex(L); 416 } 417 418 bool TargetTransformInfo::isLegalMaskedStore(Type *DataType, 419 Align Alignment) const { 420 return TTIImpl->isLegalMaskedStore(DataType, Alignment); 421 } 422 423 bool TargetTransformInfo::isLegalMaskedLoad(Type *DataType, 424 Align Alignment) const { 425 return TTIImpl->isLegalMaskedLoad(DataType, Alignment); 426 } 427 428 bool TargetTransformInfo::isLegalNTStore(Type *DataType, 429 Align Alignment) const { 430 return TTIImpl->isLegalNTStore(DataType, Alignment); 431 } 432 433 bool TargetTransformInfo::isLegalNTLoad(Type *DataType, Align Alignment) const { 434 return TTIImpl->isLegalNTLoad(DataType, Alignment); 435 } 436 437 bool TargetTransformInfo::isLegalMaskedGather(Type *DataType, 438 Align Alignment) const { 439 return TTIImpl->isLegalMaskedGather(DataType, Alignment); 440 } 441 442 bool TargetTransformInfo::isLegalMaskedScatter(Type *DataType, 443 Align Alignment) const { 444 return TTIImpl->isLegalMaskedScatter(DataType, Alignment); 445 } 446 447 bool TargetTransformInfo::isLegalMaskedCompressStore(Type *DataType) const { 448 return TTIImpl->isLegalMaskedCompressStore(DataType); 449 } 450 451 bool TargetTransformInfo::isLegalMaskedExpandLoad(Type *DataType) const { 452 return TTIImpl->isLegalMaskedExpandLoad(DataType); 453 } 454 455 bool TargetTransformInfo::hasDivRemOp(Type *DataType, bool IsSigned) const { 456 return TTIImpl->hasDivRemOp(DataType, IsSigned); 457 } 458 459 bool TargetTransformInfo::hasVolatileVariant(Instruction *I, 460 unsigned AddrSpace) const { 461 return TTIImpl->hasVolatileVariant(I, AddrSpace); 462 } 463 464 bool TargetTransformInfo::prefersVectorizedAddressing() const { 465 return TTIImpl->prefersVectorizedAddressing(); 466 } 467 468 int TargetTransformInfo::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, 469 int64_t BaseOffset, 470 bool HasBaseReg, int64_t Scale, 471 unsigned AddrSpace) const { 472 int Cost = TTIImpl->getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, 473 Scale, AddrSpace); 474 assert(Cost >= 0 && "TTI should not produce negative costs!"); 475 return Cost; 476 } 477 478 bool TargetTransformInfo::LSRWithInstrQueries() const { 479 return TTIImpl->LSRWithInstrQueries(); 480 } 481 482 bool TargetTransformInfo::isTruncateFree(Type *Ty1, Type *Ty2) const { 483 return TTIImpl->isTruncateFree(Ty1, Ty2); 484 } 485 486 bool TargetTransformInfo::isProfitableToHoist(Instruction *I) const { 487 return TTIImpl->isProfitableToHoist(I); 488 } 489 490 bool TargetTransformInfo::useAA() const { return TTIImpl->useAA(); } 491 492 bool TargetTransformInfo::isTypeLegal(Type *Ty) const { 493 return TTIImpl->isTypeLegal(Ty); 494 } 495 496 unsigned TargetTransformInfo::getRegUsageForType(Type *Ty) const { 497 return TTIImpl->getRegUsageForType(Ty); 498 } 499 500 bool TargetTransformInfo::shouldBuildLookupTables() const { 501 return TTIImpl->shouldBuildLookupTables(); 502 } 503 bool TargetTransformInfo::shouldBuildLookupTablesForConstant( 504 Constant *C) const { 505 return TTIImpl->shouldBuildLookupTablesForConstant(C); 506 } 507 508 bool TargetTransformInfo::useColdCCForColdCall(Function &F) const { 509 return TTIImpl->useColdCCForColdCall(F); 510 } 511 512 unsigned 513 TargetTransformInfo::getScalarizationOverhead(VectorType *Ty, 514 const APInt &DemandedElts, 515 bool Insert, bool Extract) const { 516 return TTIImpl->getScalarizationOverhead(Ty, DemandedElts, Insert, Extract); 517 } 518 519 unsigned TargetTransformInfo::getOperandsScalarizationOverhead( 520 ArrayRef<const Value *> Args, unsigned VF) const { 521 return TTIImpl->getOperandsScalarizationOverhead(Args, VF); 522 } 523 524 bool TargetTransformInfo::supportsEfficientVectorElementLoadStore() const { 525 return TTIImpl->supportsEfficientVectorElementLoadStore(); 526 } 527 528 bool TargetTransformInfo::enableAggressiveInterleaving( 529 bool LoopHasReductions) const { 530 return TTIImpl->enableAggressiveInterleaving(LoopHasReductions); 531 } 532 533 TargetTransformInfo::MemCmpExpansionOptions 534 TargetTransformInfo::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const { 535 return TTIImpl->enableMemCmpExpansion(OptSize, IsZeroCmp); 536 } 537 538 bool TargetTransformInfo::enableInterleavedAccessVectorization() const { 539 return TTIImpl->enableInterleavedAccessVectorization(); 540 } 541 542 bool TargetTransformInfo::enableMaskedInterleavedAccessVectorization() const { 543 return TTIImpl->enableMaskedInterleavedAccessVectorization(); 544 } 545 546 bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const { 547 return TTIImpl->isFPVectorizationPotentiallyUnsafe(); 548 } 549 550 bool TargetTransformInfo::allowsMisalignedMemoryAccesses(LLVMContext &Context, 551 unsigned BitWidth, 552 unsigned AddressSpace, 553 unsigned Alignment, 554 bool *Fast) const { 555 return TTIImpl->allowsMisalignedMemoryAccesses(Context, BitWidth, 556 AddressSpace, Alignment, Fast); 557 } 558 559 TargetTransformInfo::PopcntSupportKind 560 TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit) const { 561 return TTIImpl->getPopcntSupport(IntTyWidthInBit); 562 } 563 564 bool TargetTransformInfo::haveFastSqrt(Type *Ty) const { 565 return TTIImpl->haveFastSqrt(Ty); 566 } 567 568 bool TargetTransformInfo::isFCmpOrdCheaperThanFCmpZero(Type *Ty) const { 569 return TTIImpl->isFCmpOrdCheaperThanFCmpZero(Ty); 570 } 571 572 int TargetTransformInfo::getFPOpCost(Type *Ty) const { 573 int Cost = TTIImpl->getFPOpCost(Ty); 574 assert(Cost >= 0 && "TTI should not produce negative costs!"); 575 return Cost; 576 } 577 578 int TargetTransformInfo::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, 579 const APInt &Imm, 580 Type *Ty) const { 581 int Cost = TTIImpl->getIntImmCodeSizeCost(Opcode, Idx, Imm, Ty); 582 assert(Cost >= 0 && "TTI should not produce negative costs!"); 583 return Cost; 584 } 585 586 int TargetTransformInfo::getIntImmCost(const APInt &Imm, Type *Ty, 587 TTI::TargetCostKind CostKind) const { 588 int Cost = TTIImpl->getIntImmCost(Imm, Ty, CostKind); 589 assert(Cost >= 0 && "TTI should not produce negative costs!"); 590 return Cost; 591 } 592 593 int TargetTransformInfo::getIntImmCostInst(unsigned Opcode, unsigned Idx, 594 const APInt &Imm, Type *Ty, 595 TTI::TargetCostKind CostKind, 596 Instruction *Inst) const { 597 int Cost = TTIImpl->getIntImmCostInst(Opcode, Idx, Imm, Ty, CostKind, Inst); 598 assert(Cost >= 0 && "TTI should not produce negative costs!"); 599 return Cost; 600 } 601 602 int 603 TargetTransformInfo::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, 604 const APInt &Imm, Type *Ty, 605 TTI::TargetCostKind CostKind) const { 606 int Cost = TTIImpl->getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind); 607 assert(Cost >= 0 && "TTI should not produce negative costs!"); 608 return Cost; 609 } 610 611 unsigned TargetTransformInfo::getNumberOfRegisters(unsigned ClassID) const { 612 return TTIImpl->getNumberOfRegisters(ClassID); 613 } 614 615 unsigned TargetTransformInfo::getRegisterClassForType(bool Vector, 616 Type *Ty) const { 617 return TTIImpl->getRegisterClassForType(Vector, Ty); 618 } 619 620 const char *TargetTransformInfo::getRegisterClassName(unsigned ClassID) const { 621 return TTIImpl->getRegisterClassName(ClassID); 622 } 623 624 unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector) const { 625 return TTIImpl->getRegisterBitWidth(Vector); 626 } 627 628 unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const { 629 return TTIImpl->getMinVectorRegisterBitWidth(); 630 } 631 632 Optional<unsigned> TargetTransformInfo::getMaxVScale() const { 633 return TTIImpl->getMaxVScale(); 634 } 635 636 bool TargetTransformInfo::shouldMaximizeVectorBandwidth(bool OptSize) const { 637 return TTIImpl->shouldMaximizeVectorBandwidth(OptSize); 638 } 639 640 unsigned TargetTransformInfo::getMinimumVF(unsigned ElemWidth) const { 641 return TTIImpl->getMinimumVF(ElemWidth); 642 } 643 644 unsigned TargetTransformInfo::getMaximumVF(unsigned ElemWidth, 645 unsigned Opcode) const { 646 return TTIImpl->getMaximumVF(ElemWidth, Opcode); 647 } 648 649 bool TargetTransformInfo::shouldConsiderAddressTypePromotion( 650 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const { 651 return TTIImpl->shouldConsiderAddressTypePromotion( 652 I, AllowPromotionWithoutCommonHeader); 653 } 654 655 unsigned TargetTransformInfo::getCacheLineSize() const { 656 return TTIImpl->getCacheLineSize(); 657 } 658 659 llvm::Optional<unsigned> 660 TargetTransformInfo::getCacheSize(CacheLevel Level) const { 661 return TTIImpl->getCacheSize(Level); 662 } 663 664 llvm::Optional<unsigned> 665 TargetTransformInfo::getCacheAssociativity(CacheLevel Level) const { 666 return TTIImpl->getCacheAssociativity(Level); 667 } 668 669 unsigned TargetTransformInfo::getPrefetchDistance() const { 670 return TTIImpl->getPrefetchDistance(); 671 } 672 673 unsigned TargetTransformInfo::getMinPrefetchStride( 674 unsigned NumMemAccesses, unsigned NumStridedMemAccesses, 675 unsigned NumPrefetches, bool HasCall) const { 676 return TTIImpl->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses, 677 NumPrefetches, HasCall); 678 } 679 680 unsigned TargetTransformInfo::getMaxPrefetchIterationsAhead() const { 681 return TTIImpl->getMaxPrefetchIterationsAhead(); 682 } 683 684 bool TargetTransformInfo::enableWritePrefetching() const { 685 return TTIImpl->enableWritePrefetching(); 686 } 687 688 unsigned TargetTransformInfo::getMaxInterleaveFactor(unsigned VF) const { 689 return TTIImpl->getMaxInterleaveFactor(VF); 690 } 691 692 TargetTransformInfo::OperandValueKind 693 TargetTransformInfo::getOperandInfo(const Value *V, 694 OperandValueProperties &OpProps) { 695 OperandValueKind OpInfo = OK_AnyValue; 696 OpProps = OP_None; 697 698 if (const auto *CI = dyn_cast<ConstantInt>(V)) { 699 if (CI->getValue().isPowerOf2()) 700 OpProps = OP_PowerOf2; 701 return OK_UniformConstantValue; 702 } 703 704 // A broadcast shuffle creates a uniform value. 705 // TODO: Add support for non-zero index broadcasts. 706 // TODO: Add support for different source vector width. 707 if (const auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V)) 708 if (ShuffleInst->isZeroEltSplat()) 709 OpInfo = OK_UniformValue; 710 711 const Value *Splat = getSplatValue(V); 712 713 // Check for a splat of a constant or for a non uniform vector of constants 714 // and check if the constant(s) are all powers of two. 715 if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) { 716 OpInfo = OK_NonUniformConstantValue; 717 if (Splat) { 718 OpInfo = OK_UniformConstantValue; 719 if (auto *CI = dyn_cast<ConstantInt>(Splat)) 720 if (CI->getValue().isPowerOf2()) 721 OpProps = OP_PowerOf2; 722 } else if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) { 723 OpProps = OP_PowerOf2; 724 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) { 725 if (auto *CI = dyn_cast<ConstantInt>(CDS->getElementAsConstant(I))) 726 if (CI->getValue().isPowerOf2()) 727 continue; 728 OpProps = OP_None; 729 break; 730 } 731 } 732 } 733 734 // Check for a splat of a uniform value. This is not loop aware, so return 735 // true only for the obviously uniform cases (argument, globalvalue) 736 if (Splat && (isa<Argument>(Splat) || isa<GlobalValue>(Splat))) 737 OpInfo = OK_UniformValue; 738 739 return OpInfo; 740 } 741 742 int TargetTransformInfo::getArithmeticInstrCost( 743 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, 744 OperandValueKind Opd1Info, 745 OperandValueKind Opd2Info, OperandValueProperties Opd1PropInfo, 746 OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args, 747 const Instruction *CxtI) const { 748 int Cost = TTIImpl->getArithmeticInstrCost( 749 Opcode, Ty, CostKind, Opd1Info, Opd2Info, Opd1PropInfo, Opd2PropInfo, 750 Args, CxtI); 751 assert(Cost >= 0 && "TTI should not produce negative costs!"); 752 return Cost; 753 } 754 755 int TargetTransformInfo::getShuffleCost(ShuffleKind Kind, VectorType *Ty, 756 int Index, VectorType *SubTp) const { 757 int Cost = TTIImpl->getShuffleCost(Kind, Ty, Index, SubTp); 758 assert(Cost >= 0 && "TTI should not produce negative costs!"); 759 return Cost; 760 } 761 762 TTI::CastContextHint 763 TargetTransformInfo::getCastContextHint(const Instruction *I) { 764 if (!I) 765 return CastContextHint::None; 766 767 auto getLoadStoreKind = [](const Value *V, unsigned LdStOp, unsigned MaskedOp, 768 unsigned GatScatOp) { 769 const Instruction *I = dyn_cast<Instruction>(V); 770 if (!I) 771 return CastContextHint::None; 772 773 if (I->getOpcode() == LdStOp) 774 return CastContextHint::Normal; 775 776 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 777 if (II->getIntrinsicID() == MaskedOp) 778 return TTI::CastContextHint::Masked; 779 if (II->getIntrinsicID() == GatScatOp) 780 return TTI::CastContextHint::GatherScatter; 781 } 782 783 return TTI::CastContextHint::None; 784 }; 785 786 switch (I->getOpcode()) { 787 case Instruction::ZExt: 788 case Instruction::SExt: 789 case Instruction::FPExt: 790 return getLoadStoreKind(I->getOperand(0), Instruction::Load, 791 Intrinsic::masked_load, Intrinsic::masked_gather); 792 case Instruction::Trunc: 793 case Instruction::FPTrunc: 794 if (I->hasOneUse()) 795 return getLoadStoreKind(*I->user_begin(), Instruction::Store, 796 Intrinsic::masked_store, 797 Intrinsic::masked_scatter); 798 break; 799 default: 800 return CastContextHint::None; 801 } 802 803 return TTI::CastContextHint::None; 804 } 805 806 int TargetTransformInfo::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, 807 CastContextHint CCH, 808 TTI::TargetCostKind CostKind, 809 const Instruction *I) const { 810 assert((I == nullptr || I->getOpcode() == Opcode) && 811 "Opcode should reflect passed instruction."); 812 int Cost = TTIImpl->getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I); 813 assert(Cost >= 0 && "TTI should not produce negative costs!"); 814 return Cost; 815 } 816 817 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode, Type *Dst, 818 VectorType *VecTy, 819 unsigned Index) const { 820 int Cost = TTIImpl->getExtractWithExtendCost(Opcode, Dst, VecTy, Index); 821 assert(Cost >= 0 && "TTI should not produce negative costs!"); 822 return Cost; 823 } 824 825 int TargetTransformInfo::getCFInstrCost(unsigned Opcode, 826 TTI::TargetCostKind CostKind) const { 827 int Cost = TTIImpl->getCFInstrCost(Opcode, CostKind); 828 assert(Cost >= 0 && "TTI should not produce negative costs!"); 829 return Cost; 830 } 831 832 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, 833 Type *CondTy, 834 CmpInst::Predicate VecPred, 835 TTI::TargetCostKind CostKind, 836 const Instruction *I) const { 837 assert((I == nullptr || I->getOpcode() == Opcode) && 838 "Opcode should reflect passed instruction."); 839 int Cost = 840 TTIImpl->getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I); 841 assert(Cost >= 0 && "TTI should not produce negative costs!"); 842 return Cost; 843 } 844 845 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val, 846 unsigned Index) const { 847 int Cost = TTIImpl->getVectorInstrCost(Opcode, Val, Index); 848 assert(Cost >= 0 && "TTI should not produce negative costs!"); 849 return Cost; 850 } 851 852 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src, 853 Align Alignment, unsigned AddressSpace, 854 TTI::TargetCostKind CostKind, 855 const Instruction *I) const { 856 assert((I == nullptr || I->getOpcode() == Opcode) && 857 "Opcode should reflect passed instruction."); 858 int Cost = TTIImpl->getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 859 CostKind, I); 860 assert(Cost >= 0 && "TTI should not produce negative costs!"); 861 return Cost; 862 } 863 864 int TargetTransformInfo::getMaskedMemoryOpCost( 865 unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, 866 TTI::TargetCostKind CostKind) const { 867 int Cost = 868 TTIImpl->getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 869 CostKind); 870 assert(Cost >= 0 && "TTI should not produce negative costs!"); 871 return Cost; 872 } 873 874 int TargetTransformInfo::getGatherScatterOpCost( 875 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, 876 Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) const { 877 int Cost = TTIImpl->getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask, 878 Alignment, CostKind, I); 879 assert(Cost >= 0 && "TTI should not produce negative costs!"); 880 return Cost; 881 } 882 883 int TargetTransformInfo::getInterleavedMemoryOpCost( 884 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 885 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, 886 bool UseMaskForCond, bool UseMaskForGaps) const { 887 int Cost = TTIImpl->getInterleavedMemoryOpCost( 888 Opcode, VecTy, Factor, Indices, Alignment, AddressSpace, CostKind, 889 UseMaskForCond, UseMaskForGaps); 890 assert(Cost >= 0 && "TTI should not produce negative costs!"); 891 return Cost; 892 } 893 894 int 895 TargetTransformInfo::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 896 TTI::TargetCostKind CostKind) const { 897 int Cost = TTIImpl->getIntrinsicInstrCost(ICA, CostKind); 898 assert(Cost >= 0 && "TTI should not produce negative costs!"); 899 return Cost; 900 } 901 902 int TargetTransformInfo::getCallInstrCost(Function *F, Type *RetTy, 903 ArrayRef<Type *> Tys, 904 TTI::TargetCostKind CostKind) const { 905 int Cost = TTIImpl->getCallInstrCost(F, RetTy, Tys, CostKind); 906 assert(Cost >= 0 && "TTI should not produce negative costs!"); 907 return Cost; 908 } 909 910 unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const { 911 return TTIImpl->getNumberOfParts(Tp); 912 } 913 914 int TargetTransformInfo::getAddressComputationCost(Type *Tp, 915 ScalarEvolution *SE, 916 const SCEV *Ptr) const { 917 int Cost = TTIImpl->getAddressComputationCost(Tp, SE, Ptr); 918 assert(Cost >= 0 && "TTI should not produce negative costs!"); 919 return Cost; 920 } 921 922 int TargetTransformInfo::getMemcpyCost(const Instruction *I) const { 923 int Cost = TTIImpl->getMemcpyCost(I); 924 assert(Cost >= 0 && "TTI should not produce negative costs!"); 925 return Cost; 926 } 927 928 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode, 929 VectorType *Ty, 930 bool IsPairwiseForm, 931 TTI::TargetCostKind CostKind) const { 932 int Cost = TTIImpl->getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm, 933 CostKind); 934 assert(Cost >= 0 && "TTI should not produce negative costs!"); 935 return Cost; 936 } 937 938 int TargetTransformInfo::getMinMaxReductionCost( 939 VectorType *Ty, VectorType *CondTy, bool IsPairwiseForm, bool IsUnsigned, 940 TTI::TargetCostKind CostKind) const { 941 int Cost = 942 TTIImpl->getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned, 943 CostKind); 944 assert(Cost >= 0 && "TTI should not produce negative costs!"); 945 return Cost; 946 } 947 948 InstructionCost TargetTransformInfo::getExtendedAddReductionCost( 949 bool IsMLA, bool IsUnsigned, Type *ResTy, VectorType *Ty, 950 TTI::TargetCostKind CostKind) const { 951 return TTIImpl->getExtendedAddReductionCost(IsMLA, IsUnsigned, ResTy, Ty, 952 CostKind); 953 } 954 955 unsigned 956 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const { 957 return TTIImpl->getCostOfKeepingLiveOverCall(Tys); 958 } 959 960 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst, 961 MemIntrinsicInfo &Info) const { 962 return TTIImpl->getTgtMemIntrinsic(Inst, Info); 963 } 964 965 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const { 966 return TTIImpl->getAtomicMemIntrinsicMaxElementSize(); 967 } 968 969 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic( 970 IntrinsicInst *Inst, Type *ExpectedType) const { 971 return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType); 972 } 973 974 Type *TargetTransformInfo::getMemcpyLoopLoweringType( 975 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace, 976 unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign) const { 977 return TTIImpl->getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace, 978 DestAddrSpace, SrcAlign, DestAlign); 979 } 980 981 void TargetTransformInfo::getMemcpyLoopResidualLoweringType( 982 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context, 983 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, 984 unsigned SrcAlign, unsigned DestAlign) const { 985 TTIImpl->getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes, 986 SrcAddrSpace, DestAddrSpace, 987 SrcAlign, DestAlign); 988 } 989 990 bool TargetTransformInfo::areInlineCompatible(const Function *Caller, 991 const Function *Callee) const { 992 return TTIImpl->areInlineCompatible(Caller, Callee); 993 } 994 995 bool TargetTransformInfo::areFunctionArgsABICompatible( 996 const Function *Caller, const Function *Callee, 997 SmallPtrSetImpl<Argument *> &Args) const { 998 return TTIImpl->areFunctionArgsABICompatible(Caller, Callee, Args); 999 } 1000 1001 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode, 1002 Type *Ty) const { 1003 return TTIImpl->isIndexedLoadLegal(Mode, Ty); 1004 } 1005 1006 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode, 1007 Type *Ty) const { 1008 return TTIImpl->isIndexedStoreLegal(Mode, Ty); 1009 } 1010 1011 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const { 1012 return TTIImpl->getLoadStoreVecRegBitWidth(AS); 1013 } 1014 1015 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const { 1016 return TTIImpl->isLegalToVectorizeLoad(LI); 1017 } 1018 1019 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const { 1020 return TTIImpl->isLegalToVectorizeStore(SI); 1021 } 1022 1023 bool TargetTransformInfo::isLegalToVectorizeLoadChain( 1024 unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const { 1025 return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment, 1026 AddrSpace); 1027 } 1028 1029 bool TargetTransformInfo::isLegalToVectorizeStoreChain( 1030 unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const { 1031 return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment, 1032 AddrSpace); 1033 } 1034 1035 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF, 1036 unsigned LoadSize, 1037 unsigned ChainSizeInBytes, 1038 VectorType *VecTy) const { 1039 return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy); 1040 } 1041 1042 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF, 1043 unsigned StoreSize, 1044 unsigned ChainSizeInBytes, 1045 VectorType *VecTy) const { 1046 return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy); 1047 } 1048 1049 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode, Type *Ty, 1050 ReductionFlags Flags) const { 1051 return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags); 1052 } 1053 1054 bool TargetTransformInfo::preferInLoopReduction(unsigned Opcode, Type *Ty, 1055 ReductionFlags Flags) const { 1056 return TTIImpl->preferInLoopReduction(Opcode, Ty, Flags); 1057 } 1058 1059 bool TargetTransformInfo::preferPredicatedReductionSelect( 1060 unsigned Opcode, Type *Ty, ReductionFlags Flags) const { 1061 return TTIImpl->preferPredicatedReductionSelect(Opcode, Ty, Flags); 1062 } 1063 1064 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const { 1065 return TTIImpl->shouldExpandReduction(II); 1066 } 1067 1068 unsigned TargetTransformInfo::getGISelRematGlobalCost() const { 1069 return TTIImpl->getGISelRematGlobalCost(); 1070 } 1071 1072 bool TargetTransformInfo::supportsScalableVectors() const { 1073 return TTIImpl->supportsScalableVectors(); 1074 } 1075 1076 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const { 1077 return TTIImpl->getInstructionLatency(I); 1078 } 1079 1080 static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft, 1081 unsigned Level) { 1082 // We don't need a shuffle if we just want to have element 0 in position 0 of 1083 // the vector. 1084 if (!SI && Level == 0 && IsLeft) 1085 return true; 1086 else if (!SI) 1087 return false; 1088 1089 SmallVector<int, 32> Mask( 1090 cast<FixedVectorType>(SI->getType())->getNumElements(), -1); 1091 1092 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether 1093 // we look at the left or right side. 1094 for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2) 1095 Mask[i] = val; 1096 1097 ArrayRef<int> ActualMask = SI->getShuffleMask(); 1098 return Mask == ActualMask; 1099 } 1100 1101 static Optional<TTI::ReductionData> getReductionData(Instruction *I) { 1102 Value *L, *R; 1103 if (m_BinOp(m_Value(L), m_Value(R)).match(I)) 1104 return TTI::ReductionData(TTI::RK_Arithmetic, I->getOpcode(), L, R); 1105 if (auto *SI = dyn_cast<SelectInst>(I)) { 1106 if (m_SMin(m_Value(L), m_Value(R)).match(SI) || 1107 m_SMax(m_Value(L), m_Value(R)).match(SI) || 1108 m_OrdFMin(m_Value(L), m_Value(R)).match(SI) || 1109 m_OrdFMax(m_Value(L), m_Value(R)).match(SI) || 1110 m_UnordFMin(m_Value(L), m_Value(R)).match(SI) || 1111 m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) { 1112 auto *CI = cast<CmpInst>(SI->getCondition()); 1113 return TTI::ReductionData(TTI::RK_MinMax, CI->getOpcode(), L, R); 1114 } 1115 if (m_UMin(m_Value(L), m_Value(R)).match(SI) || 1116 m_UMax(m_Value(L), m_Value(R)).match(SI)) { 1117 auto *CI = cast<CmpInst>(SI->getCondition()); 1118 return TTI::ReductionData(TTI::RK_UnsignedMinMax, CI->getOpcode(), L, R); 1119 } 1120 } 1121 return llvm::None; 1122 } 1123 1124 static TTI::ReductionKind matchPairwiseReductionAtLevel(Instruction *I, 1125 unsigned Level, 1126 unsigned NumLevels) { 1127 // Match one level of pairwise operations. 1128 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, 1129 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> 1130 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, 1131 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> 1132 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 1133 if (!I) 1134 return TTI::RK_None; 1135 1136 assert(I->getType()->isVectorTy() && "Expecting a vector type"); 1137 1138 Optional<TTI::ReductionData> RD = getReductionData(I); 1139 if (!RD) 1140 return TTI::RK_None; 1141 1142 ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS); 1143 if (!LS && Level) 1144 return TTI::RK_None; 1145 ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS); 1146 if (!RS && Level) 1147 return TTI::RK_None; 1148 1149 // On level 0 we can omit one shufflevector instruction. 1150 if (!Level && !RS && !LS) 1151 return TTI::RK_None; 1152 1153 // Shuffle inputs must match. 1154 Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr; 1155 Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr; 1156 Value *NextLevelOp = nullptr; 1157 if (NextLevelOpR && NextLevelOpL) { 1158 // If we have two shuffles their operands must match. 1159 if (NextLevelOpL != NextLevelOpR) 1160 return TTI::RK_None; 1161 1162 NextLevelOp = NextLevelOpL; 1163 } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) { 1164 // On the first level we can omit the shufflevector <0, undef,...>. So the 1165 // input to the other shufflevector <1, undef> must match with one of the 1166 // inputs to the current binary operation. 1167 // Example: 1168 // %NextLevelOpL = shufflevector %R, <1, undef ...> 1169 // %BinOp = fadd %NextLevelOpL, %R 1170 if (NextLevelOpL && NextLevelOpL != RD->RHS) 1171 return TTI::RK_None; 1172 else if (NextLevelOpR && NextLevelOpR != RD->LHS) 1173 return TTI::RK_None; 1174 1175 NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS; 1176 } else 1177 return TTI::RK_None; 1178 1179 // Check that the next levels binary operation exists and matches with the 1180 // current one. 1181 if (Level + 1 != NumLevels) { 1182 if (!isa<Instruction>(NextLevelOp)) 1183 return TTI::RK_None; 1184 Optional<TTI::ReductionData> NextLevelRD = 1185 getReductionData(cast<Instruction>(NextLevelOp)); 1186 if (!NextLevelRD || !RD->hasSameData(*NextLevelRD)) 1187 return TTI::RK_None; 1188 } 1189 1190 // Shuffle mask for pairwise operation must match. 1191 if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) { 1192 if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level)) 1193 return TTI::RK_None; 1194 } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) { 1195 if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level)) 1196 return TTI::RK_None; 1197 } else { 1198 return TTI::RK_None; 1199 } 1200 1201 if (++Level == NumLevels) 1202 return RD->Kind; 1203 1204 // Match next level. 1205 return matchPairwiseReductionAtLevel(dyn_cast<Instruction>(NextLevelOp), Level, 1206 NumLevels); 1207 } 1208 1209 TTI::ReductionKind TTI::matchPairwiseReduction( 1210 const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) { 1211 if (!EnableReduxCost) 1212 return TTI::RK_None; 1213 1214 // Need to extract the first element. 1215 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1)); 1216 unsigned Idx = ~0u; 1217 if (CI) 1218 Idx = CI->getZExtValue(); 1219 if (Idx != 0) 1220 return TTI::RK_None; 1221 1222 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0)); 1223 if (!RdxStart) 1224 return TTI::RK_None; 1225 Optional<TTI::ReductionData> RD = getReductionData(RdxStart); 1226 if (!RD) 1227 return TTI::RK_None; 1228 1229 auto *VecTy = cast<FixedVectorType>(RdxStart->getType()); 1230 unsigned NumVecElems = VecTy->getNumElements(); 1231 if (!isPowerOf2_32(NumVecElems)) 1232 return TTI::RK_None; 1233 1234 // We look for a sequence of shuffle,shuffle,add triples like the following 1235 // that builds a pairwise reduction tree. 1236 // 1237 // (X0, X1, X2, X3) 1238 // (X0 + X1, X2 + X3, undef, undef) 1239 // ((X0 + X1) + (X2 + X3), undef, undef, undef) 1240 // 1241 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, 1242 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> 1243 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, 1244 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> 1245 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 1246 // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, 1247 // <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> 1248 // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, 1249 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> 1250 // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1 1251 // %r = extractelement <4 x float> %bin.rdx8, i32 0 1252 if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) == 1253 TTI::RK_None) 1254 return TTI::RK_None; 1255 1256 Opcode = RD->Opcode; 1257 Ty = VecTy; 1258 1259 return RD->Kind; 1260 } 1261 1262 static std::pair<Value *, ShuffleVectorInst *> 1263 getShuffleAndOtherOprd(Value *L, Value *R) { 1264 ShuffleVectorInst *S = nullptr; 1265 1266 if ((S = dyn_cast<ShuffleVectorInst>(L))) 1267 return std::make_pair(R, S); 1268 1269 S = dyn_cast<ShuffleVectorInst>(R); 1270 return std::make_pair(L, S); 1271 } 1272 1273 TTI::ReductionKind TTI::matchVectorSplittingReduction( 1274 const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) { 1275 1276 if (!EnableReduxCost) 1277 return TTI::RK_None; 1278 1279 // Need to extract the first element. 1280 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1)); 1281 unsigned Idx = ~0u; 1282 if (CI) 1283 Idx = CI->getZExtValue(); 1284 if (Idx != 0) 1285 return TTI::RK_None; 1286 1287 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0)); 1288 if (!RdxStart) 1289 return TTI::RK_None; 1290 Optional<TTI::ReductionData> RD = getReductionData(RdxStart); 1291 if (!RD) 1292 return TTI::RK_None; 1293 1294 auto *VecTy = cast<FixedVectorType>(ReduxRoot->getOperand(0)->getType()); 1295 unsigned NumVecElems = VecTy->getNumElements(); 1296 if (!isPowerOf2_32(NumVecElems)) 1297 return TTI::RK_None; 1298 1299 // We look for a sequence of shuffles and adds like the following matching one 1300 // fadd, shuffle vector pair at a time. 1301 // 1302 // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef, 1303 // <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> 1304 // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf 1305 // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef, 1306 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> 1307 // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7 1308 // %r = extractelement <4 x float> %bin.rdx8, i32 0 1309 1310 unsigned MaskStart = 1; 1311 Instruction *RdxOp = RdxStart; 1312 SmallVector<int, 32> ShuffleMask(NumVecElems, 0); 1313 unsigned NumVecElemsRemain = NumVecElems; 1314 while (NumVecElemsRemain - 1) { 1315 // Check for the right reduction operation. 1316 if (!RdxOp) 1317 return TTI::RK_None; 1318 Optional<TTI::ReductionData> RDLevel = getReductionData(RdxOp); 1319 if (!RDLevel || !RDLevel->hasSameData(*RD)) 1320 return TTI::RK_None; 1321 1322 Value *NextRdxOp; 1323 ShuffleVectorInst *Shuffle; 1324 std::tie(NextRdxOp, Shuffle) = 1325 getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS); 1326 1327 // Check the current reduction operation and the shuffle use the same value. 1328 if (Shuffle == nullptr) 1329 return TTI::RK_None; 1330 if (Shuffle->getOperand(0) != NextRdxOp) 1331 return TTI::RK_None; 1332 1333 // Check that shuffle masks matches. 1334 for (unsigned j = 0; j != MaskStart; ++j) 1335 ShuffleMask[j] = MaskStart + j; 1336 // Fill the rest of the mask with -1 for undef. 1337 std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1); 1338 1339 ArrayRef<int> Mask = Shuffle->getShuffleMask(); 1340 if (ShuffleMask != Mask) 1341 return TTI::RK_None; 1342 1343 RdxOp = dyn_cast<Instruction>(NextRdxOp); 1344 NumVecElemsRemain /= 2; 1345 MaskStart *= 2; 1346 } 1347 1348 Opcode = RD->Opcode; 1349 Ty = VecTy; 1350 return RD->Kind; 1351 } 1352 1353 TTI::ReductionKind 1354 TTI::matchVectorReduction(const ExtractElementInst *Root, unsigned &Opcode, 1355 VectorType *&Ty, bool &IsPairwise) { 1356 TTI::ReductionKind RdxKind = matchVectorSplittingReduction(Root, Opcode, Ty); 1357 if (RdxKind != TTI::ReductionKind::RK_None) { 1358 IsPairwise = false; 1359 return RdxKind; 1360 } 1361 IsPairwise = true; 1362 return matchPairwiseReduction(Root, Opcode, Ty); 1363 } 1364 1365 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const { 1366 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 1367 1368 switch (I->getOpcode()) { 1369 case Instruction::GetElementPtr: 1370 case Instruction::Ret: 1371 case Instruction::PHI: 1372 case Instruction::Br: 1373 case Instruction::Add: 1374 case Instruction::FAdd: 1375 case Instruction::Sub: 1376 case Instruction::FSub: 1377 case Instruction::Mul: 1378 case Instruction::FMul: 1379 case Instruction::UDiv: 1380 case Instruction::SDiv: 1381 case Instruction::FDiv: 1382 case Instruction::URem: 1383 case Instruction::SRem: 1384 case Instruction::FRem: 1385 case Instruction::Shl: 1386 case Instruction::LShr: 1387 case Instruction::AShr: 1388 case Instruction::And: 1389 case Instruction::Or: 1390 case Instruction::Xor: 1391 case Instruction::FNeg: 1392 case Instruction::Select: 1393 case Instruction::ICmp: 1394 case Instruction::FCmp: 1395 case Instruction::Store: 1396 case Instruction::Load: 1397 case Instruction::ZExt: 1398 case Instruction::SExt: 1399 case Instruction::FPToUI: 1400 case Instruction::FPToSI: 1401 case Instruction::FPExt: 1402 case Instruction::PtrToInt: 1403 case Instruction::IntToPtr: 1404 case Instruction::SIToFP: 1405 case Instruction::UIToFP: 1406 case Instruction::Trunc: 1407 case Instruction::FPTrunc: 1408 case Instruction::BitCast: 1409 case Instruction::AddrSpaceCast: 1410 case Instruction::ExtractElement: 1411 case Instruction::InsertElement: 1412 case Instruction::ExtractValue: 1413 case Instruction::ShuffleVector: 1414 case Instruction::Call: 1415 return getUserCost(I, CostKind); 1416 default: 1417 // We don't have any information on this instruction. 1418 return -1; 1419 } 1420 } 1421 1422 TargetTransformInfo::Concept::~Concept() {} 1423 1424 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {} 1425 1426 TargetIRAnalysis::TargetIRAnalysis( 1427 std::function<Result(const Function &)> TTICallback) 1428 : TTICallback(std::move(TTICallback)) {} 1429 1430 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F, 1431 FunctionAnalysisManager &) { 1432 return TTICallback(F); 1433 } 1434 1435 AnalysisKey TargetIRAnalysis::Key; 1436 1437 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) { 1438 return Result(F.getParent()->getDataLayout()); 1439 } 1440 1441 // Register the basic pass. 1442 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti", 1443 "Target Transform Information", false, true) 1444 char TargetTransformInfoWrapperPass::ID = 0; 1445 1446 void TargetTransformInfoWrapperPass::anchor() {} 1447 1448 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass() 1449 : ImmutablePass(ID) { 1450 initializeTargetTransformInfoWrapperPassPass( 1451 *PassRegistry::getPassRegistry()); 1452 } 1453 1454 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass( 1455 TargetIRAnalysis TIRA) 1456 : ImmutablePass(ID), TIRA(std::move(TIRA)) { 1457 initializeTargetTransformInfoWrapperPassPass( 1458 *PassRegistry::getPassRegistry()); 1459 } 1460 1461 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) { 1462 FunctionAnalysisManager DummyFAM; 1463 TTI = TIRA.run(F, DummyFAM); 1464 return *TTI; 1465 } 1466 1467 ImmutablePass * 1468 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) { 1469 return new TargetTransformInfoWrapperPass(std::move(TIRA)); 1470 } 1471