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 TypeSize 314 GCNTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const { 315 switch (K) { 316 case TargetTransformInfo::RGK_Scalar: 317 return TypeSize::getFixed(32); 318 case TargetTransformInfo::RGK_FixedWidthVector: 319 return TypeSize::getFixed(ST->hasPackedFP32Ops() ? 64 : 32); 320 case TargetTransformInfo::RGK_ScalableVector: 321 return TypeSize::getScalable(0); 322 } 323 llvm_unreachable("Unsupported register kind"); 324 } 325 326 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const { 327 return 32; 328 } 329 330 unsigned GCNTTIImpl::getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 331 if (Opcode == Instruction::Load || Opcode == Instruction::Store) 332 return 32 * 4 / ElemWidth; 333 return (ElemWidth == 16 && ST->has16BitInsts()) ? 2 334 : (ElemWidth == 32 && ST->hasPackedFP32Ops()) ? 2 335 : 1; 336 } 337 338 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize, 339 unsigned ChainSizeInBytes, 340 VectorType *VecTy) const { 341 unsigned VecRegBitWidth = VF * LoadSize; 342 if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32) 343 // TODO: Support element-size less than 32bit? 344 return 128 / LoadSize; 345 346 return VF; 347 } 348 349 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize, 350 unsigned ChainSizeInBytes, 351 VectorType *VecTy) const { 352 unsigned VecRegBitWidth = VF * StoreSize; 353 if (VecRegBitWidth > 128) 354 return 128 / StoreSize; 355 356 return VF; 357 } 358 359 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 360 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 361 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 362 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 363 AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) { 364 return 512; 365 } 366 367 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 368 return 8 * ST->getMaxPrivateElementSize(); 369 370 // Common to flat, global, local and region. Assume for unknown addrspace. 371 return 128; 372 } 373 374 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 375 Align Alignment, 376 unsigned AddrSpace) const { 377 // We allow vectorization of flat stores, even though we may need to decompose 378 // them later if they may access private memory. We don't have enough context 379 // here, and legalization can handle it. 380 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 381 return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) && 382 ChainSizeInBytes <= ST->getMaxPrivateElementSize(); 383 } 384 return true; 385 } 386 387 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 388 Align Alignment, 389 unsigned AddrSpace) const { 390 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 391 } 392 393 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 394 Align Alignment, 395 unsigned AddrSpace) const { 396 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 397 } 398 399 // FIXME: Really we would like to issue multiple 128-bit loads and stores per 400 // iteration. Should we report a larger size and let it legalize? 401 // 402 // FIXME: Should we use narrower types for local/region, or account for when 403 // unaligned access is legal? 404 // 405 // FIXME: This could use fine tuning and microbenchmarks. 406 Type *GCNTTIImpl::getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, 407 unsigned SrcAddrSpace, 408 unsigned DestAddrSpace, 409 unsigned SrcAlign, 410 unsigned DestAlign) const { 411 unsigned MinAlign = std::min(SrcAlign, DestAlign); 412 413 // A (multi-)dword access at an address == 2 (mod 4) will be decomposed by the 414 // hardware into byte accesses. If you assume all alignments are equally 415 // probable, it's more efficient on average to use short accesses for this 416 // case. 417 if (MinAlign == 2) 418 return Type::getInt16Ty(Context); 419 420 // Not all subtargets have 128-bit DS instructions, and we currently don't 421 // form them by default. 422 if (SrcAddrSpace == AMDGPUAS::LOCAL_ADDRESS || 423 SrcAddrSpace == AMDGPUAS::REGION_ADDRESS || 424 DestAddrSpace == AMDGPUAS::LOCAL_ADDRESS || 425 DestAddrSpace == AMDGPUAS::REGION_ADDRESS) { 426 return FixedVectorType::get(Type::getInt32Ty(Context), 2); 427 } 428 429 // Global memory works best with 16-byte accesses. Private memory will also 430 // hit this, although they'll be decomposed. 431 return FixedVectorType::get(Type::getInt32Ty(Context), 4); 432 } 433 434 void GCNTTIImpl::getMemcpyLoopResidualLoweringType( 435 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context, 436 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, 437 unsigned SrcAlign, unsigned DestAlign) const { 438 assert(RemainingBytes < 16); 439 440 unsigned MinAlign = std::min(SrcAlign, DestAlign); 441 442 if (MinAlign != 2) { 443 Type *I64Ty = Type::getInt64Ty(Context); 444 while (RemainingBytes >= 8) { 445 OpsOut.push_back(I64Ty); 446 RemainingBytes -= 8; 447 } 448 449 Type *I32Ty = Type::getInt32Ty(Context); 450 while (RemainingBytes >= 4) { 451 OpsOut.push_back(I32Ty); 452 RemainingBytes -= 4; 453 } 454 } 455 456 Type *I16Ty = Type::getInt16Ty(Context); 457 while (RemainingBytes >= 2) { 458 OpsOut.push_back(I16Ty); 459 RemainingBytes -= 2; 460 } 461 462 Type *I8Ty = Type::getInt8Ty(Context); 463 while (RemainingBytes) { 464 OpsOut.push_back(I8Ty); 465 --RemainingBytes; 466 } 467 } 468 469 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) { 470 // Disable unrolling if the loop is not vectorized. 471 // TODO: Enable this again. 472 if (VF == 1) 473 return 1; 474 475 return 8; 476 } 477 478 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst, 479 MemIntrinsicInfo &Info) const { 480 switch (Inst->getIntrinsicID()) { 481 case Intrinsic::amdgcn_atomic_inc: 482 case Intrinsic::amdgcn_atomic_dec: 483 case Intrinsic::amdgcn_ds_ordered_add: 484 case Intrinsic::amdgcn_ds_ordered_swap: 485 case Intrinsic::amdgcn_ds_fadd: 486 case Intrinsic::amdgcn_ds_fmin: 487 case Intrinsic::amdgcn_ds_fmax: { 488 auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2)); 489 auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4)); 490 if (!Ordering || !Volatile) 491 return false; // Invalid. 492 493 unsigned OrderingVal = Ordering->getZExtValue(); 494 if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent)) 495 return false; 496 497 Info.PtrVal = Inst->getArgOperand(0); 498 Info.Ordering = static_cast<AtomicOrdering>(OrderingVal); 499 Info.ReadMem = true; 500 Info.WriteMem = true; 501 Info.IsVolatile = !Volatile->isNullValue(); 502 return true; 503 } 504 default: 505 return false; 506 } 507 } 508 509 int GCNTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty, 510 TTI::TargetCostKind CostKind, 511 TTI::OperandValueKind Opd1Info, 512 TTI::OperandValueKind Opd2Info, 513 TTI::OperandValueProperties Opd1PropInfo, 514 TTI::OperandValueProperties Opd2PropInfo, 515 ArrayRef<const Value *> Args, 516 const Instruction *CxtI) { 517 EVT OrigTy = TLI->getValueType(DL, Ty); 518 if (!OrigTy.isSimple()) { 519 // FIXME: We're having to query the throughput cost so that the basic 520 // implementation tries to generate legalize and scalarization costs. Maybe 521 // we could hoist the scalarization code here? 522 if (CostKind != TTI::TCK_CodeSize) 523 return BaseT::getArithmeticInstrCost(Opcode, Ty, TTI::TCK_RecipThroughput, 524 Opd1Info, Opd2Info, Opd1PropInfo, 525 Opd2PropInfo, Args, CxtI); 526 // Scalarization 527 528 // Check if any of the operands are vector operands. 529 int ISD = TLI->InstructionOpcodeToISD(Opcode); 530 assert(ISD && "Invalid opcode"); 531 532 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 533 534 bool IsFloat = Ty->isFPOrFPVectorTy(); 535 // Assume that floating point arithmetic operations cost twice as much as 536 // integer operations. 537 unsigned OpCost = (IsFloat ? 2 : 1); 538 539 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) { 540 // The operation is legal. Assume it costs 1. 541 // TODO: Once we have extract/insert subvector cost we need to use them. 542 return LT.first * OpCost; 543 } 544 545 if (!TLI->isOperationExpand(ISD, LT.second)) { 546 // If the operation is custom lowered, then assume that the code is twice 547 // as expensive. 548 return LT.first * 2 * OpCost; 549 } 550 551 // Else, assume that we need to scalarize this op. 552 // TODO: If one of the types get legalized by splitting, handle this 553 // similarly to what getCastInstrCost() does. 554 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 555 unsigned Num = cast<FixedVectorType>(VTy)->getNumElements(); 556 unsigned Cost = getArithmeticInstrCost( 557 Opcode, VTy->getScalarType(), CostKind, Opd1Info, Opd2Info, 558 Opd1PropInfo, Opd2PropInfo, Args, CxtI); 559 // Return the cost of multiple scalar invocation plus the cost of 560 // inserting and extracting the values. 561 SmallVector<Type *> Tys(Args.size(), Ty); 562 return getScalarizationOverhead(VTy, Args, Tys) + Num * Cost; 563 } 564 565 // We don't know anything about this scalar instruction. 566 return OpCost; 567 } 568 569 // Legalize the type. 570 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 571 int ISD = TLI->InstructionOpcodeToISD(Opcode); 572 573 // Because we don't have any legal vector operations, but the legal types, we 574 // need to account for split vectors. 575 unsigned NElts = LT.second.isVector() ? 576 LT.second.getVectorNumElements() : 1; 577 578 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 579 580 switch (ISD) { 581 case ISD::SHL: 582 case ISD::SRL: 583 case ISD::SRA: 584 if (SLT == MVT::i64) 585 return get64BitInstrCost(CostKind) * LT.first * NElts; 586 587 if (ST->has16BitInsts() && SLT == MVT::i16) 588 NElts = (NElts + 1) / 2; 589 590 // i32 591 return getFullRateInstrCost() * LT.first * NElts; 592 case ISD::ADD: 593 case ISD::SUB: 594 case ISD::AND: 595 case ISD::OR: 596 case ISD::XOR: 597 if (SLT == MVT::i64) { 598 // and, or and xor are typically split into 2 VALU instructions. 599 return 2 * getFullRateInstrCost() * LT.first * NElts; 600 } 601 602 if (ST->has16BitInsts() && SLT == MVT::i16) 603 NElts = (NElts + 1) / 2; 604 605 return LT.first * NElts * getFullRateInstrCost(); 606 case ISD::MUL: { 607 const int QuarterRateCost = getQuarterRateInstrCost(CostKind); 608 if (SLT == MVT::i64) { 609 const int FullRateCost = getFullRateInstrCost(); 610 return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts; 611 } 612 613 if (ST->has16BitInsts() && SLT == MVT::i16) 614 NElts = (NElts + 1) / 2; 615 616 // i32 617 return QuarterRateCost * NElts * LT.first; 618 } 619 case ISD::FMUL: 620 // Check possible fuse {fadd|fsub}(a,fmul(b,c)) and return zero cost for 621 // fmul(b,c) supposing the fadd|fsub will get estimated cost for the whole 622 // fused operation. 623 if (CxtI && CxtI->hasOneUse()) 624 if (const auto *FAdd = dyn_cast<BinaryOperator>(*CxtI->user_begin())) { 625 const int OPC = TLI->InstructionOpcodeToISD(FAdd->getOpcode()); 626 if (OPC == ISD::FADD || OPC == ISD::FSUB) { 627 if (ST->hasMadMacF32Insts() && SLT == MVT::f32 && !HasFP32Denormals) 628 return TargetTransformInfo::TCC_Free; 629 if (ST->has16BitInsts() && SLT == MVT::f16 && !HasFP64FP16Denormals) 630 return TargetTransformInfo::TCC_Free; 631 632 // Estimate all types may be fused with contract/unsafe flags 633 const TargetOptions &Options = TLI->getTargetMachine().Options; 634 if (Options.AllowFPOpFusion == FPOpFusion::Fast || 635 Options.UnsafeFPMath || 636 (FAdd->hasAllowContract() && CxtI->hasAllowContract())) 637 return TargetTransformInfo::TCC_Free; 638 } 639 } 640 LLVM_FALLTHROUGH; 641 case ISD::FADD: 642 case ISD::FSUB: 643 if (ST->hasPackedFP32Ops() && SLT == MVT::f32) 644 NElts = (NElts + 1) / 2; 645 if (SLT == MVT::f64) 646 return LT.first * NElts * get64BitInstrCost(CostKind); 647 648 if (ST->has16BitInsts() && SLT == MVT::f16) 649 NElts = (NElts + 1) / 2; 650 651 if (SLT == MVT::f32 || SLT == MVT::f16) 652 return LT.first * NElts * getFullRateInstrCost(); 653 break; 654 case ISD::FDIV: 655 case ISD::FREM: 656 // FIXME: frem should be handled separately. The fdiv in it is most of it, 657 // but the current lowering is also not entirely correct. 658 if (SLT == MVT::f64) { 659 int Cost = 7 * get64BitInstrCost(CostKind) + 660 getQuarterRateInstrCost(CostKind) + 661 3 * getHalfRateInstrCost(CostKind); 662 // Add cost of workaround. 663 if (!ST->hasUsableDivScaleConditionOutput()) 664 Cost += 3 * getFullRateInstrCost(); 665 666 return LT.first * Cost * NElts; 667 } 668 669 if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) { 670 // TODO: This is more complicated, unsafe flags etc. 671 if ((SLT == MVT::f32 && !HasFP32Denormals) || 672 (SLT == MVT::f16 && ST->has16BitInsts())) { 673 return LT.first * getQuarterRateInstrCost(CostKind) * NElts; 674 } 675 } 676 677 if (SLT == MVT::f16 && ST->has16BitInsts()) { 678 // 2 x v_cvt_f32_f16 679 // f32 rcp 680 // f32 fmul 681 // v_cvt_f16_f32 682 // f16 div_fixup 683 int Cost = 684 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost(CostKind); 685 return LT.first * Cost * NElts; 686 } 687 688 if (SLT == MVT::f32 || SLT == MVT::f16) { 689 // 4 more v_cvt_* insts without f16 insts support 690 int Cost = (SLT == MVT::f16 ? 14 : 10) * getFullRateInstrCost() + 691 1 * getQuarterRateInstrCost(CostKind); 692 693 if (!HasFP32Denormals) { 694 // FP mode switches. 695 Cost += 2 * getFullRateInstrCost(); 696 } 697 698 return LT.first * NElts * Cost; 699 } 700 break; 701 case ISD::FNEG: 702 // Use the backend' estimation. If fneg is not free each element will cost 703 // one additional instruction. 704 return TLI->isFNegFree(SLT) ? 0 : NElts; 705 default: 706 break; 707 } 708 709 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info, 710 Opd1PropInfo, Opd2PropInfo, Args, CxtI); 711 } 712 713 // Return true if there's a potential benefit from using v2f16/v2i16 714 // instructions for an intrinsic, even if it requires nontrivial legalization. 715 static bool intrinsicHasPackedVectorBenefit(Intrinsic::ID ID) { 716 switch (ID) { 717 case Intrinsic::fma: // TODO: fmuladd 718 // There's a small benefit to using vector ops in the legalized code. 719 case Intrinsic::round: 720 case Intrinsic::uadd_sat: 721 case Intrinsic::usub_sat: 722 case Intrinsic::sadd_sat: 723 case Intrinsic::ssub_sat: 724 return true; 725 default: 726 return false; 727 } 728 } 729 730 InstructionCost 731 GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 732 TTI::TargetCostKind CostKind) { 733 if (ICA.getID() == Intrinsic::fabs) 734 return 0; 735 736 if (!intrinsicHasPackedVectorBenefit(ICA.getID())) 737 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 738 739 Type *RetTy = ICA.getReturnType(); 740 EVT OrigTy = TLI->getValueType(DL, RetTy); 741 if (!OrigTy.isSimple()) { 742 if (CostKind != TTI::TCK_CodeSize) 743 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 744 745 // TODO: Combine these two logic paths. 746 if (ICA.isTypeBasedOnly()) 747 return getTypeBasedIntrinsicInstrCost(ICA, CostKind); 748 749 unsigned RetVF = 750 (RetTy->isVectorTy() ? cast<FixedVectorType>(RetTy)->getNumElements() 751 : 1); 752 const IntrinsicInst *I = ICA.getInst(); 753 const SmallVectorImpl<const Value *> &Args = ICA.getArgs(); 754 FastMathFlags FMF = ICA.getFlags(); 755 // Assume that we need to scalarize this intrinsic. 756 757 // Compute the scalarization overhead based on Args for a vector 758 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while 759 // CostModel will pass a vector RetTy and VF is 1. 760 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max(); 761 if (RetVF > 1) { 762 ScalarizationCost = 0; 763 if (!RetTy->isVoidTy()) 764 ScalarizationCost += 765 getScalarizationOverhead(cast<VectorType>(RetTy), true, false); 766 ScalarizationCost += 767 getOperandsScalarizationOverhead(Args, ICA.getArgTypes()); 768 } 769 770 IntrinsicCostAttributes Attrs(ICA.getID(), RetTy, ICA.getArgTypes(), FMF, I, 771 ScalarizationCost); 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 793 switch (ICA.getID()) { 794 case Intrinsic::fma: 795 InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost(CostKind) 796 : getQuarterRateInstrCost(CostKind); 797 break; 798 case Intrinsic::uadd_sat: 799 case Intrinsic::usub_sat: 800 case Intrinsic::sadd_sat: 801 case Intrinsic::ssub_sat: 802 static const auto ValidSatTys = {MVT::v2i16, MVT::v4i16}; 803 if (any_of(ValidSatTys, [<](MVT M) { return M == LT.second; })) 804 NElts = 1; 805 break; 806 } 807 808 return LT.first * NElts * InstRate; 809 } 810 811 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode, 812 TTI::TargetCostKind CostKind) { 813 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) 814 return Opcode == Instruction::PHI ? 0 : 1; 815 816 // XXX - For some reason this isn't called for switch. 817 switch (Opcode) { 818 case Instruction::Br: 819 case Instruction::Ret: 820 return 10; 821 default: 822 return BaseT::getCFInstrCost(Opcode, CostKind); 823 } 824 } 825 826 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, 827 bool IsPairwise, 828 TTI::TargetCostKind CostKind) { 829 EVT OrigTy = TLI->getValueType(DL, Ty); 830 831 // Computes cost on targets that have packed math instructions(which support 832 // 16-bit types only). 833 if (IsPairwise || 834 !ST->hasVOP3PInsts() || 835 OrigTy.getScalarSizeInBits() != 16) 836 return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise, CostKind); 837 838 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 839 return LT.first * getFullRateInstrCost(); 840 } 841 842 int GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, 843 bool IsPairwise, bool IsUnsigned, 844 TTI::TargetCostKind CostKind) { 845 EVT OrigTy = TLI->getValueType(DL, Ty); 846 847 // Computes cost on targets that have packed math instructions(which support 848 // 16-bit types only). 849 if (IsPairwise || 850 !ST->hasVOP3PInsts() || 851 OrigTy.getScalarSizeInBits() != 16) 852 return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned, 853 CostKind); 854 855 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 856 return LT.first * getHalfRateInstrCost(CostKind); 857 } 858 859 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 860 unsigned Index) { 861 switch (Opcode) { 862 case Instruction::ExtractElement: 863 case Instruction::InsertElement: { 864 unsigned EltSize 865 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 866 if (EltSize < 32) { 867 if (EltSize == 16 && Index == 0 && ST->has16BitInsts()) 868 return 0; 869 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 870 } 871 872 // Extracts are just reads of a subregister, so are free. Inserts are 873 // considered free because we don't want to have any cost for scalarizing 874 // operations, and we don't have to copy into a different register class. 875 876 // Dynamic indexing isn't free and is best avoided. 877 return Index == ~0u ? 2 : 0; 878 } 879 default: 880 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 881 } 882 } 883 884 /// Analyze if the results of inline asm are divergent. If \p Indices is empty, 885 /// this is analyzing the collective result of all output registers. Otherwise, 886 /// this is only querying a specific result index if this returns multiple 887 /// registers in a struct. 888 bool GCNTTIImpl::isInlineAsmSourceOfDivergence( 889 const CallInst *CI, ArrayRef<unsigned> Indices) const { 890 // TODO: Handle complex extract indices 891 if (Indices.size() > 1) 892 return true; 893 894 const DataLayout &DL = CI->getModule()->getDataLayout(); 895 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 896 TargetLowering::AsmOperandInfoVector TargetConstraints = 897 TLI->ParseConstraints(DL, ST->getRegisterInfo(), *CI); 898 899 const int TargetOutputIdx = Indices.empty() ? -1 : Indices[0]; 900 901 int OutputIdx = 0; 902 for (auto &TC : TargetConstraints) { 903 if (TC.Type != InlineAsm::isOutput) 904 continue; 905 906 // Skip outputs we don't care about. 907 if (TargetOutputIdx != -1 && TargetOutputIdx != OutputIdx++) 908 continue; 909 910 TLI->ComputeConstraintToUse(TC, SDValue()); 911 912 Register AssignedReg; 913 const TargetRegisterClass *RC; 914 std::tie(AssignedReg, RC) = TLI->getRegForInlineAsmConstraint( 915 TRI, TC.ConstraintCode, TC.ConstraintVT); 916 if (AssignedReg) { 917 // FIXME: This is a workaround for getRegForInlineAsmConstraint 918 // returning VS_32 919 RC = TRI->getPhysRegClass(AssignedReg); 920 } 921 922 // For AGPR constraints null is returned on subtargets without AGPRs, so 923 // assume divergent for null. 924 if (!RC || !TRI->isSGPRClass(RC)) 925 return true; 926 } 927 928 return false; 929 } 930 931 /// \returns true if the new GPU divergence analysis is enabled. 932 bool GCNTTIImpl::useGPUDivergenceAnalysis() const { 933 return !UseLegacyDA; 934 } 935 936 /// \returns true if the result of the value could potentially be 937 /// different across workitems in a wavefront. 938 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const { 939 if (const Argument *A = dyn_cast<Argument>(V)) 940 return !AMDGPU::isArgPassedInSGPR(A); 941 942 // Loads from the private and flat address spaces are divergent, because 943 // threads can execute the load instruction with the same inputs and get 944 // different results. 945 // 946 // All other loads are not divergent, because if threads issue loads with the 947 // same arguments, they will always get the same result. 948 if (const LoadInst *Load = dyn_cast<LoadInst>(V)) 949 return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS || 950 Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS; 951 952 // Atomics are divergent because they are executed sequentially: when an 953 // atomic operation refers to the same address in each thread, then each 954 // thread after the first sees the value written by the previous thread as 955 // original value. 956 if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V)) 957 return true; 958 959 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) 960 return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID()); 961 962 // Assume all function calls are a source of divergence. 963 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 964 if (CI->isInlineAsm()) 965 return isInlineAsmSourceOfDivergence(CI); 966 return true; 967 } 968 969 // Assume all function calls are a source of divergence. 970 if (isa<InvokeInst>(V)) 971 return true; 972 973 return false; 974 } 975 976 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const { 977 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 978 switch (Intrinsic->getIntrinsicID()) { 979 default: 980 return false; 981 case Intrinsic::amdgcn_readfirstlane: 982 case Intrinsic::amdgcn_readlane: 983 case Intrinsic::amdgcn_icmp: 984 case Intrinsic::amdgcn_fcmp: 985 case Intrinsic::amdgcn_ballot: 986 case Intrinsic::amdgcn_if_break: 987 return true; 988 } 989 } 990 991 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 992 if (CI->isInlineAsm()) 993 return !isInlineAsmSourceOfDivergence(CI); 994 return false; 995 } 996 997 const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V); 998 if (!ExtValue) 999 return false; 1000 1001 const CallInst *CI = dyn_cast<CallInst>(ExtValue->getOperand(0)); 1002 if (!CI) 1003 return false; 1004 1005 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(CI)) { 1006 switch (Intrinsic->getIntrinsicID()) { 1007 default: 1008 return false; 1009 case Intrinsic::amdgcn_if: 1010 case Intrinsic::amdgcn_else: { 1011 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 1012 return Indices.size() == 1 && Indices[0] == 1; 1013 } 1014 } 1015 } 1016 1017 // If we have inline asm returning mixed SGPR and VGPR results, we inferred 1018 // divergent for the overall struct return. We need to override it in the 1019 // case we're extracting an SGPR component here. 1020 if (CI->isInlineAsm()) 1021 return !isInlineAsmSourceOfDivergence(CI, ExtValue->getIndices()); 1022 1023 return false; 1024 } 1025 1026 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes, 1027 Intrinsic::ID IID) const { 1028 switch (IID) { 1029 case Intrinsic::amdgcn_atomic_inc: 1030 case Intrinsic::amdgcn_atomic_dec: 1031 case Intrinsic::amdgcn_ds_fadd: 1032 case Intrinsic::amdgcn_ds_fmin: 1033 case Intrinsic::amdgcn_ds_fmax: 1034 case Intrinsic::amdgcn_is_shared: 1035 case Intrinsic::amdgcn_is_private: 1036 OpIndexes.push_back(0); 1037 return true; 1038 default: 1039 return false; 1040 } 1041 } 1042 1043 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, 1044 Value *OldV, 1045 Value *NewV) const { 1046 auto IntrID = II->getIntrinsicID(); 1047 switch (IntrID) { 1048 case Intrinsic::amdgcn_atomic_inc: 1049 case Intrinsic::amdgcn_atomic_dec: 1050 case Intrinsic::amdgcn_ds_fadd: 1051 case Intrinsic::amdgcn_ds_fmin: 1052 case Intrinsic::amdgcn_ds_fmax: { 1053 const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4)); 1054 if (!IsVolatile->isZero()) 1055 return nullptr; 1056 Module *M = II->getParent()->getParent()->getParent(); 1057 Type *DestTy = II->getType(); 1058 Type *SrcTy = NewV->getType(); 1059 Function *NewDecl = 1060 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy}); 1061 II->setArgOperand(0, NewV); 1062 II->setCalledFunction(NewDecl); 1063 return II; 1064 } 1065 case Intrinsic::amdgcn_is_shared: 1066 case Intrinsic::amdgcn_is_private: { 1067 unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ? 1068 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 1069 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1070 LLVMContext &Ctx = NewV->getType()->getContext(); 1071 ConstantInt *NewVal = (TrueAS == NewAS) ? 1072 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx); 1073 return NewVal; 1074 } 1075 case Intrinsic::ptrmask: { 1076 unsigned OldAS = OldV->getType()->getPointerAddressSpace(); 1077 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1078 Value *MaskOp = II->getArgOperand(1); 1079 Type *MaskTy = MaskOp->getType(); 1080 1081 bool DoTruncate = false; 1082 1083 const GCNTargetMachine &TM = 1084 static_cast<const GCNTargetMachine &>(getTLI()->getTargetMachine()); 1085 if (!TM.isNoopAddrSpaceCast(OldAS, NewAS)) { 1086 // All valid 64-bit to 32-bit casts work by chopping off the high 1087 // bits. Any masking only clearing the low bits will also apply in the new 1088 // address space. 1089 if (DL.getPointerSizeInBits(OldAS) != 64 || 1090 DL.getPointerSizeInBits(NewAS) != 32) 1091 return nullptr; 1092 1093 // TODO: Do we need to thread more context in here? 1094 KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II); 1095 if (Known.countMinLeadingOnes() < 32) 1096 return nullptr; 1097 1098 DoTruncate = true; 1099 } 1100 1101 IRBuilder<> B(II); 1102 if (DoTruncate) { 1103 MaskTy = B.getInt32Ty(); 1104 MaskOp = B.CreateTrunc(MaskOp, MaskTy); 1105 } 1106 1107 return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy}, 1108 {NewV, MaskOp}); 1109 } 1110 default: 1111 return nullptr; 1112 } 1113 } 1114 1115 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *VT, 1116 ArrayRef<int> Mask, int Index, 1117 VectorType *SubTp) { 1118 if (ST->hasVOP3PInsts()) { 1119 if (cast<FixedVectorType>(VT)->getNumElements() == 2 && 1120 DL.getTypeSizeInBits(VT->getElementType()) == 16) { 1121 // With op_sel VOP3P instructions freely can access the low half or high 1122 // half of a register, so any swizzle is free. 1123 1124 switch (Kind) { 1125 case TTI::SK_Broadcast: 1126 case TTI::SK_Reverse: 1127 case TTI::SK_PermuteSingleSrc: 1128 return 0; 1129 default: 1130 break; 1131 } 1132 } 1133 } 1134 1135 return BaseT::getShuffleCost(Kind, VT, Mask, Index, SubTp); 1136 } 1137 1138 bool GCNTTIImpl::areInlineCompatible(const Function *Caller, 1139 const Function *Callee) const { 1140 const TargetMachine &TM = getTLI()->getTargetMachine(); 1141 const GCNSubtarget *CallerST 1142 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller)); 1143 const GCNSubtarget *CalleeST 1144 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee)); 1145 1146 const FeatureBitset &CallerBits = CallerST->getFeatureBits(); 1147 const FeatureBitset &CalleeBits = CalleeST->getFeatureBits(); 1148 1149 FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList; 1150 FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList; 1151 if ((RealCallerBits & RealCalleeBits) != RealCalleeBits) 1152 return false; 1153 1154 // FIXME: dx10_clamp can just take the caller setting, but there seems to be 1155 // no way to support merge for backend defined attributes. 1156 AMDGPU::SIModeRegisterDefaults CallerMode(*Caller); 1157 AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee); 1158 if (!CallerMode.isInlineCompatible(CalleeMode)) 1159 return false; 1160 1161 if (Callee->hasFnAttribute(Attribute::AlwaysInline) || 1162 Callee->hasFnAttribute(Attribute::InlineHint)) 1163 return true; 1164 1165 // Hack to make compile times reasonable. 1166 if (InlineMaxBB) { 1167 // Single BB does not increase total BB amount. 1168 if (Callee->size() == 1) 1169 return true; 1170 size_t BBSize = Caller->size() + Callee->size() - 1; 1171 return BBSize <= InlineMaxBB; 1172 } 1173 1174 return true; 1175 } 1176 1177 unsigned GCNTTIImpl::adjustInliningThreshold(const CallBase *CB) const { 1178 // If we have a pointer to private array passed into a function 1179 // it will not be optimized out, leaving scratch usage. 1180 // Increase the inline threshold to allow inlining in this case. 1181 uint64_t AllocaSize = 0; 1182 SmallPtrSet<const AllocaInst *, 8> AIVisited; 1183 for (Value *PtrArg : CB->args()) { 1184 PointerType *Ty = dyn_cast<PointerType>(PtrArg->getType()); 1185 if (!Ty || (Ty->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS && 1186 Ty->getAddressSpace() != AMDGPUAS::FLAT_ADDRESS)) 1187 continue; 1188 1189 PtrArg = getUnderlyingObject(PtrArg); 1190 if (const AllocaInst *AI = dyn_cast<AllocaInst>(PtrArg)) { 1191 if (!AI->isStaticAlloca() || !AIVisited.insert(AI).second) 1192 continue; 1193 AllocaSize += DL.getTypeAllocSize(AI->getAllocatedType()); 1194 // If the amount of stack memory is excessive we will not be able 1195 // to get rid of the scratch anyway, bail out. 1196 if (AllocaSize > ArgAllocaCutoff) { 1197 AllocaSize = 0; 1198 break; 1199 } 1200 } 1201 } 1202 if (AllocaSize) 1203 return ArgAllocaCost; 1204 return 0; 1205 } 1206 1207 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1208 TTI::UnrollingPreferences &UP) { 1209 CommonTTI.getUnrollingPreferences(L, SE, UP); 1210 } 1211 1212 void GCNTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 1213 TTI::PeelingPreferences &PP) { 1214 CommonTTI.getPeelingPreferences(L, SE, PP); 1215 } 1216 1217 int GCNTTIImpl::get64BitInstrCost(TTI::TargetCostKind CostKind) const { 1218 return ST->hasFullRate64Ops() 1219 ? getFullRateInstrCost() 1220 : ST->hasHalfRate64Ops() ? getHalfRateInstrCost(CostKind) 1221 : getQuarterRateInstrCost(CostKind); 1222 } 1223 1224 R600TTIImpl::R600TTIImpl(const AMDGPUTargetMachine *TM, const Function &F) 1225 : BaseT(TM, F.getParent()->getDataLayout()), 1226 ST(static_cast<const R600Subtarget *>(TM->getSubtargetImpl(F))), 1227 TLI(ST->getTargetLowering()), CommonTTI(TM, F) {} 1228 1229 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 1230 return 4 * 128; // XXX - 4 channels. Should these count as vector instead? 1231 } 1232 1233 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const { 1234 return getHardwareNumberOfRegisters(Vec); 1235 } 1236 1237 TypeSize 1238 R600TTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const { 1239 return TypeSize::getFixed(32); 1240 } 1241 1242 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const { 1243 return 32; 1244 } 1245 1246 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 1247 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 1248 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) 1249 return 128; 1250 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1251 AddrSpace == AMDGPUAS::REGION_ADDRESS) 1252 return 64; 1253 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 1254 return 32; 1255 1256 if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS || 1257 AddrSpace == AMDGPUAS::PARAM_I_ADDRESS || 1258 (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 && 1259 AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15))) 1260 return 128; 1261 llvm_unreachable("unhandled address space"); 1262 } 1263 1264 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 1265 Align Alignment, 1266 unsigned AddrSpace) const { 1267 // We allow vectorization of flat stores, even though we may need to decompose 1268 // them later if they may access private memory. We don't have enough context 1269 // here, and legalization can handle it. 1270 return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS); 1271 } 1272 1273 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 1274 Align Alignment, 1275 unsigned AddrSpace) const { 1276 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 1277 } 1278 1279 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 1280 Align Alignment, 1281 unsigned AddrSpace) const { 1282 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 1283 } 1284 1285 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) { 1286 // Disable unrolling if the loop is not vectorized. 1287 // TODO: Enable this again. 1288 if (VF == 1) 1289 return 1; 1290 1291 return 8; 1292 } 1293 1294 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode, 1295 TTI::TargetCostKind CostKind) { 1296 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) 1297 return Opcode == Instruction::PHI ? 0 : 1; 1298 1299 // XXX - For some reason this isn't called for switch. 1300 switch (Opcode) { 1301 case Instruction::Br: 1302 case Instruction::Ret: 1303 return 10; 1304 default: 1305 return BaseT::getCFInstrCost(Opcode, CostKind); 1306 } 1307 } 1308 1309 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 1310 unsigned Index) { 1311 switch (Opcode) { 1312 case Instruction::ExtractElement: 1313 case Instruction::InsertElement: { 1314 unsigned EltSize 1315 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 1316 if (EltSize < 32) { 1317 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 1318 } 1319 1320 // Extracts are just reads of a subregister, so are free. Inserts are 1321 // considered free because we don't want to have any cost for scalarizing 1322 // operations, and we don't have to copy into a different register class. 1323 1324 // Dynamic indexing isn't free and is best avoided. 1325 return Index == ~0u ? 2 : 0; 1326 } 1327 default: 1328 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 1329 } 1330 } 1331 1332 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1333 TTI::UnrollingPreferences &UP) { 1334 CommonTTI.getUnrollingPreferences(L, SE, UP); 1335 } 1336 1337 void R600TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 1338 TTI::PeelingPreferences &PP) { 1339 CommonTTI.getPeelingPreferences(L, SE, PP); 1340 } 1341