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