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