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