1 //===- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI pass -----------===// 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 // \file 10 // This file implements a TargetTransformInfo analysis pass specific to the 11 // AMDGPU target machine. It uses the target's detailed information to provide 12 // more precise answers to certain TTI queries, while letting the target 13 // independent and default TTI implementations handle the rest. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "AMDGPUTargetTransformInfo.h" 18 #include "AMDGPUTargetMachine.h" 19 #include "llvm/Analysis/LoopInfo.h" 20 #include "llvm/Analysis/ValueTracking.h" 21 #include "llvm/IR/IntrinsicsAMDGPU.h" 22 #include "llvm/IR/PatternMatch.h" 23 #include "llvm/Support/KnownBits.h" 24 25 using namespace llvm; 26 27 #define DEBUG_TYPE "AMDGPUtti" 28 29 static cl::opt<unsigned> UnrollThresholdPrivate( 30 "amdgpu-unroll-threshold-private", 31 cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"), 32 cl::init(2700), cl::Hidden); 33 34 static cl::opt<unsigned> UnrollThresholdLocal( 35 "amdgpu-unroll-threshold-local", 36 cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"), 37 cl::init(1000), cl::Hidden); 38 39 static cl::opt<unsigned> UnrollThresholdIf( 40 "amdgpu-unroll-threshold-if", 41 cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"), 42 cl::init(150), cl::Hidden); 43 44 static cl::opt<bool> UnrollRuntimeLocal( 45 "amdgpu-unroll-runtime-local", 46 cl::desc("Allow runtime unroll for AMDGPU if local memory used in a loop"), 47 cl::init(true), cl::Hidden); 48 49 static cl::opt<bool> UseLegacyDA( 50 "amdgpu-use-legacy-divergence-analysis", 51 cl::desc("Enable legacy divergence analysis for AMDGPU"), 52 cl::init(false), cl::Hidden); 53 54 static cl::opt<unsigned> UnrollMaxBlockToAnalyze( 55 "amdgpu-unroll-max-block-to-analyze", 56 cl::desc("Inner loop block size threshold to analyze in unroll for AMDGPU"), 57 cl::init(32), cl::Hidden); 58 59 static cl::opt<unsigned> ArgAllocaCost("amdgpu-inline-arg-alloca-cost", 60 cl::Hidden, cl::init(4000), 61 cl::desc("Cost of alloca argument")); 62 63 // If the amount of scratch memory to eliminate exceeds our ability to allocate 64 // it into registers we gain nothing by aggressively inlining functions for that 65 // heuristic. 66 static cl::opt<unsigned> 67 ArgAllocaCutoff("amdgpu-inline-arg-alloca-cutoff", cl::Hidden, 68 cl::init(256), 69 cl::desc("Maximum alloca size to use for inline cost")); 70 71 // Inliner constraint to achieve reasonable compilation time. 72 static cl::opt<size_t> InlineMaxBB( 73 "amdgpu-inline-max-bb", cl::Hidden, cl::init(1100), 74 cl::desc("Maximum number of BBs allowed in a function after inlining" 75 " (compile time constraint)")); 76 77 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond, 78 unsigned Depth = 0) { 79 const Instruction *I = dyn_cast<Instruction>(Cond); 80 if (!I) 81 return false; 82 83 for (const Value *V : I->operand_values()) { 84 if (!L->contains(I)) 85 continue; 86 if (const PHINode *PHI = dyn_cast<PHINode>(V)) { 87 if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) { 88 return SubLoop->contains(PHI); })) 89 return true; 90 } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1)) 91 return true; 92 } 93 return false; 94 } 95 96 AMDGPUTTIImpl::AMDGPUTTIImpl(const AMDGPUTargetMachine *TM, const Function &F) 97 : BaseT(TM, F.getParent()->getDataLayout()), 98 TargetTriple(TM->getTargetTriple()), 99 ST(static_cast<const GCNSubtarget *>(TM->getSubtargetImpl(F))), 100 TLI(ST->getTargetLowering()) {} 101 102 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 103 TTI::UnrollingPreferences &UP) { 104 const Function &F = *L->getHeader()->getParent(); 105 UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300); 106 UP.MaxCount = std::numeric_limits<unsigned>::max(); 107 UP.Partial = true; 108 109 // TODO: Do we want runtime unrolling? 110 111 // Maximum alloca size than can fit registers. Reserve 16 registers. 112 const unsigned MaxAlloca = (256 - 16) * 4; 113 unsigned ThresholdPrivate = UnrollThresholdPrivate; 114 unsigned ThresholdLocal = UnrollThresholdLocal; 115 116 // If this loop has the amdgpu.loop.unroll.threshold metadata we will use the 117 // provided threshold value as the default for Threshold 118 if (MDNode *LoopUnrollThreshold = 119 findOptionMDForLoop(L, "amdgpu.loop.unroll.threshold")) { 120 if (LoopUnrollThreshold->getNumOperands() == 2) { 121 ConstantInt *MetaThresholdValue = mdconst::extract_or_null<ConstantInt>( 122 LoopUnrollThreshold->getOperand(1)); 123 if (MetaThresholdValue) { 124 // We will also use the supplied value for PartialThreshold for now. 125 // We may introduce additional metadata if it becomes necessary in the 126 // future. 127 UP.Threshold = MetaThresholdValue->getSExtValue(); 128 UP.PartialThreshold = UP.Threshold; 129 ThresholdPrivate = std::min(ThresholdPrivate, UP.Threshold); 130 ThresholdLocal = std::min(ThresholdLocal, UP.Threshold); 131 } 132 } 133 } 134 135 unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal); 136 for (const BasicBlock *BB : L->getBlocks()) { 137 const DataLayout &DL = BB->getModule()->getDataLayout(); 138 unsigned LocalGEPsSeen = 0; 139 140 if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) { 141 return SubLoop->contains(BB); })) 142 continue; // Block belongs to an inner loop. 143 144 for (const Instruction &I : *BB) { 145 // Unroll a loop which contains an "if" statement whose condition 146 // defined by a PHI belonging to the loop. This may help to eliminate 147 // if region and potentially even PHI itself, saving on both divergence 148 // and registers used for the PHI. 149 // Add a small bonus for each of such "if" statements. 150 if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) { 151 if (UP.Threshold < MaxBoost && Br->isConditional()) { 152 BasicBlock *Succ0 = Br->getSuccessor(0); 153 BasicBlock *Succ1 = Br->getSuccessor(1); 154 if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) || 155 (L->contains(Succ1) && L->isLoopExiting(Succ1))) 156 continue; 157 if (dependsOnLocalPhi(L, Br->getCondition())) { 158 UP.Threshold += UnrollThresholdIf; 159 LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold 160 << " for loop:\n" 161 << *L << " due to " << *Br << '\n'); 162 if (UP.Threshold >= MaxBoost) 163 return; 164 } 165 } 166 continue; 167 } 168 169 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I); 170 if (!GEP) 171 continue; 172 173 unsigned AS = GEP->getAddressSpace(); 174 unsigned Threshold = 0; 175 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 176 Threshold = ThresholdPrivate; 177 else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) 178 Threshold = ThresholdLocal; 179 else 180 continue; 181 182 if (UP.Threshold >= Threshold) 183 continue; 184 185 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 186 const Value *Ptr = GEP->getPointerOperand(); 187 const AllocaInst *Alloca = 188 dyn_cast<AllocaInst>(getUnderlyingObject(Ptr)); 189 if (!Alloca || !Alloca->isStaticAlloca()) 190 continue; 191 Type *Ty = Alloca->getAllocatedType(); 192 unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0; 193 if (AllocaSize > MaxAlloca) 194 continue; 195 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 196 AS == AMDGPUAS::REGION_ADDRESS) { 197 LocalGEPsSeen++; 198 // Inhibit unroll for local memory if we have seen addressing not to 199 // a variable, most likely we will be unable to combine it. 200 // Do not unroll too deep inner loops for local memory to give a chance 201 // to unroll an outer loop for a more important reason. 202 if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 || 203 (!isa<GlobalVariable>(GEP->getPointerOperand()) && 204 !isa<Argument>(GEP->getPointerOperand()))) 205 continue; 206 LLVM_DEBUG(dbgs() << "Allow unroll runtime for loop:\n" 207 << *L << " due to LDS use.\n"); 208 UP.Runtime = UnrollRuntimeLocal; 209 } 210 211 // Check if GEP depends on a value defined by this loop itself. 212 bool HasLoopDef = false; 213 for (const Value *Op : GEP->operands()) { 214 const Instruction *Inst = dyn_cast<Instruction>(Op); 215 if (!Inst || L->isLoopInvariant(Op)) 216 continue; 217 218 if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) { 219 return SubLoop->contains(Inst); })) 220 continue; 221 HasLoopDef = true; 222 break; 223 } 224 if (!HasLoopDef) 225 continue; 226 227 // We want to do whatever we can to limit the number of alloca 228 // instructions that make it through to the code generator. allocas 229 // require us to use indirect addressing, which is slow and prone to 230 // compiler bugs. If this loop does an address calculation on an 231 // alloca ptr, then we want to use a higher than normal loop unroll 232 // threshold. This will give SROA a better chance to eliminate these 233 // allocas. 234 // 235 // We also want to have more unrolling for local memory to let ds 236 // instructions with different offsets combine. 237 // 238 // Don't use the maximum allowed value here as it will make some 239 // programs way too big. 240 UP.Threshold = Threshold; 241 LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold 242 << " for loop:\n" 243 << *L << " due to " << *GEP << '\n'); 244 if (UP.Threshold >= MaxBoost) 245 return; 246 } 247 248 // If we got a GEP in a small BB from inner loop then increase max trip 249 // count to analyze for better estimation cost in unroll 250 if (L->isInnermost() && BB->size() < UnrollMaxBlockToAnalyze) 251 UP.MaxIterationsCountToAnalyze = 32; 252 } 253 } 254 255 void AMDGPUTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 256 TTI::PeelingPreferences &PP) { 257 BaseT::getPeelingPreferences(L, SE, PP); 258 } 259 260 const FeatureBitset GCNTTIImpl::InlineFeatureIgnoreList = { 261 // Codegen control options which don't matter. 262 AMDGPU::FeatureEnableLoadStoreOpt, AMDGPU::FeatureEnableSIScheduler, 263 AMDGPU::FeatureEnableUnsafeDSOffsetFolding, AMDGPU::FeatureFlatForGlobal, 264 AMDGPU::FeaturePromoteAlloca, AMDGPU::FeatureUnalignedScratchAccess, 265 AMDGPU::FeatureUnalignedAccessMode, 266 267 AMDGPU::FeatureAutoWaitcntBeforeBarrier, 268 269 // Property of the kernel/environment which can't actually differ. 270 AMDGPU::FeatureSGPRInitBug, AMDGPU::FeatureXNACK, 271 AMDGPU::FeatureTrapHandler, 272 273 // The default assumption needs to be ecc is enabled, but no directly 274 // exposed operations depend on it, so it can be safely inlined. 275 AMDGPU::FeatureSRAMECC, 276 277 // Perf-tuning features 278 AMDGPU::FeatureFastFMAF32, AMDGPU::HalfRate64Ops}; 279 280 GCNTTIImpl::GCNTTIImpl(const AMDGPUTargetMachine *TM, const Function &F) 281 : BaseT(TM, F.getParent()->getDataLayout()), 282 ST(static_cast<const GCNSubtarget *>(TM->getSubtargetImpl(F))), 283 TLI(ST->getTargetLowering()), CommonTTI(TM, F), 284 IsGraphics(AMDGPU::isGraphics(F.getCallingConv())), 285 MaxVGPRs(ST->getMaxNumVGPRs( 286 std::max(ST->getWavesPerEU(F).first, 287 ST->getWavesPerEUForWorkGroup( 288 ST->getFlatWorkGroupSizes(F).second)))) { 289 AMDGPU::SIModeRegisterDefaults Mode(F); 290 HasFP32Denormals = Mode.allFP32Denormals(); 291 HasFP64FP16Denormals = Mode.allFP64FP16Denormals(); 292 } 293 294 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 295 // The concept of vector registers doesn't really exist. Some packed vector 296 // operations operate on the normal 32-bit registers. 297 return MaxVGPRs; 298 } 299 300 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const { 301 // This is really the number of registers to fill when vectorizing / 302 // interleaving loops, so we lie to avoid trying to use all registers. 303 return getHardwareNumberOfRegisters(Vec) >> 3; 304 } 305 306 unsigned GCNTTIImpl::getNumberOfRegisters(unsigned RCID) const { 307 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 308 const TargetRegisterClass *RC = TRI->getRegClass(RCID); 309 unsigned NumVGPRs = (TRI->getRegSizeInBits(*RC) + 31) / 32; 310 return getHardwareNumberOfRegisters(false) / NumVGPRs; 311 } 312 313 unsigned GCNTTIImpl::getRegisterBitWidth(bool Vector) const { 314 return (Vector && ST->hasPackedFP32Ops()) ? 64 : 32; 315 } 316 317 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const { 318 return 32; 319 } 320 321 unsigned GCNTTIImpl::getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 322 if (Opcode == Instruction::Load || Opcode == Instruction::Store) 323 return 32 * 4 / ElemWidth; 324 return (ElemWidth == 16 && ST->has16BitInsts()) ? 2 325 : (ElemWidth == 32 && ST->hasPackedFP32Ops()) ? 2 326 : 1; 327 } 328 329 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize, 330 unsigned ChainSizeInBytes, 331 VectorType *VecTy) const { 332 unsigned VecRegBitWidth = VF * LoadSize; 333 if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32) 334 // TODO: Support element-size less than 32bit? 335 return 128 / LoadSize; 336 337 return VF; 338 } 339 340 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize, 341 unsigned ChainSizeInBytes, 342 VectorType *VecTy) const { 343 unsigned VecRegBitWidth = VF * StoreSize; 344 if (VecRegBitWidth > 128) 345 return 128 / StoreSize; 346 347 return VF; 348 } 349 350 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 351 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 352 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 353 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 354 AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) { 355 return 512; 356 } 357 358 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 359 return 8 * ST->getMaxPrivateElementSize(); 360 361 // Common to flat, global, local and region. Assume for unknown addrspace. 362 return 128; 363 } 364 365 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 366 Align Alignment, 367 unsigned AddrSpace) const { 368 // We allow vectorization of flat stores, even though we may need to decompose 369 // them later if they may access private memory. We don't have enough context 370 // here, and legalization can handle it. 371 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 372 return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) && 373 ChainSizeInBytes <= ST->getMaxPrivateElementSize(); 374 } 375 return true; 376 } 377 378 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 379 Align Alignment, 380 unsigned AddrSpace) const { 381 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 382 } 383 384 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 385 Align Alignment, 386 unsigned AddrSpace) const { 387 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 388 } 389 390 // FIXME: Really we would like to issue multiple 128-bit loads and stores per 391 // iteration. Should we report a larger size and let it legalize? 392 // 393 // FIXME: Should we use narrower types for local/region, or account for when 394 // unaligned access is legal? 395 // 396 // FIXME: This could use fine tuning and microbenchmarks. 397 Type *GCNTTIImpl::getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, 398 unsigned SrcAddrSpace, 399 unsigned DestAddrSpace, 400 unsigned SrcAlign, 401 unsigned DestAlign) const { 402 unsigned MinAlign = std::min(SrcAlign, DestAlign); 403 404 // A (multi-)dword access at an address == 2 (mod 4) will be decomposed by the 405 // hardware into byte accesses. If you assume all alignments are equally 406 // probable, it's more efficient on average to use short accesses for this 407 // case. 408 if (MinAlign == 2) 409 return Type::getInt16Ty(Context); 410 411 // Not all subtargets have 128-bit DS instructions, and we currently don't 412 // form them by default. 413 if (SrcAddrSpace == AMDGPUAS::LOCAL_ADDRESS || 414 SrcAddrSpace == AMDGPUAS::REGION_ADDRESS || 415 DestAddrSpace == AMDGPUAS::LOCAL_ADDRESS || 416 DestAddrSpace == AMDGPUAS::REGION_ADDRESS) { 417 return FixedVectorType::get(Type::getInt32Ty(Context), 2); 418 } 419 420 // Global memory works best with 16-byte accesses. Private memory will also 421 // hit this, although they'll be decomposed. 422 return FixedVectorType::get(Type::getInt32Ty(Context), 4); 423 } 424 425 void GCNTTIImpl::getMemcpyLoopResidualLoweringType( 426 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context, 427 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, 428 unsigned SrcAlign, unsigned DestAlign) const { 429 assert(RemainingBytes < 16); 430 431 unsigned MinAlign = std::min(SrcAlign, DestAlign); 432 433 if (MinAlign != 2) { 434 Type *I64Ty = Type::getInt64Ty(Context); 435 while (RemainingBytes >= 8) { 436 OpsOut.push_back(I64Ty); 437 RemainingBytes -= 8; 438 } 439 440 Type *I32Ty = Type::getInt32Ty(Context); 441 while (RemainingBytes >= 4) { 442 OpsOut.push_back(I32Ty); 443 RemainingBytes -= 4; 444 } 445 } 446 447 Type *I16Ty = Type::getInt16Ty(Context); 448 while (RemainingBytes >= 2) { 449 OpsOut.push_back(I16Ty); 450 RemainingBytes -= 2; 451 } 452 453 Type *I8Ty = Type::getInt8Ty(Context); 454 while (RemainingBytes) { 455 OpsOut.push_back(I8Ty); 456 --RemainingBytes; 457 } 458 } 459 460 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) { 461 // Disable unrolling if the loop is not vectorized. 462 // TODO: Enable this again. 463 if (VF == 1) 464 return 1; 465 466 return 8; 467 } 468 469 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst, 470 MemIntrinsicInfo &Info) const { 471 switch (Inst->getIntrinsicID()) { 472 case Intrinsic::amdgcn_atomic_inc: 473 case Intrinsic::amdgcn_atomic_dec: 474 case Intrinsic::amdgcn_ds_ordered_add: 475 case Intrinsic::amdgcn_ds_ordered_swap: 476 case Intrinsic::amdgcn_ds_fadd: 477 case Intrinsic::amdgcn_ds_fmin: 478 case Intrinsic::amdgcn_ds_fmax: { 479 auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2)); 480 auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4)); 481 if (!Ordering || !Volatile) 482 return false; // Invalid. 483 484 unsigned OrderingVal = Ordering->getZExtValue(); 485 if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent)) 486 return false; 487 488 Info.PtrVal = Inst->getArgOperand(0); 489 Info.Ordering = static_cast<AtomicOrdering>(OrderingVal); 490 Info.ReadMem = true; 491 Info.WriteMem = true; 492 Info.IsVolatile = !Volatile->isNullValue(); 493 return true; 494 } 495 default: 496 return false; 497 } 498 } 499 500 int GCNTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty, 501 TTI::TargetCostKind CostKind, 502 TTI::OperandValueKind Opd1Info, 503 TTI::OperandValueKind Opd2Info, 504 TTI::OperandValueProperties Opd1PropInfo, 505 TTI::OperandValueProperties Opd2PropInfo, 506 ArrayRef<const Value *> Args, 507 const Instruction *CxtI) { 508 EVT OrigTy = TLI->getValueType(DL, Ty); 509 if (!OrigTy.isSimple()) { 510 // FIXME: We're having to query the throughput cost so that the basic 511 // implementation tries to generate legalize and scalarization costs. Maybe 512 // we could hoist the scalarization code here? 513 if (CostKind != TTI::TCK_CodeSize) 514 return BaseT::getArithmeticInstrCost(Opcode, Ty, TTI::TCK_RecipThroughput, 515 Opd1Info, Opd2Info, Opd1PropInfo, 516 Opd2PropInfo, Args, CxtI); 517 // Scalarization 518 519 // Check if any of the operands are vector operands. 520 int ISD = TLI->InstructionOpcodeToISD(Opcode); 521 assert(ISD && "Invalid opcode"); 522 523 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 524 525 bool IsFloat = Ty->isFPOrFPVectorTy(); 526 // Assume that floating point arithmetic operations cost twice as much as 527 // integer operations. 528 unsigned OpCost = (IsFloat ? 2 : 1); 529 530 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) { 531 // The operation is legal. Assume it costs 1. 532 // TODO: Once we have extract/insert subvector cost we need to use them. 533 return LT.first * OpCost; 534 } 535 536 if (!TLI->isOperationExpand(ISD, LT.second)) { 537 // If the operation is custom lowered, then assume that the code is twice 538 // as expensive. 539 return LT.first * 2 * OpCost; 540 } 541 542 // Else, assume that we need to scalarize this op. 543 // TODO: If one of the types get legalized by splitting, handle this 544 // similarly to what getCastInstrCost() does. 545 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 546 unsigned Num = cast<FixedVectorType>(VTy)->getNumElements(); 547 unsigned Cost = getArithmeticInstrCost( 548 Opcode, VTy->getScalarType(), CostKind, Opd1Info, Opd2Info, 549 Opd1PropInfo, Opd2PropInfo, Args, CxtI); 550 // Return the cost of multiple scalar invocation plus the cost of 551 // inserting and extracting the values. 552 return getScalarizationOverhead(VTy, Args) + Num * Cost; 553 } 554 555 // We don't know anything about this scalar instruction. 556 return OpCost; 557 } 558 559 // Legalize the type. 560 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 561 int ISD = TLI->InstructionOpcodeToISD(Opcode); 562 563 // Because we don't have any legal vector operations, but the legal types, we 564 // need to account for split vectors. 565 unsigned NElts = LT.second.isVector() ? 566 LT.second.getVectorNumElements() : 1; 567 568 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 569 570 switch (ISD) { 571 case ISD::SHL: 572 case ISD::SRL: 573 case ISD::SRA: 574 if (SLT == MVT::i64) 575 return get64BitInstrCost(CostKind) * LT.first * NElts; 576 577 if (ST->has16BitInsts() && SLT == MVT::i16) 578 NElts = (NElts + 1) / 2; 579 580 // i32 581 return getFullRateInstrCost() * LT.first * NElts; 582 case ISD::ADD: 583 case ISD::SUB: 584 case ISD::AND: 585 case ISD::OR: 586 case ISD::XOR: 587 if (SLT == MVT::i64) { 588 // and, or and xor are typically split into 2 VALU instructions. 589 return 2 * getFullRateInstrCost() * LT.first * NElts; 590 } 591 592 if (ST->has16BitInsts() && SLT == MVT::i16) 593 NElts = (NElts + 1) / 2; 594 595 return LT.first * NElts * getFullRateInstrCost(); 596 case ISD::MUL: { 597 const int QuarterRateCost = getQuarterRateInstrCost(CostKind); 598 if (SLT == MVT::i64) { 599 const int FullRateCost = getFullRateInstrCost(); 600 return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts; 601 } 602 603 if (ST->has16BitInsts() && SLT == MVT::i16) 604 NElts = (NElts + 1) / 2; 605 606 // i32 607 return QuarterRateCost * NElts * LT.first; 608 } 609 case ISD::FMUL: 610 // Check possible fuse {fadd|fsub}(a,fmul(b,c)) and return zero cost for 611 // fmul(b,c) supposing the fadd|fsub will get estimated cost for the whole 612 // fused operation. 613 if (CxtI && CxtI->hasOneUse()) 614 if (const auto *FAdd = dyn_cast<BinaryOperator>(*CxtI->user_begin())) { 615 const int OPC = TLI->InstructionOpcodeToISD(FAdd->getOpcode()); 616 if (OPC == ISD::FADD || OPC == ISD::FSUB) { 617 if (ST->hasMadMacF32Insts() && SLT == MVT::f32 && !HasFP32Denormals) 618 return TargetTransformInfo::TCC_Free; 619 if (ST->has16BitInsts() && SLT == MVT::f16 && !HasFP64FP16Denormals) 620 return TargetTransformInfo::TCC_Free; 621 622 // Estimate all types may be fused with contract/unsafe flags 623 const TargetOptions &Options = TLI->getTargetMachine().Options; 624 if (Options.AllowFPOpFusion == FPOpFusion::Fast || 625 Options.UnsafeFPMath || 626 (FAdd->hasAllowContract() && CxtI->hasAllowContract())) 627 return TargetTransformInfo::TCC_Free; 628 } 629 } 630 LLVM_FALLTHROUGH; 631 case ISD::FADD: 632 case ISD::FSUB: 633 if (ST->hasPackedFP32Ops() && SLT == MVT::f32) 634 NElts = (NElts + 1) / 2; 635 if (SLT == MVT::f64) 636 return LT.first * NElts * get64BitInstrCost(CostKind); 637 638 if (ST->has16BitInsts() && SLT == MVT::f16) 639 NElts = (NElts + 1) / 2; 640 641 if (SLT == MVT::f32 || SLT == MVT::f16) 642 return LT.first * NElts * getFullRateInstrCost(); 643 break; 644 case ISD::FDIV: 645 case ISD::FREM: 646 // FIXME: frem should be handled separately. The fdiv in it is most of it, 647 // but the current lowering is also not entirely correct. 648 if (SLT == MVT::f64) { 649 int Cost = 7 * get64BitInstrCost(CostKind) + 650 getQuarterRateInstrCost(CostKind) + 651 3 * getHalfRateInstrCost(CostKind); 652 // Add cost of workaround. 653 if (!ST->hasUsableDivScaleConditionOutput()) 654 Cost += 3 * getFullRateInstrCost(); 655 656 return LT.first * Cost * NElts; 657 } 658 659 if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) { 660 // TODO: This is more complicated, unsafe flags etc. 661 if ((SLT == MVT::f32 && !HasFP32Denormals) || 662 (SLT == MVT::f16 && ST->has16BitInsts())) { 663 return LT.first * getQuarterRateInstrCost(CostKind) * NElts; 664 } 665 } 666 667 if (SLT == MVT::f16 && ST->has16BitInsts()) { 668 // 2 x v_cvt_f32_f16 669 // f32 rcp 670 // f32 fmul 671 // v_cvt_f16_f32 672 // f16 div_fixup 673 int Cost = 674 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost(CostKind); 675 return LT.first * Cost * NElts; 676 } 677 678 if (SLT == MVT::f32 || SLT == MVT::f16) { 679 // 4 more v_cvt_* insts without f16 insts support 680 int Cost = (SLT == MVT::f16 ? 14 : 10) * getFullRateInstrCost() + 681 1 * getQuarterRateInstrCost(CostKind); 682 683 if (!HasFP32Denormals) { 684 // FP mode switches. 685 Cost += 2 * getFullRateInstrCost(); 686 } 687 688 return LT.first * NElts * Cost; 689 } 690 break; 691 case ISD::FNEG: 692 // Use the backend' estimation. If fneg is not free each element will cost 693 // one additional instruction. 694 return TLI->isFNegFree(SLT) ? 0 : NElts; 695 default: 696 break; 697 } 698 699 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info, 700 Opd1PropInfo, Opd2PropInfo, Args, CxtI); 701 } 702 703 // Return true if there's a potential benefit from using v2f16/v2i16 704 // instructions for an intrinsic, even if it requires nontrivial legalization. 705 static bool intrinsicHasPackedVectorBenefit(Intrinsic::ID ID) { 706 switch (ID) { 707 case Intrinsic::fma: // TODO: fmuladd 708 // There's a small benefit to using vector ops in the legalized code. 709 case Intrinsic::round: 710 case Intrinsic::uadd_sat: 711 case Intrinsic::usub_sat: 712 case Intrinsic::sadd_sat: 713 case Intrinsic::ssub_sat: 714 return true; 715 default: 716 return false; 717 } 718 } 719 720 int GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 721 TTI::TargetCostKind CostKind) { 722 if (ICA.getID() == Intrinsic::fabs) 723 return 0; 724 725 if (!intrinsicHasPackedVectorBenefit(ICA.getID())) 726 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 727 728 Type *RetTy = ICA.getReturnType(); 729 EVT OrigTy = TLI->getValueType(DL, RetTy); 730 if (!OrigTy.isSimple()) { 731 if (CostKind != TTI::TCK_CodeSize) 732 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 733 734 // TODO: Combine these two logic paths. 735 if (ICA.isTypeBasedOnly()) 736 return getTypeBasedIntrinsicInstrCost(ICA, CostKind); 737 738 Type *RetTy = ICA.getReturnType(); 739 unsigned VF = ICA.getVectorFactor().getFixedValue(); 740 unsigned RetVF = 741 (RetTy->isVectorTy() ? cast<FixedVectorType>(RetTy)->getNumElements() 742 : 1); 743 assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type"); 744 const IntrinsicInst *I = ICA.getInst(); 745 const SmallVectorImpl<const Value *> &Args = ICA.getArgs(); 746 FastMathFlags FMF = ICA.getFlags(); 747 // Assume that we need to scalarize this intrinsic. 748 SmallVector<Type *, 4> Types; 749 for (const Value *Op : Args) { 750 Type *OpTy = Op->getType(); 751 assert(VF == 1 || !OpTy->isVectorTy()); 752 Types.push_back(VF == 1 ? OpTy : FixedVectorType::get(OpTy, VF)); 753 } 754 755 if (VF > 1 && !RetTy->isVoidTy()) 756 RetTy = FixedVectorType::get(RetTy, VF); 757 758 // Compute the scalarization overhead based on Args for a vector 759 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while 760 // CostModel will pass a vector RetTy and VF is 1. 761 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max(); 762 if (RetVF > 1 || VF > 1) { 763 ScalarizationCost = 0; 764 if (!RetTy->isVoidTy()) 765 ScalarizationCost += 766 getScalarizationOverhead(cast<VectorType>(RetTy), true, false); 767 ScalarizationCost += getOperandsScalarizationOverhead(Args, VF); 768 } 769 770 IntrinsicCostAttributes Attrs(ICA.getID(), RetTy, Types, FMF, 771 ScalarizationCost, I); 772 return getIntrinsicInstrCost(Attrs, CostKind); 773 } 774 775 // Legalize the type. 776 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy); 777 778 unsigned NElts = LT.second.isVector() ? 779 LT.second.getVectorNumElements() : 1; 780 781 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 782 783 if (SLT == MVT::f64) 784 return LT.first * NElts * get64BitInstrCost(CostKind); 785 786 if ((ST->has16BitInsts() && SLT == MVT::f16) || 787 (ST->hasPackedFP32Ops() && SLT == MVT::f32)) 788 NElts = (NElts + 1) / 2; 789 790 // TODO: Get more refined intrinsic costs? 791 unsigned InstRate = getQuarterRateInstrCost(CostKind); 792 if (ICA.getID() == Intrinsic::fma) { 793 InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost(CostKind) 794 : getQuarterRateInstrCost(CostKind); 795 } 796 797 return LT.first * NElts * InstRate; 798 } 799 800 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode, 801 TTI::TargetCostKind CostKind) { 802 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) 803 return Opcode == Instruction::PHI ? 0 : 1; 804 805 // XXX - For some reason this isn't called for switch. 806 switch (Opcode) { 807 case Instruction::Br: 808 case Instruction::Ret: 809 return 10; 810 default: 811 return BaseT::getCFInstrCost(Opcode, CostKind); 812 } 813 } 814 815 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, 816 bool IsPairwise, 817 TTI::TargetCostKind CostKind) { 818 EVT OrigTy = TLI->getValueType(DL, Ty); 819 820 // Computes cost on targets that have packed math instructions(which support 821 // 16-bit types only). 822 if (IsPairwise || 823 !ST->hasVOP3PInsts() || 824 OrigTy.getScalarSizeInBits() != 16) 825 return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise, CostKind); 826 827 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 828 return LT.first * getFullRateInstrCost(); 829 } 830 831 int GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, 832 bool IsPairwise, bool IsUnsigned, 833 TTI::TargetCostKind CostKind) { 834 EVT OrigTy = TLI->getValueType(DL, Ty); 835 836 // Computes cost on targets that have packed math instructions(which support 837 // 16-bit types only). 838 if (IsPairwise || 839 !ST->hasVOP3PInsts() || 840 OrigTy.getScalarSizeInBits() != 16) 841 return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned, 842 CostKind); 843 844 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 845 return LT.first * getHalfRateInstrCost(CostKind); 846 } 847 848 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 849 unsigned Index) { 850 switch (Opcode) { 851 case Instruction::ExtractElement: 852 case Instruction::InsertElement: { 853 unsigned EltSize 854 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 855 if (EltSize < 32) { 856 if (EltSize == 16 && Index == 0 && ST->has16BitInsts()) 857 return 0; 858 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 859 } 860 861 // Extracts are just reads of a subregister, so are free. Inserts are 862 // considered free because we don't want to have any cost for scalarizing 863 // operations, and we don't have to copy into a different register class. 864 865 // Dynamic indexing isn't free and is best avoided. 866 return Index == ~0u ? 2 : 0; 867 } 868 default: 869 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 870 } 871 } 872 873 /// Analyze if the results of inline asm are divergent. If \p Indices is empty, 874 /// this is analyzing the collective result of all output registers. Otherwise, 875 /// this is only querying a specific result index if this returns multiple 876 /// registers in a struct. 877 bool GCNTTIImpl::isInlineAsmSourceOfDivergence( 878 const CallInst *CI, ArrayRef<unsigned> Indices) const { 879 // TODO: Handle complex extract indices 880 if (Indices.size() > 1) 881 return true; 882 883 const DataLayout &DL = CI->getModule()->getDataLayout(); 884 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 885 TargetLowering::AsmOperandInfoVector TargetConstraints = 886 TLI->ParseConstraints(DL, ST->getRegisterInfo(), *CI); 887 888 const int TargetOutputIdx = Indices.empty() ? -1 : Indices[0]; 889 890 int OutputIdx = 0; 891 for (auto &TC : TargetConstraints) { 892 if (TC.Type != InlineAsm::isOutput) 893 continue; 894 895 // Skip outputs we don't care about. 896 if (TargetOutputIdx != -1 && TargetOutputIdx != OutputIdx++) 897 continue; 898 899 TLI->ComputeConstraintToUse(TC, SDValue()); 900 901 Register AssignedReg; 902 const TargetRegisterClass *RC; 903 std::tie(AssignedReg, RC) = TLI->getRegForInlineAsmConstraint( 904 TRI, TC.ConstraintCode, TC.ConstraintVT); 905 if (AssignedReg) { 906 // FIXME: This is a workaround for getRegForInlineAsmConstraint 907 // returning VS_32 908 RC = TRI->getPhysRegClass(AssignedReg); 909 } 910 911 // For AGPR constraints null is returned on subtargets without AGPRs, so 912 // assume divergent for null. 913 if (!RC || !TRI->isSGPRClass(RC)) 914 return true; 915 } 916 917 return false; 918 } 919 920 /// \returns true if the new GPU divergence analysis is enabled. 921 bool GCNTTIImpl::useGPUDivergenceAnalysis() const { 922 return !UseLegacyDA; 923 } 924 925 /// \returns true if the result of the value could potentially be 926 /// different across workitems in a wavefront. 927 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const { 928 if (const Argument *A = dyn_cast<Argument>(V)) 929 return !AMDGPU::isArgPassedInSGPR(A); 930 931 // Loads from the private and flat address spaces are divergent, because 932 // threads can execute the load instruction with the same inputs and get 933 // different results. 934 // 935 // All other loads are not divergent, because if threads issue loads with the 936 // same arguments, they will always get the same result. 937 if (const LoadInst *Load = dyn_cast<LoadInst>(V)) 938 return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS || 939 Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS; 940 941 // Atomics are divergent because they are executed sequentially: when an 942 // atomic operation refers to the same address in each thread, then each 943 // thread after the first sees the value written by the previous thread as 944 // original value. 945 if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V)) 946 return true; 947 948 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) 949 return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID()); 950 951 // Assume all function calls are a source of divergence. 952 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 953 if (CI->isInlineAsm()) 954 return isInlineAsmSourceOfDivergence(CI); 955 return true; 956 } 957 958 // Assume all function calls are a source of divergence. 959 if (isa<InvokeInst>(V)) 960 return true; 961 962 return false; 963 } 964 965 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const { 966 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 967 switch (Intrinsic->getIntrinsicID()) { 968 default: 969 return false; 970 case Intrinsic::amdgcn_readfirstlane: 971 case Intrinsic::amdgcn_readlane: 972 case Intrinsic::amdgcn_icmp: 973 case Intrinsic::amdgcn_fcmp: 974 case Intrinsic::amdgcn_ballot: 975 case Intrinsic::amdgcn_if_break: 976 return true; 977 } 978 } 979 980 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 981 if (CI->isInlineAsm()) 982 return !isInlineAsmSourceOfDivergence(CI); 983 return false; 984 } 985 986 const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V); 987 if (!ExtValue) 988 return false; 989 990 const CallInst *CI = dyn_cast<CallInst>(ExtValue->getOperand(0)); 991 if (!CI) 992 return false; 993 994 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(CI)) { 995 switch (Intrinsic->getIntrinsicID()) { 996 default: 997 return false; 998 case Intrinsic::amdgcn_if: 999 case Intrinsic::amdgcn_else: { 1000 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 1001 return Indices.size() == 1 && Indices[0] == 1; 1002 } 1003 } 1004 } 1005 1006 // If we have inline asm returning mixed SGPR and VGPR results, we inferred 1007 // divergent for the overall struct return. We need to override it in the 1008 // case we're extracting an SGPR component here. 1009 if (CI->isInlineAsm()) 1010 return !isInlineAsmSourceOfDivergence(CI, ExtValue->getIndices()); 1011 1012 return false; 1013 } 1014 1015 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes, 1016 Intrinsic::ID IID) const { 1017 switch (IID) { 1018 case Intrinsic::amdgcn_atomic_inc: 1019 case Intrinsic::amdgcn_atomic_dec: 1020 case Intrinsic::amdgcn_ds_fadd: 1021 case Intrinsic::amdgcn_ds_fmin: 1022 case Intrinsic::amdgcn_ds_fmax: 1023 case Intrinsic::amdgcn_is_shared: 1024 case Intrinsic::amdgcn_is_private: 1025 OpIndexes.push_back(0); 1026 return true; 1027 default: 1028 return false; 1029 } 1030 } 1031 1032 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, 1033 Value *OldV, 1034 Value *NewV) const { 1035 auto IntrID = II->getIntrinsicID(); 1036 switch (IntrID) { 1037 case Intrinsic::amdgcn_atomic_inc: 1038 case Intrinsic::amdgcn_atomic_dec: 1039 case Intrinsic::amdgcn_ds_fadd: 1040 case Intrinsic::amdgcn_ds_fmin: 1041 case Intrinsic::amdgcn_ds_fmax: { 1042 const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4)); 1043 if (!IsVolatile->isZero()) 1044 return nullptr; 1045 Module *M = II->getParent()->getParent()->getParent(); 1046 Type *DestTy = II->getType(); 1047 Type *SrcTy = NewV->getType(); 1048 Function *NewDecl = 1049 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy}); 1050 II->setArgOperand(0, NewV); 1051 II->setCalledFunction(NewDecl); 1052 return II; 1053 } 1054 case Intrinsic::amdgcn_is_shared: 1055 case Intrinsic::amdgcn_is_private: { 1056 unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ? 1057 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 1058 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1059 LLVMContext &Ctx = NewV->getType()->getContext(); 1060 ConstantInt *NewVal = (TrueAS == NewAS) ? 1061 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx); 1062 return NewVal; 1063 } 1064 case Intrinsic::ptrmask: { 1065 unsigned OldAS = OldV->getType()->getPointerAddressSpace(); 1066 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1067 Value *MaskOp = II->getArgOperand(1); 1068 Type *MaskTy = MaskOp->getType(); 1069 1070 bool DoTruncate = false; 1071 1072 const GCNTargetMachine &TM = 1073 static_cast<const GCNTargetMachine &>(getTLI()->getTargetMachine()); 1074 if (!TM.isNoopAddrSpaceCast(OldAS, NewAS)) { 1075 // All valid 64-bit to 32-bit casts work by chopping off the high 1076 // bits. Any masking only clearing the low bits will also apply in the new 1077 // address space. 1078 if (DL.getPointerSizeInBits(OldAS) != 64 || 1079 DL.getPointerSizeInBits(NewAS) != 32) 1080 return nullptr; 1081 1082 // TODO: Do we need to thread more context in here? 1083 KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II); 1084 if (Known.countMinLeadingOnes() < 32) 1085 return nullptr; 1086 1087 DoTruncate = true; 1088 } 1089 1090 IRBuilder<> B(II); 1091 if (DoTruncate) { 1092 MaskTy = B.getInt32Ty(); 1093 MaskOp = B.CreateTrunc(MaskOp, MaskTy); 1094 } 1095 1096 return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy}, 1097 {NewV, MaskOp}); 1098 } 1099 default: 1100 return nullptr; 1101 } 1102 } 1103 1104 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *VT, 1105 int Index, VectorType *SubTp) { 1106 if (ST->hasVOP3PInsts()) { 1107 if (cast<FixedVectorType>(VT)->getNumElements() == 2 && 1108 DL.getTypeSizeInBits(VT->getElementType()) == 16) { 1109 // With op_sel VOP3P instructions freely can access the low half or high 1110 // half of a register, so any swizzle is free. 1111 1112 switch (Kind) { 1113 case TTI::SK_Broadcast: 1114 case TTI::SK_Reverse: 1115 case TTI::SK_PermuteSingleSrc: 1116 return 0; 1117 default: 1118 break; 1119 } 1120 } 1121 } 1122 1123 return BaseT::getShuffleCost(Kind, VT, Index, SubTp); 1124 } 1125 1126 bool GCNTTIImpl::areInlineCompatible(const Function *Caller, 1127 const Function *Callee) const { 1128 const TargetMachine &TM = getTLI()->getTargetMachine(); 1129 const GCNSubtarget *CallerST 1130 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller)); 1131 const GCNSubtarget *CalleeST 1132 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee)); 1133 1134 const FeatureBitset &CallerBits = CallerST->getFeatureBits(); 1135 const FeatureBitset &CalleeBits = CalleeST->getFeatureBits(); 1136 1137 FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList; 1138 FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList; 1139 if ((RealCallerBits & RealCalleeBits) != RealCalleeBits) 1140 return false; 1141 1142 // FIXME: dx10_clamp can just take the caller setting, but there seems to be 1143 // no way to support merge for backend defined attributes. 1144 AMDGPU::SIModeRegisterDefaults CallerMode(*Caller); 1145 AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee); 1146 if (!CallerMode.isInlineCompatible(CalleeMode)) 1147 return false; 1148 1149 // Hack to make compile times reasonable. 1150 if (InlineMaxBB && !Callee->hasFnAttribute(Attribute::InlineHint)) { 1151 // Single BB does not increase total BB amount, thus subtract 1. 1152 size_t BBSize = Caller->size() + Callee->size() - 1; 1153 return BBSize <= InlineMaxBB; 1154 } 1155 1156 return true; 1157 } 1158 1159 unsigned GCNTTIImpl::adjustInliningThreshold(const CallBase *CB) const { 1160 // If we have a pointer to private array passed into a function 1161 // it will not be optimized out, leaving scratch usage. 1162 // Increase the inline threshold to allow inlining in this case. 1163 uint64_t AllocaSize = 0; 1164 SmallPtrSet<const AllocaInst *, 8> AIVisited; 1165 for (Value *PtrArg : CB->args()) { 1166 PointerType *Ty = dyn_cast<PointerType>(PtrArg->getType()); 1167 if (!Ty || (Ty->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS && 1168 Ty->getAddressSpace() != AMDGPUAS::FLAT_ADDRESS)) 1169 continue; 1170 1171 PtrArg = getUnderlyingObject(PtrArg); 1172 if (const AllocaInst *AI = dyn_cast<AllocaInst>(PtrArg)) { 1173 if (!AI->isStaticAlloca() || !AIVisited.insert(AI).second) 1174 continue; 1175 AllocaSize += DL.getTypeAllocSize(AI->getAllocatedType()); 1176 // If the amount of stack memory is excessive we will not be able 1177 // to get rid of the scratch anyway, bail out. 1178 if (AllocaSize > ArgAllocaCutoff) { 1179 AllocaSize = 0; 1180 break; 1181 } 1182 } 1183 } 1184 if (AllocaSize) 1185 return ArgAllocaCost; 1186 return 0; 1187 } 1188 1189 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1190 TTI::UnrollingPreferences &UP) { 1191 CommonTTI.getUnrollingPreferences(L, SE, UP); 1192 } 1193 1194 void GCNTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 1195 TTI::PeelingPreferences &PP) { 1196 CommonTTI.getPeelingPreferences(L, SE, PP); 1197 } 1198 1199 int GCNTTIImpl::get64BitInstrCost(TTI::TargetCostKind CostKind) const { 1200 return ST->hasFullRate64Ops() 1201 ? getFullRateInstrCost() 1202 : ST->hasHalfRate64Ops() ? getHalfRateInstrCost(CostKind) 1203 : getQuarterRateInstrCost(CostKind); 1204 } 1205 1206 R600TTIImpl::R600TTIImpl(const AMDGPUTargetMachine *TM, const Function &F) 1207 : BaseT(TM, F.getParent()->getDataLayout()), 1208 ST(static_cast<const R600Subtarget *>(TM->getSubtargetImpl(F))), 1209 TLI(ST->getTargetLowering()), CommonTTI(TM, F) {} 1210 1211 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 1212 return 4 * 128; // XXX - 4 channels. Should these count as vector instead? 1213 } 1214 1215 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const { 1216 return getHardwareNumberOfRegisters(Vec); 1217 } 1218 1219 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const { 1220 return 32; 1221 } 1222 1223 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const { 1224 return 32; 1225 } 1226 1227 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 1228 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 1229 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) 1230 return 128; 1231 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1232 AddrSpace == AMDGPUAS::REGION_ADDRESS) 1233 return 64; 1234 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 1235 return 32; 1236 1237 if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS || 1238 AddrSpace == AMDGPUAS::PARAM_I_ADDRESS || 1239 (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 && 1240 AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15))) 1241 return 128; 1242 llvm_unreachable("unhandled address space"); 1243 } 1244 1245 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 1246 Align Alignment, 1247 unsigned AddrSpace) const { 1248 // We allow vectorization of flat stores, even though we may need to decompose 1249 // them later if they may access private memory. We don't have enough context 1250 // here, and legalization can handle it. 1251 return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS); 1252 } 1253 1254 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 1255 Align Alignment, 1256 unsigned AddrSpace) const { 1257 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 1258 } 1259 1260 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 1261 Align Alignment, 1262 unsigned AddrSpace) const { 1263 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 1264 } 1265 1266 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) { 1267 // Disable unrolling if the loop is not vectorized. 1268 // TODO: Enable this again. 1269 if (VF == 1) 1270 return 1; 1271 1272 return 8; 1273 } 1274 1275 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode, 1276 TTI::TargetCostKind CostKind) { 1277 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) 1278 return Opcode == Instruction::PHI ? 0 : 1; 1279 1280 // XXX - For some reason this isn't called for switch. 1281 switch (Opcode) { 1282 case Instruction::Br: 1283 case Instruction::Ret: 1284 return 10; 1285 default: 1286 return BaseT::getCFInstrCost(Opcode, CostKind); 1287 } 1288 } 1289 1290 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 1291 unsigned Index) { 1292 switch (Opcode) { 1293 case Instruction::ExtractElement: 1294 case Instruction::InsertElement: { 1295 unsigned EltSize 1296 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 1297 if (EltSize < 32) { 1298 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 1299 } 1300 1301 // Extracts are just reads of a subregister, so are free. Inserts are 1302 // considered free because we don't want to have any cost for scalarizing 1303 // operations, and we don't have to copy into a different register class. 1304 1305 // Dynamic indexing isn't free and is best avoided. 1306 return Index == ~0u ? 2 : 0; 1307 } 1308 default: 1309 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 1310 } 1311 } 1312 1313 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1314 TTI::UnrollingPreferences &UP) { 1315 CommonTTI.getUnrollingPreferences(L, SE, UP); 1316 } 1317 1318 void R600TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 1319 TTI::PeelingPreferences &PP) { 1320 CommonTTI.getPeelingPreferences(L, SE, PP); 1321 } 1322