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