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