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 bool TargetTransformInfo::emitGetActiveLaneMask(Loop *L, LoopInfo *LI, 316 ScalarEvolution &SE, bool TailFolded) const { 317 return TTIImpl->emitGetActiveLaneMask(L, LI, SE, TailFolded); 318 } 319 320 void TargetTransformInfo::getUnrollingPreferences( 321 Loop *L, ScalarEvolution &SE, UnrollingPreferences &UP) const { 322 return TTIImpl->getUnrollingPreferences(L, SE, UP); 323 } 324 325 bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm) const { 326 return TTIImpl->isLegalAddImmediate(Imm); 327 } 328 329 bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm) const { 330 return TTIImpl->isLegalICmpImmediate(Imm); 331 } 332 333 bool TargetTransformInfo::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, 334 int64_t BaseOffset, 335 bool HasBaseReg, int64_t Scale, 336 unsigned AddrSpace, 337 Instruction *I) const { 338 return TTIImpl->isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg, 339 Scale, AddrSpace, I); 340 } 341 342 bool TargetTransformInfo::isLSRCostLess(LSRCost &C1, LSRCost &C2) const { 343 return TTIImpl->isLSRCostLess(C1, C2); 344 } 345 346 bool TargetTransformInfo::isProfitableLSRChainElement(Instruction *I) const { 347 return TTIImpl->isProfitableLSRChainElement(I); 348 } 349 350 bool TargetTransformInfo::canMacroFuseCmp() const { 351 return TTIImpl->canMacroFuseCmp(); 352 } 353 354 bool TargetTransformInfo::canSaveCmp(Loop *L, BranchInst **BI, 355 ScalarEvolution *SE, LoopInfo *LI, 356 DominatorTree *DT, AssumptionCache *AC, 357 TargetLibraryInfo *LibInfo) const { 358 return TTIImpl->canSaveCmp(L, BI, SE, LI, DT, AC, LibInfo); 359 } 360 361 bool TargetTransformInfo::shouldFavorPostInc() const { 362 return TTIImpl->shouldFavorPostInc(); 363 } 364 365 bool TargetTransformInfo::shouldFavorBackedgeIndex(const Loop *L) const { 366 return TTIImpl->shouldFavorBackedgeIndex(L); 367 } 368 369 bool TargetTransformInfo::isLegalMaskedStore(Type *DataType, 370 Align Alignment) const { 371 return TTIImpl->isLegalMaskedStore(DataType, Alignment); 372 } 373 374 bool TargetTransformInfo::isLegalMaskedLoad(Type *DataType, 375 Align Alignment) const { 376 return TTIImpl->isLegalMaskedLoad(DataType, Alignment); 377 } 378 379 bool TargetTransformInfo::isLegalNTStore(Type *DataType, 380 Align Alignment) const { 381 return TTIImpl->isLegalNTStore(DataType, Alignment); 382 } 383 384 bool TargetTransformInfo::isLegalNTLoad(Type *DataType, Align Alignment) const { 385 return TTIImpl->isLegalNTLoad(DataType, Alignment); 386 } 387 388 bool TargetTransformInfo::isLegalMaskedGather(Type *DataType, 389 Align Alignment) const { 390 return TTIImpl->isLegalMaskedGather(DataType, Alignment); 391 } 392 393 bool TargetTransformInfo::isLegalMaskedScatter(Type *DataType, 394 Align Alignment) const { 395 return TTIImpl->isLegalMaskedScatter(DataType, Alignment); 396 } 397 398 bool TargetTransformInfo::isLegalMaskedCompressStore(Type *DataType) const { 399 return TTIImpl->isLegalMaskedCompressStore(DataType); 400 } 401 402 bool TargetTransformInfo::isLegalMaskedExpandLoad(Type *DataType) const { 403 return TTIImpl->isLegalMaskedExpandLoad(DataType); 404 } 405 406 bool TargetTransformInfo::hasDivRemOp(Type *DataType, bool IsSigned) const { 407 return TTIImpl->hasDivRemOp(DataType, IsSigned); 408 } 409 410 bool TargetTransformInfo::hasVolatileVariant(Instruction *I, 411 unsigned AddrSpace) const { 412 return TTIImpl->hasVolatileVariant(I, AddrSpace); 413 } 414 415 bool TargetTransformInfo::prefersVectorizedAddressing() const { 416 return TTIImpl->prefersVectorizedAddressing(); 417 } 418 419 int TargetTransformInfo::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, 420 int64_t BaseOffset, 421 bool HasBaseReg, int64_t Scale, 422 unsigned AddrSpace) const { 423 int Cost = TTIImpl->getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, 424 Scale, AddrSpace); 425 assert(Cost >= 0 && "TTI should not produce negative costs!"); 426 return Cost; 427 } 428 429 bool TargetTransformInfo::LSRWithInstrQueries() const { 430 return TTIImpl->LSRWithInstrQueries(); 431 } 432 433 bool TargetTransformInfo::isTruncateFree(Type *Ty1, Type *Ty2) const { 434 return TTIImpl->isTruncateFree(Ty1, Ty2); 435 } 436 437 bool TargetTransformInfo::isProfitableToHoist(Instruction *I) const { 438 return TTIImpl->isProfitableToHoist(I); 439 } 440 441 bool TargetTransformInfo::useAA() const { return TTIImpl->useAA(); } 442 443 bool TargetTransformInfo::isTypeLegal(Type *Ty) const { 444 return TTIImpl->isTypeLegal(Ty); 445 } 446 447 bool TargetTransformInfo::shouldBuildLookupTables() const { 448 return TTIImpl->shouldBuildLookupTables(); 449 } 450 bool TargetTransformInfo::shouldBuildLookupTablesForConstant( 451 Constant *C) const { 452 return TTIImpl->shouldBuildLookupTablesForConstant(C); 453 } 454 455 bool TargetTransformInfo::useColdCCForColdCall(Function &F) const { 456 return TTIImpl->useColdCCForColdCall(F); 457 } 458 459 unsigned 460 TargetTransformInfo::getScalarizationOverhead(VectorType *Ty, 461 const APInt &DemandedElts, 462 bool Insert, bool Extract) const { 463 return TTIImpl->getScalarizationOverhead(Ty, DemandedElts, Insert, Extract); 464 } 465 466 unsigned TargetTransformInfo::getOperandsScalarizationOverhead( 467 ArrayRef<const Value *> Args, unsigned VF) const { 468 return TTIImpl->getOperandsScalarizationOverhead(Args, VF); 469 } 470 471 bool TargetTransformInfo::supportsEfficientVectorElementLoadStore() const { 472 return TTIImpl->supportsEfficientVectorElementLoadStore(); 473 } 474 475 bool TargetTransformInfo::enableAggressiveInterleaving( 476 bool LoopHasReductions) const { 477 return TTIImpl->enableAggressiveInterleaving(LoopHasReductions); 478 } 479 480 TargetTransformInfo::MemCmpExpansionOptions 481 TargetTransformInfo::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const { 482 return TTIImpl->enableMemCmpExpansion(OptSize, IsZeroCmp); 483 } 484 485 bool TargetTransformInfo::enableInterleavedAccessVectorization() const { 486 return TTIImpl->enableInterleavedAccessVectorization(); 487 } 488 489 bool TargetTransformInfo::enableMaskedInterleavedAccessVectorization() const { 490 return TTIImpl->enableMaskedInterleavedAccessVectorization(); 491 } 492 493 bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const { 494 return TTIImpl->isFPVectorizationPotentiallyUnsafe(); 495 } 496 497 bool TargetTransformInfo::allowsMisalignedMemoryAccesses(LLVMContext &Context, 498 unsigned BitWidth, 499 unsigned AddressSpace, 500 unsigned Alignment, 501 bool *Fast) const { 502 return TTIImpl->allowsMisalignedMemoryAccesses(Context, BitWidth, 503 AddressSpace, Alignment, Fast); 504 } 505 506 TargetTransformInfo::PopcntSupportKind 507 TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit) const { 508 return TTIImpl->getPopcntSupport(IntTyWidthInBit); 509 } 510 511 bool TargetTransformInfo::haveFastSqrt(Type *Ty) const { 512 return TTIImpl->haveFastSqrt(Ty); 513 } 514 515 bool TargetTransformInfo::isFCmpOrdCheaperThanFCmpZero(Type *Ty) const { 516 return TTIImpl->isFCmpOrdCheaperThanFCmpZero(Ty); 517 } 518 519 int TargetTransformInfo::getFPOpCost(Type *Ty) const { 520 int Cost = TTIImpl->getFPOpCost(Ty); 521 assert(Cost >= 0 && "TTI should not produce negative costs!"); 522 return Cost; 523 } 524 525 int TargetTransformInfo::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, 526 const APInt &Imm, 527 Type *Ty) const { 528 int Cost = TTIImpl->getIntImmCodeSizeCost(Opcode, Idx, Imm, Ty); 529 assert(Cost >= 0 && "TTI should not produce negative costs!"); 530 return Cost; 531 } 532 533 int TargetTransformInfo::getIntImmCost(const APInt &Imm, Type *Ty, 534 TTI::TargetCostKind CostKind) const { 535 int Cost = TTIImpl->getIntImmCost(Imm, Ty, CostKind); 536 assert(Cost >= 0 && "TTI should not produce negative costs!"); 537 return Cost; 538 } 539 540 int 541 TargetTransformInfo::getIntImmCostInst(unsigned Opcode, unsigned Idx, 542 const APInt &Imm, Type *Ty, 543 TTI::TargetCostKind CostKind) const { 544 int Cost = TTIImpl->getIntImmCostInst(Opcode, Idx, Imm, Ty, CostKind); 545 assert(Cost >= 0 && "TTI should not produce negative costs!"); 546 return Cost; 547 } 548 549 int 550 TargetTransformInfo::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, 551 const APInt &Imm, Type *Ty, 552 TTI::TargetCostKind CostKind) const { 553 int Cost = TTIImpl->getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind); 554 assert(Cost >= 0 && "TTI should not produce negative costs!"); 555 return Cost; 556 } 557 558 unsigned TargetTransformInfo::getNumberOfRegisters(unsigned ClassID) const { 559 return TTIImpl->getNumberOfRegisters(ClassID); 560 } 561 562 unsigned TargetTransformInfo::getRegisterClassForType(bool Vector, 563 Type *Ty) const { 564 return TTIImpl->getRegisterClassForType(Vector, Ty); 565 } 566 567 const char *TargetTransformInfo::getRegisterClassName(unsigned ClassID) const { 568 return TTIImpl->getRegisterClassName(ClassID); 569 } 570 571 unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector) const { 572 return TTIImpl->getRegisterBitWidth(Vector); 573 } 574 575 unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const { 576 return TTIImpl->getMinVectorRegisterBitWidth(); 577 } 578 579 bool TargetTransformInfo::shouldMaximizeVectorBandwidth(bool OptSize) const { 580 return TTIImpl->shouldMaximizeVectorBandwidth(OptSize); 581 } 582 583 unsigned TargetTransformInfo::getMinimumVF(unsigned ElemWidth) const { 584 return TTIImpl->getMinimumVF(ElemWidth); 585 } 586 587 bool TargetTransformInfo::shouldConsiderAddressTypePromotion( 588 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const { 589 return TTIImpl->shouldConsiderAddressTypePromotion( 590 I, AllowPromotionWithoutCommonHeader); 591 } 592 593 unsigned TargetTransformInfo::getCacheLineSize() const { 594 return TTIImpl->getCacheLineSize(); 595 } 596 597 llvm::Optional<unsigned> 598 TargetTransformInfo::getCacheSize(CacheLevel Level) const { 599 return TTIImpl->getCacheSize(Level); 600 } 601 602 llvm::Optional<unsigned> 603 TargetTransformInfo::getCacheAssociativity(CacheLevel Level) const { 604 return TTIImpl->getCacheAssociativity(Level); 605 } 606 607 unsigned TargetTransformInfo::getPrefetchDistance() const { 608 return TTIImpl->getPrefetchDistance(); 609 } 610 611 unsigned TargetTransformInfo::getMinPrefetchStride( 612 unsigned NumMemAccesses, unsigned NumStridedMemAccesses, 613 unsigned NumPrefetches, bool HasCall) const { 614 return TTIImpl->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses, 615 NumPrefetches, HasCall); 616 } 617 618 unsigned TargetTransformInfo::getMaxPrefetchIterationsAhead() const { 619 return TTIImpl->getMaxPrefetchIterationsAhead(); 620 } 621 622 bool TargetTransformInfo::enableWritePrefetching() const { 623 return TTIImpl->enableWritePrefetching(); 624 } 625 626 unsigned TargetTransformInfo::getMaxInterleaveFactor(unsigned VF) const { 627 return TTIImpl->getMaxInterleaveFactor(VF); 628 } 629 630 TargetTransformInfo::OperandValueKind 631 TargetTransformInfo::getOperandInfo(Value *V, OperandValueProperties &OpProps) { 632 OperandValueKind OpInfo = OK_AnyValue; 633 OpProps = OP_None; 634 635 if (auto *CI = dyn_cast<ConstantInt>(V)) { 636 if (CI->getValue().isPowerOf2()) 637 OpProps = OP_PowerOf2; 638 return OK_UniformConstantValue; 639 } 640 641 // A broadcast shuffle creates a uniform value. 642 // TODO: Add support for non-zero index broadcasts. 643 // TODO: Add support for different source vector width. 644 if (auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V)) 645 if (ShuffleInst->isZeroEltSplat()) 646 OpInfo = OK_UniformValue; 647 648 const Value *Splat = getSplatValue(V); 649 650 // Check for a splat of a constant or for a non uniform vector of constants 651 // and check if the constant(s) are all powers of two. 652 if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) { 653 OpInfo = OK_NonUniformConstantValue; 654 if (Splat) { 655 OpInfo = OK_UniformConstantValue; 656 if (auto *CI = dyn_cast<ConstantInt>(Splat)) 657 if (CI->getValue().isPowerOf2()) 658 OpProps = OP_PowerOf2; 659 } else if (auto *CDS = dyn_cast<ConstantDataSequential>(V)) { 660 OpProps = OP_PowerOf2; 661 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) { 662 if (auto *CI = dyn_cast<ConstantInt>(CDS->getElementAsConstant(I))) 663 if (CI->getValue().isPowerOf2()) 664 continue; 665 OpProps = OP_None; 666 break; 667 } 668 } 669 } 670 671 // Check for a splat of a uniform value. This is not loop aware, so return 672 // true only for the obviously uniform cases (argument, globalvalue) 673 if (Splat && (isa<Argument>(Splat) || isa<GlobalValue>(Splat))) 674 OpInfo = OK_UniformValue; 675 676 return OpInfo; 677 } 678 679 int TargetTransformInfo::getArithmeticInstrCost( 680 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, 681 OperandValueKind Opd1Info, 682 OperandValueKind Opd2Info, OperandValueProperties Opd1PropInfo, 683 OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args, 684 const Instruction *CxtI) const { 685 int Cost = TTIImpl->getArithmeticInstrCost( 686 Opcode, Ty, CostKind, Opd1Info, Opd2Info, Opd1PropInfo, Opd2PropInfo, 687 Args, CxtI); 688 assert(Cost >= 0 && "TTI should not produce negative costs!"); 689 return Cost; 690 } 691 692 int TargetTransformInfo::getShuffleCost(ShuffleKind Kind, VectorType *Ty, 693 int Index, VectorType *SubTp) const { 694 int Cost = TTIImpl->getShuffleCost(Kind, Ty, Index, SubTp); 695 assert(Cost >= 0 && "TTI should not produce negative costs!"); 696 return Cost; 697 } 698 699 int TargetTransformInfo::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, 700 TTI::TargetCostKind CostKind, 701 const Instruction *I) const { 702 assert((I == nullptr || I->getOpcode() == Opcode) && 703 "Opcode should reflect passed instruction."); 704 int Cost = TTIImpl->getCastInstrCost(Opcode, Dst, Src, CostKind, I); 705 assert(Cost >= 0 && "TTI should not produce negative costs!"); 706 return Cost; 707 } 708 709 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode, Type *Dst, 710 VectorType *VecTy, 711 unsigned Index) const { 712 int Cost = TTIImpl->getExtractWithExtendCost(Opcode, Dst, VecTy, Index); 713 assert(Cost >= 0 && "TTI should not produce negative costs!"); 714 return Cost; 715 } 716 717 int TargetTransformInfo::getCFInstrCost(unsigned Opcode, 718 TTI::TargetCostKind CostKind) const { 719 int Cost = TTIImpl->getCFInstrCost(Opcode, CostKind); 720 assert(Cost >= 0 && "TTI should not produce negative costs!"); 721 return Cost; 722 } 723 724 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, 725 Type *CondTy, 726 TTI::TargetCostKind CostKind, 727 const Instruction *I) const { 728 assert((I == nullptr || I->getOpcode() == Opcode) && 729 "Opcode should reflect passed instruction."); 730 int Cost = TTIImpl->getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I); 731 assert(Cost >= 0 && "TTI should not produce negative costs!"); 732 return Cost; 733 } 734 735 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val, 736 unsigned Index) const { 737 int Cost = TTIImpl->getVectorInstrCost(Opcode, Val, Index); 738 assert(Cost >= 0 && "TTI should not produce negative costs!"); 739 return Cost; 740 } 741 742 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src, 743 Align Alignment, unsigned AddressSpace, 744 TTI::TargetCostKind CostKind, 745 const Instruction *I) const { 746 assert((I == nullptr || I->getOpcode() == Opcode) && 747 "Opcode should reflect passed instruction."); 748 int Cost = TTIImpl->getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 749 CostKind, I); 750 assert(Cost >= 0 && "TTI should not produce negative costs!"); 751 return Cost; 752 } 753 754 int TargetTransformInfo::getMaskedMemoryOpCost(unsigned Opcode, Type *Src, 755 unsigned Alignment, 756 unsigned AddressSpace, 757 TTI::TargetCostKind CostKind) const { 758 int Cost = 759 TTIImpl->getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 760 CostKind); 761 assert(Cost >= 0 && "TTI should not produce negative costs!"); 762 return Cost; 763 } 764 765 int TargetTransformInfo::getGatherScatterOpCost( 766 unsigned Opcode, Type *DataTy, Value *Ptr, bool VariableMask, 767 unsigned Alignment, TTI::TargetCostKind CostKind, 768 const Instruction *I) const { 769 int Cost = TTIImpl->getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask, 770 Alignment, CostKind, I); 771 assert(Cost >= 0 && "TTI should not produce negative costs!"); 772 return Cost; 773 } 774 775 int TargetTransformInfo::getInterleavedMemoryOpCost( 776 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 777 unsigned Alignment, unsigned AddressSpace, 778 TTI::TargetCostKind CostKind, 779 bool UseMaskForCond, bool UseMaskForGaps) const { 780 int Cost = TTIImpl->getInterleavedMemoryOpCost( 781 Opcode, VecTy, Factor, Indices, Alignment, AddressSpace, CostKind, 782 UseMaskForCond, UseMaskForGaps); 783 assert(Cost >= 0 && "TTI should not produce negative costs!"); 784 return Cost; 785 } 786 787 int 788 TargetTransformInfo::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 789 TTI::TargetCostKind CostKind) const { 790 int Cost = TTIImpl->getIntrinsicInstrCost(ICA, CostKind); 791 assert(Cost >= 0 && "TTI should not produce negative costs!"); 792 return Cost; 793 } 794 795 int TargetTransformInfo::getCallInstrCost(Function *F, Type *RetTy, 796 ArrayRef<Type *> Tys, 797 TTI::TargetCostKind CostKind) const { 798 int Cost = TTIImpl->getCallInstrCost(F, RetTy, Tys, CostKind); 799 assert(Cost >= 0 && "TTI should not produce negative costs!"); 800 return Cost; 801 } 802 803 unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const { 804 return TTIImpl->getNumberOfParts(Tp); 805 } 806 807 int TargetTransformInfo::getAddressComputationCost(Type *Tp, 808 ScalarEvolution *SE, 809 const SCEV *Ptr) const { 810 int Cost = TTIImpl->getAddressComputationCost(Tp, SE, Ptr); 811 assert(Cost >= 0 && "TTI should not produce negative costs!"); 812 return Cost; 813 } 814 815 int TargetTransformInfo::getMemcpyCost(const Instruction *I) const { 816 int Cost = TTIImpl->getMemcpyCost(I); 817 assert(Cost >= 0 && "TTI should not produce negative costs!"); 818 return Cost; 819 } 820 821 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode, 822 VectorType *Ty, 823 bool IsPairwiseForm, 824 TTI::TargetCostKind CostKind) const { 825 int Cost = TTIImpl->getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm, 826 CostKind); 827 assert(Cost >= 0 && "TTI should not produce negative costs!"); 828 return Cost; 829 } 830 831 int TargetTransformInfo::getMinMaxReductionCost( 832 VectorType *Ty, VectorType *CondTy, bool IsPairwiseForm, bool IsUnsigned, 833 TTI::TargetCostKind CostKind) const { 834 int Cost = 835 TTIImpl->getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned, 836 CostKind); 837 assert(Cost >= 0 && "TTI should not produce negative costs!"); 838 return Cost; 839 } 840 841 unsigned 842 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const { 843 return TTIImpl->getCostOfKeepingLiveOverCall(Tys); 844 } 845 846 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst, 847 MemIntrinsicInfo &Info) const { 848 return TTIImpl->getTgtMemIntrinsic(Inst, Info); 849 } 850 851 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const { 852 return TTIImpl->getAtomicMemIntrinsicMaxElementSize(); 853 } 854 855 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic( 856 IntrinsicInst *Inst, Type *ExpectedType) const { 857 return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType); 858 } 859 860 Type *TargetTransformInfo::getMemcpyLoopLoweringType( 861 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace, 862 unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign) const { 863 return TTIImpl->getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace, 864 DestAddrSpace, SrcAlign, DestAlign); 865 } 866 867 void TargetTransformInfo::getMemcpyLoopResidualLoweringType( 868 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context, 869 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, 870 unsigned SrcAlign, unsigned DestAlign) const { 871 TTIImpl->getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes, 872 SrcAddrSpace, DestAddrSpace, 873 SrcAlign, DestAlign); 874 } 875 876 bool TargetTransformInfo::areInlineCompatible(const Function *Caller, 877 const Function *Callee) const { 878 return TTIImpl->areInlineCompatible(Caller, Callee); 879 } 880 881 bool TargetTransformInfo::areFunctionArgsABICompatible( 882 const Function *Caller, const Function *Callee, 883 SmallPtrSetImpl<Argument *> &Args) const { 884 return TTIImpl->areFunctionArgsABICompatible(Caller, Callee, Args); 885 } 886 887 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode, 888 Type *Ty) const { 889 return TTIImpl->isIndexedLoadLegal(Mode, Ty); 890 } 891 892 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode, 893 Type *Ty) const { 894 return TTIImpl->isIndexedStoreLegal(Mode, Ty); 895 } 896 897 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const { 898 return TTIImpl->getLoadStoreVecRegBitWidth(AS); 899 } 900 901 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const { 902 return TTIImpl->isLegalToVectorizeLoad(LI); 903 } 904 905 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const { 906 return TTIImpl->isLegalToVectorizeStore(SI); 907 } 908 909 bool TargetTransformInfo::isLegalToVectorizeLoadChain( 910 unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const { 911 return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment, 912 AddrSpace); 913 } 914 915 bool TargetTransformInfo::isLegalToVectorizeStoreChain( 916 unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const { 917 return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment, 918 AddrSpace); 919 } 920 921 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF, 922 unsigned LoadSize, 923 unsigned ChainSizeInBytes, 924 VectorType *VecTy) const { 925 return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy); 926 } 927 928 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF, 929 unsigned StoreSize, 930 unsigned ChainSizeInBytes, 931 VectorType *VecTy) const { 932 return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy); 933 } 934 935 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode, Type *Ty, 936 ReductionFlags Flags) const { 937 return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags); 938 } 939 940 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const { 941 return TTIImpl->shouldExpandReduction(II); 942 } 943 944 unsigned TargetTransformInfo::getGISelRematGlobalCost() const { 945 return TTIImpl->getGISelRematGlobalCost(); 946 } 947 948 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const { 949 return TTIImpl->getInstructionLatency(I); 950 } 951 952 static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft, 953 unsigned Level) { 954 // We don't need a shuffle if we just want to have element 0 in position 0 of 955 // the vector. 956 if (!SI && Level == 0 && IsLeft) 957 return true; 958 else if (!SI) 959 return false; 960 961 SmallVector<int, 32> Mask(SI->getType()->getNumElements(), -1); 962 963 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether 964 // we look at the left or right side. 965 for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2) 966 Mask[i] = val; 967 968 ArrayRef<int> ActualMask = SI->getShuffleMask(); 969 return Mask == ActualMask; 970 } 971 972 namespace { 973 /// Kind of the reduction data. 974 enum ReductionKind { 975 RK_None, /// Not a reduction. 976 RK_Arithmetic, /// Binary reduction data. 977 RK_MinMax, /// Min/max reduction data. 978 RK_UnsignedMinMax, /// Unsigned min/max reduction data. 979 }; 980 /// Contains opcode + LHS/RHS parts of the reduction operations. 981 struct ReductionData { 982 ReductionData() = delete; 983 ReductionData(ReductionKind Kind, unsigned Opcode, Value *LHS, Value *RHS) 984 : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind) { 985 assert(Kind != RK_None && "expected binary or min/max reduction only."); 986 } 987 unsigned Opcode = 0; 988 Value *LHS = nullptr; 989 Value *RHS = nullptr; 990 ReductionKind Kind = RK_None; 991 bool hasSameData(ReductionData &RD) const { 992 return Kind == RD.Kind && Opcode == RD.Opcode; 993 } 994 }; 995 } // namespace 996 997 static Optional<ReductionData> getReductionData(Instruction *I) { 998 Value *L, *R; 999 if (m_BinOp(m_Value(L), m_Value(R)).match(I)) 1000 return ReductionData(RK_Arithmetic, I->getOpcode(), L, R); 1001 if (auto *SI = dyn_cast<SelectInst>(I)) { 1002 if (m_SMin(m_Value(L), m_Value(R)).match(SI) || 1003 m_SMax(m_Value(L), m_Value(R)).match(SI) || 1004 m_OrdFMin(m_Value(L), m_Value(R)).match(SI) || 1005 m_OrdFMax(m_Value(L), m_Value(R)).match(SI) || 1006 m_UnordFMin(m_Value(L), m_Value(R)).match(SI) || 1007 m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) { 1008 auto *CI = cast<CmpInst>(SI->getCondition()); 1009 return ReductionData(RK_MinMax, CI->getOpcode(), L, R); 1010 } 1011 if (m_UMin(m_Value(L), m_Value(R)).match(SI) || 1012 m_UMax(m_Value(L), m_Value(R)).match(SI)) { 1013 auto *CI = cast<CmpInst>(SI->getCondition()); 1014 return ReductionData(RK_UnsignedMinMax, CI->getOpcode(), L, R); 1015 } 1016 } 1017 return llvm::None; 1018 } 1019 1020 static ReductionKind matchPairwiseReductionAtLevel(Instruction *I, 1021 unsigned Level, 1022 unsigned NumLevels) { 1023 // Match one level of pairwise operations. 1024 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, 1025 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> 1026 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, 1027 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> 1028 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 1029 if (!I) 1030 return RK_None; 1031 1032 assert(I->getType()->isVectorTy() && "Expecting a vector type"); 1033 1034 Optional<ReductionData> RD = getReductionData(I); 1035 if (!RD) 1036 return RK_None; 1037 1038 ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS); 1039 if (!LS && Level) 1040 return RK_None; 1041 ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS); 1042 if (!RS && Level) 1043 return RK_None; 1044 1045 // On level 0 we can omit one shufflevector instruction. 1046 if (!Level && !RS && !LS) 1047 return RK_None; 1048 1049 // Shuffle inputs must match. 1050 Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr; 1051 Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr; 1052 Value *NextLevelOp = nullptr; 1053 if (NextLevelOpR && NextLevelOpL) { 1054 // If we have two shuffles their operands must match. 1055 if (NextLevelOpL != NextLevelOpR) 1056 return RK_None; 1057 1058 NextLevelOp = NextLevelOpL; 1059 } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) { 1060 // On the first level we can omit the shufflevector <0, undef,...>. So the 1061 // input to the other shufflevector <1, undef> must match with one of the 1062 // inputs to the current binary operation. 1063 // Example: 1064 // %NextLevelOpL = shufflevector %R, <1, undef ...> 1065 // %BinOp = fadd %NextLevelOpL, %R 1066 if (NextLevelOpL && NextLevelOpL != RD->RHS) 1067 return RK_None; 1068 else if (NextLevelOpR && NextLevelOpR != RD->LHS) 1069 return RK_None; 1070 1071 NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS; 1072 } else 1073 return RK_None; 1074 1075 // Check that the next levels binary operation exists and matches with the 1076 // current one. 1077 if (Level + 1 != NumLevels) { 1078 Optional<ReductionData> NextLevelRD = 1079 getReductionData(cast<Instruction>(NextLevelOp)); 1080 if (!NextLevelRD || !RD->hasSameData(*NextLevelRD)) 1081 return RK_None; 1082 } 1083 1084 // Shuffle mask for pairwise operation must match. 1085 if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) { 1086 if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level)) 1087 return RK_None; 1088 } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) { 1089 if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level)) 1090 return RK_None; 1091 } else { 1092 return RK_None; 1093 } 1094 1095 if (++Level == NumLevels) 1096 return RD->Kind; 1097 1098 // Match next level. 1099 return matchPairwiseReductionAtLevel(cast<Instruction>(NextLevelOp), Level, 1100 NumLevels); 1101 } 1102 1103 static ReductionKind matchPairwiseReduction(const ExtractElementInst *ReduxRoot, 1104 unsigned &Opcode, 1105 VectorType *&Ty) { 1106 if (!EnableReduxCost) 1107 return RK_None; 1108 1109 // Need to extract the first element. 1110 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1)); 1111 unsigned Idx = ~0u; 1112 if (CI) 1113 Idx = CI->getZExtValue(); 1114 if (Idx != 0) 1115 return RK_None; 1116 1117 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0)); 1118 if (!RdxStart) 1119 return RK_None; 1120 Optional<ReductionData> RD = getReductionData(RdxStart); 1121 if (!RD) 1122 return RK_None; 1123 1124 auto *VecTy = cast<VectorType>(RdxStart->getType()); 1125 unsigned NumVecElems = VecTy->getNumElements(); 1126 if (!isPowerOf2_32(NumVecElems)) 1127 return RK_None; 1128 1129 // We look for a sequence of shuffle,shuffle,add triples like the following 1130 // that builds a pairwise reduction tree. 1131 // 1132 // (X0, X1, X2, X3) 1133 // (X0 + X1, X2 + X3, undef, undef) 1134 // ((X0 + X1) + (X2 + X3), undef, undef, undef) 1135 // 1136 // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef, 1137 // <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef> 1138 // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef, 1139 // <4 x i32> <i32 1, i32 3, i32 undef, i32 undef> 1140 // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1 1141 // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, 1142 // <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef> 1143 // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef, 1144 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> 1145 // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1 1146 // %r = extractelement <4 x float> %bin.rdx8, i32 0 1147 if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) == 1148 RK_None) 1149 return RK_None; 1150 1151 Opcode = RD->Opcode; 1152 Ty = VecTy; 1153 1154 return RD->Kind; 1155 } 1156 1157 static std::pair<Value *, ShuffleVectorInst *> 1158 getShuffleAndOtherOprd(Value *L, Value *R) { 1159 ShuffleVectorInst *S = nullptr; 1160 1161 if ((S = dyn_cast<ShuffleVectorInst>(L))) 1162 return std::make_pair(R, S); 1163 1164 S = dyn_cast<ShuffleVectorInst>(R); 1165 return std::make_pair(L, S); 1166 } 1167 1168 static ReductionKind 1169 matchVectorSplittingReduction(const ExtractElementInst *ReduxRoot, 1170 unsigned &Opcode, VectorType *&Ty) { 1171 if (!EnableReduxCost) 1172 return RK_None; 1173 1174 // Need to extract the first element. 1175 ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1)); 1176 unsigned Idx = ~0u; 1177 if (CI) 1178 Idx = CI->getZExtValue(); 1179 if (Idx != 0) 1180 return RK_None; 1181 1182 auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0)); 1183 if (!RdxStart) 1184 return RK_None; 1185 Optional<ReductionData> RD = getReductionData(RdxStart); 1186 if (!RD) 1187 return RK_None; 1188 1189 auto *VecTy = cast<VectorType>(ReduxRoot->getOperand(0)->getType()); 1190 unsigned NumVecElems = VecTy->getNumElements(); 1191 if (!isPowerOf2_32(NumVecElems)) 1192 return RK_None; 1193 1194 // We look for a sequence of shuffles and adds like the following matching one 1195 // fadd, shuffle vector pair at a time. 1196 // 1197 // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef, 1198 // <4 x i32> <i32 2, i32 3, i32 undef, i32 undef> 1199 // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf 1200 // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef, 1201 // <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef> 1202 // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7 1203 // %r = extractelement <4 x float> %bin.rdx8, i32 0 1204 1205 unsigned MaskStart = 1; 1206 Instruction *RdxOp = RdxStart; 1207 SmallVector<int, 32> ShuffleMask(NumVecElems, 0); 1208 unsigned NumVecElemsRemain = NumVecElems; 1209 while (NumVecElemsRemain - 1) { 1210 // Check for the right reduction operation. 1211 if (!RdxOp) 1212 return RK_None; 1213 Optional<ReductionData> RDLevel = getReductionData(RdxOp); 1214 if (!RDLevel || !RDLevel->hasSameData(*RD)) 1215 return RK_None; 1216 1217 Value *NextRdxOp; 1218 ShuffleVectorInst *Shuffle; 1219 std::tie(NextRdxOp, Shuffle) = 1220 getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS); 1221 1222 // Check the current reduction operation and the shuffle use the same value. 1223 if (Shuffle == nullptr) 1224 return RK_None; 1225 if (Shuffle->getOperand(0) != NextRdxOp) 1226 return RK_None; 1227 1228 // Check that shuffle masks matches. 1229 for (unsigned j = 0; j != MaskStart; ++j) 1230 ShuffleMask[j] = MaskStart + j; 1231 // Fill the rest of the mask with -1 for undef. 1232 std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1); 1233 1234 ArrayRef<int> Mask = Shuffle->getShuffleMask(); 1235 if (ShuffleMask != Mask) 1236 return RK_None; 1237 1238 RdxOp = dyn_cast<Instruction>(NextRdxOp); 1239 NumVecElemsRemain /= 2; 1240 MaskStart *= 2; 1241 } 1242 1243 Opcode = RD->Opcode; 1244 Ty = VecTy; 1245 return RD->Kind; 1246 } 1247 1248 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const { 1249 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 1250 1251 switch (I->getOpcode()) { 1252 case Instruction::GetElementPtr: 1253 return getUserCost(I, CostKind); 1254 1255 case Instruction::Ret: 1256 case Instruction::PHI: 1257 case Instruction::Br: { 1258 return getCFInstrCost(I->getOpcode(), CostKind); 1259 } 1260 case Instruction::Add: 1261 case Instruction::FAdd: 1262 case Instruction::Sub: 1263 case Instruction::FSub: 1264 case Instruction::Mul: 1265 case Instruction::FMul: 1266 case Instruction::UDiv: 1267 case Instruction::SDiv: 1268 case Instruction::FDiv: 1269 case Instruction::URem: 1270 case Instruction::SRem: 1271 case Instruction::FRem: 1272 case Instruction::Shl: 1273 case Instruction::LShr: 1274 case Instruction::AShr: 1275 case Instruction::And: 1276 case Instruction::Or: 1277 case Instruction::Xor: { 1278 TargetTransformInfo::OperandValueKind Op1VK, Op2VK; 1279 TargetTransformInfo::OperandValueProperties Op1VP, Op2VP; 1280 Op1VK = getOperandInfo(I->getOperand(0), Op1VP); 1281 Op2VK = getOperandInfo(I->getOperand(1), Op2VP); 1282 SmallVector<const Value *, 2> Operands(I->operand_values()); 1283 return getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind, 1284 Op1VK, Op2VK, 1285 Op1VP, Op2VP, Operands, I); 1286 } 1287 case Instruction::FNeg: { 1288 TargetTransformInfo::OperandValueKind Op1VK, Op2VK; 1289 TargetTransformInfo::OperandValueProperties Op1VP, Op2VP; 1290 Op1VK = getOperandInfo(I->getOperand(0), Op1VP); 1291 Op2VK = OK_AnyValue; 1292 Op2VP = OP_None; 1293 SmallVector<const Value *, 2> Operands(I->operand_values()); 1294 return getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind, 1295 Op1VK, Op2VK, 1296 Op1VP, Op2VP, Operands, I); 1297 } 1298 case Instruction::Select: { 1299 const SelectInst *SI = cast<SelectInst>(I); 1300 Type *CondTy = SI->getCondition()->getType(); 1301 return getCmpSelInstrCost(I->getOpcode(), I->getType(), CondTy, 1302 CostKind, I); 1303 } 1304 case Instruction::ICmp: 1305 case Instruction::FCmp: { 1306 Type *ValTy = I->getOperand(0)->getType(); 1307 return getCmpSelInstrCost(I->getOpcode(), ValTy, I->getType(), 1308 CostKind, I); 1309 } 1310 case Instruction::Store: { 1311 const StoreInst *SI = cast<StoreInst>(I); 1312 Type *ValTy = SI->getValueOperand()->getType(); 1313 return getMemoryOpCost(I->getOpcode(), ValTy, SI->getAlign(), 1314 SI->getPointerAddressSpace(), CostKind, I); 1315 } 1316 case Instruction::Load: { 1317 const LoadInst *LI = cast<LoadInst>(I); 1318 return getMemoryOpCost(I->getOpcode(), I->getType(), LI->getAlign(), 1319 LI->getPointerAddressSpace(), CostKind, I); 1320 } 1321 case Instruction::ZExt: 1322 case Instruction::SExt: 1323 case Instruction::FPToUI: 1324 case Instruction::FPToSI: 1325 case Instruction::FPExt: 1326 case Instruction::PtrToInt: 1327 case Instruction::IntToPtr: 1328 case Instruction::SIToFP: 1329 case Instruction::UIToFP: 1330 case Instruction::Trunc: 1331 case Instruction::FPTrunc: 1332 case Instruction::BitCast: 1333 case Instruction::AddrSpaceCast: 1334 return getUserCost(I, CostKind); 1335 case Instruction::ExtractElement: { 1336 const ExtractElementInst *EEI = cast<ExtractElementInst>(I); 1337 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 1338 unsigned Idx = -1; 1339 if (CI) 1340 Idx = CI->getZExtValue(); 1341 1342 // Try to match a reduction sequence (series of shufflevector and vector 1343 // adds followed by a extractelement). 1344 unsigned ReduxOpCode; 1345 VectorType *ReduxType; 1346 1347 switch (matchVectorSplittingReduction(EEI, ReduxOpCode, ReduxType)) { 1348 case RK_Arithmetic: 1349 return getArithmeticReductionCost(ReduxOpCode, ReduxType, 1350 /*IsPairwiseForm=*/false, 1351 CostKind); 1352 case RK_MinMax: 1353 return getMinMaxReductionCost( 1354 ReduxType, cast<VectorType>(CmpInst::makeCmpResultType(ReduxType)), 1355 /*IsPairwiseForm=*/false, /*IsUnsigned=*/false); 1356 case RK_UnsignedMinMax: 1357 return getMinMaxReductionCost( 1358 ReduxType, cast<VectorType>(CmpInst::makeCmpResultType(ReduxType)), 1359 /*IsPairwiseForm=*/false, /*IsUnsigned=*/true); 1360 case RK_None: 1361 break; 1362 } 1363 1364 switch (matchPairwiseReduction(EEI, ReduxOpCode, ReduxType)) { 1365 case RK_Arithmetic: 1366 return getArithmeticReductionCost(ReduxOpCode, ReduxType, 1367 /*IsPairwiseForm=*/true, CostKind); 1368 case RK_MinMax: 1369 return getMinMaxReductionCost( 1370 ReduxType, cast<VectorType>(CmpInst::makeCmpResultType(ReduxType)), 1371 /*IsPairwiseForm=*/true, /*IsUnsigned=*/false); 1372 case RK_UnsignedMinMax: 1373 return getMinMaxReductionCost( 1374 ReduxType, cast<VectorType>(CmpInst::makeCmpResultType(ReduxType)), 1375 /*IsPairwiseForm=*/true, /*IsUnsigned=*/true); 1376 case RK_None: 1377 break; 1378 } 1379 1380 return getVectorInstrCost(I->getOpcode(), EEI->getOperand(0)->getType(), 1381 Idx); 1382 } 1383 case Instruction::InsertElement: { 1384 const InsertElementInst *IE = cast<InsertElementInst>(I); 1385 ConstantInt *CI = dyn_cast<ConstantInt>(IE->getOperand(2)); 1386 unsigned Idx = -1; 1387 if (CI) 1388 Idx = CI->getZExtValue(); 1389 return getVectorInstrCost(I->getOpcode(), IE->getType(), Idx); 1390 } 1391 case Instruction::ExtractValue: 1392 return 0; // Model all ExtractValue nodes as free. 1393 case Instruction::ShuffleVector: { 1394 const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I); 1395 auto *Ty = cast<VectorType>(Shuffle->getType()); 1396 auto *SrcTy = cast<VectorType>(Shuffle->getOperand(0)->getType()); 1397 1398 // TODO: Identify and add costs for insert subvector, etc. 1399 int SubIndex; 1400 if (Shuffle->isExtractSubvectorMask(SubIndex)) 1401 return TTIImpl->getShuffleCost(SK_ExtractSubvector, SrcTy, SubIndex, Ty); 1402 1403 if (Shuffle->changesLength()) 1404 return -1; 1405 1406 if (Shuffle->isIdentity()) 1407 return 0; 1408 1409 if (Shuffle->isReverse()) 1410 return TTIImpl->getShuffleCost(SK_Reverse, Ty, 0, nullptr); 1411 1412 if (Shuffle->isSelect()) 1413 return TTIImpl->getShuffleCost(SK_Select, Ty, 0, nullptr); 1414 1415 if (Shuffle->isTranspose()) 1416 return TTIImpl->getShuffleCost(SK_Transpose, Ty, 0, nullptr); 1417 1418 if (Shuffle->isZeroEltSplat()) 1419 return TTIImpl->getShuffleCost(SK_Broadcast, Ty, 0, nullptr); 1420 1421 if (Shuffle->isSingleSource()) 1422 return TTIImpl->getShuffleCost(SK_PermuteSingleSrc, Ty, 0, nullptr); 1423 1424 return TTIImpl->getShuffleCost(SK_PermuteTwoSrc, Ty, 0, nullptr); 1425 } 1426 case Instruction::Call: 1427 return getUserCost(I, CostKind); 1428 default: 1429 // We don't have any information on this instruction. 1430 return -1; 1431 } 1432 } 1433 1434 TargetTransformInfo::Concept::~Concept() {} 1435 1436 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {} 1437 1438 TargetIRAnalysis::TargetIRAnalysis( 1439 std::function<Result(const Function &)> TTICallback) 1440 : TTICallback(std::move(TTICallback)) {} 1441 1442 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F, 1443 FunctionAnalysisManager &) { 1444 return TTICallback(F); 1445 } 1446 1447 AnalysisKey TargetIRAnalysis::Key; 1448 1449 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) { 1450 return Result(F.getParent()->getDataLayout()); 1451 } 1452 1453 // Register the basic pass. 1454 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti", 1455 "Target Transform Information", false, true) 1456 char TargetTransformInfoWrapperPass::ID = 0; 1457 1458 void TargetTransformInfoWrapperPass::anchor() {} 1459 1460 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass() 1461 : ImmutablePass(ID) { 1462 initializeTargetTransformInfoWrapperPassPass( 1463 *PassRegistry::getPassRegistry()); 1464 } 1465 1466 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass( 1467 TargetIRAnalysis TIRA) 1468 : ImmutablePass(ID), TIRA(std::move(TIRA)) { 1469 initializeTargetTransformInfoWrapperPassPass( 1470 *PassRegistry::getPassRegistry()); 1471 } 1472 1473 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) { 1474 FunctionAnalysisManager DummyFAM; 1475 TTI = TIRA.run(F, DummyFAM); 1476 return *TTI; 1477 } 1478 1479 ImmutablePass * 1480 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) { 1481 return new TargetTransformInfoWrapperPass(std::move(TIRA)); 1482 } 1483