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 "AMDGPUSubtarget.h" 19 #include "Utils/AMDGPUBaseInfo.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/Analysis/TargetTransformInfo.h" 23 #include "llvm/Analysis/ValueTracking.h" 24 #include "llvm/CodeGen/ISDOpcodes.h" 25 #include "llvm/CodeGen/ValueTypes.h" 26 #include "llvm/IR/Argument.h" 27 #include "llvm/IR/Attributes.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CallingConv.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DerivedTypes.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/IntrinsicInst.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/PatternMatch.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/IR/Value.h" 40 #include "llvm/MC/SubtargetFeature.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/MachineValueType.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Target/TargetMachine.h" 48 #include <algorithm> 49 #include <cassert> 50 #include <limits> 51 #include <utility> 52 53 using namespace llvm; 54 55 #define DEBUG_TYPE "AMDGPUtti" 56 57 static cl::opt<unsigned> UnrollThresholdPrivate( 58 "amdgpu-unroll-threshold-private", 59 cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"), 60 cl::init(2700), cl::Hidden); 61 62 static cl::opt<unsigned> UnrollThresholdLocal( 63 "amdgpu-unroll-threshold-local", 64 cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"), 65 cl::init(1000), cl::Hidden); 66 67 static cl::opt<unsigned> UnrollThresholdIf( 68 "amdgpu-unroll-threshold-if", 69 cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"), 70 cl::init(150), cl::Hidden); 71 72 static cl::opt<bool> UnrollRuntimeLocal( 73 "amdgpu-unroll-runtime-local", 74 cl::desc("Allow runtime unroll for AMDGPU if local memory used in a loop"), 75 cl::init(true), cl::Hidden); 76 77 static cl::opt<bool> UseLegacyDA( 78 "amdgpu-use-legacy-divergence-analysis", 79 cl::desc("Enable legacy divergence analysis for AMDGPU"), 80 cl::init(false), cl::Hidden); 81 82 static cl::opt<unsigned> UnrollMaxBlockToAnalyze( 83 "amdgpu-unroll-max-block-to-analyze", 84 cl::desc("Inner loop block size threshold to analyze in unroll for AMDGPU"), 85 cl::init(20), cl::Hidden); 86 87 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond, 88 unsigned Depth = 0) { 89 const Instruction *I = dyn_cast<Instruction>(Cond); 90 if (!I) 91 return false; 92 93 for (const Value *V : I->operand_values()) { 94 if (!L->contains(I)) 95 continue; 96 if (const PHINode *PHI = dyn_cast<PHINode>(V)) { 97 if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) { 98 return SubLoop->contains(PHI); })) 99 return true; 100 } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1)) 101 return true; 102 } 103 return false; 104 } 105 106 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 107 TTI::UnrollingPreferences &UP) { 108 const Function &F = *L->getHeader()->getParent(); 109 UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300); 110 UP.MaxCount = std::numeric_limits<unsigned>::max(); 111 UP.Partial = true; 112 113 // TODO: Do we want runtime unrolling? 114 115 // Maximum alloca size than can fit registers. Reserve 16 registers. 116 const unsigned MaxAlloca = (256 - 16) * 4; 117 unsigned ThresholdPrivate = UnrollThresholdPrivate; 118 unsigned ThresholdLocal = UnrollThresholdLocal; 119 unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal); 120 for (const BasicBlock *BB : L->getBlocks()) { 121 const DataLayout &DL = BB->getModule()->getDataLayout(); 122 unsigned LocalGEPsSeen = 0; 123 124 if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) { 125 return SubLoop->contains(BB); })) 126 continue; // Block belongs to an inner loop. 127 128 for (const Instruction &I : *BB) { 129 // Unroll a loop which contains an "if" statement whose condition 130 // defined by a PHI belonging to the loop. This may help to eliminate 131 // if region and potentially even PHI itself, saving on both divergence 132 // and registers used for the PHI. 133 // Add a small bonus for each of such "if" statements. 134 if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) { 135 if (UP.Threshold < MaxBoost && Br->isConditional()) { 136 BasicBlock *Succ0 = Br->getSuccessor(0); 137 BasicBlock *Succ1 = Br->getSuccessor(1); 138 if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) || 139 (L->contains(Succ1) && L->isLoopExiting(Succ1))) 140 continue; 141 if (dependsOnLocalPhi(L, Br->getCondition())) { 142 UP.Threshold += UnrollThresholdIf; 143 LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold 144 << " for loop:\n" 145 << *L << " due to " << *Br << '\n'); 146 if (UP.Threshold >= MaxBoost) 147 return; 148 } 149 } 150 continue; 151 } 152 153 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I); 154 if (!GEP) 155 continue; 156 157 unsigned AS = GEP->getAddressSpace(); 158 unsigned Threshold = 0; 159 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 160 Threshold = ThresholdPrivate; 161 else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) 162 Threshold = ThresholdLocal; 163 else 164 continue; 165 166 if (UP.Threshold >= Threshold) 167 continue; 168 169 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 170 const Value *Ptr = GEP->getPointerOperand(); 171 const AllocaInst *Alloca = 172 dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr, DL)); 173 if (!Alloca || !Alloca->isStaticAlloca()) 174 continue; 175 Type *Ty = Alloca->getAllocatedType(); 176 unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0; 177 if (AllocaSize > MaxAlloca) 178 continue; 179 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 180 AS == AMDGPUAS::REGION_ADDRESS) { 181 LocalGEPsSeen++; 182 // Inhibit unroll for local memory if we have seen addressing not to 183 // a variable, most likely we will be unable to combine it. 184 // Do not unroll too deep inner loops for local memory to give a chance 185 // to unroll an outer loop for a more important reason. 186 if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 || 187 (!isa<GlobalVariable>(GEP->getPointerOperand()) && 188 !isa<Argument>(GEP->getPointerOperand()))) 189 continue; 190 LLVM_DEBUG(dbgs() << "Allow unroll runtime for loop:\n" 191 << *L << " due to LDS use.\n"); 192 UP.Runtime = UnrollRuntimeLocal; 193 } 194 195 // Check if GEP depends on a value defined by this loop itself. 196 bool HasLoopDef = false; 197 for (const Value *Op : GEP->operands()) { 198 const Instruction *Inst = dyn_cast<Instruction>(Op); 199 if (!Inst || L->isLoopInvariant(Op)) 200 continue; 201 202 if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) { 203 return SubLoop->contains(Inst); })) 204 continue; 205 HasLoopDef = true; 206 break; 207 } 208 if (!HasLoopDef) 209 continue; 210 211 // We want to do whatever we can to limit the number of alloca 212 // instructions that make it through to the code generator. allocas 213 // require us to use indirect addressing, which is slow and prone to 214 // compiler bugs. If this loop does an address calculation on an 215 // alloca ptr, then we want to use a higher than normal loop unroll 216 // threshold. This will give SROA a better chance to eliminate these 217 // allocas. 218 // 219 // We also want to have more unrolling for local memory to let ds 220 // instructions with different offsets combine. 221 // 222 // Don't use the maximum allowed value here as it will make some 223 // programs way too big. 224 UP.Threshold = Threshold; 225 LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold 226 << " for loop:\n" 227 << *L << " due to " << *GEP << '\n'); 228 if (UP.Threshold >= MaxBoost) 229 return; 230 } 231 232 // If we got a GEP in a small BB from inner loop then increase max trip 233 // count to analyze for better estimation cost in unroll 234 if (L->empty() && BB->size() < UnrollMaxBlockToAnalyze) 235 UP.MaxIterationsCountToAnalyze = 32; 236 } 237 } 238 239 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 240 // The concept of vector registers doesn't really exist. Some packed vector 241 // operations operate on the normal 32-bit registers. 242 return 256; 243 } 244 245 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const { 246 // This is really the number of registers to fill when vectorizing / 247 // interleaving loops, so we lie to avoid trying to use all registers. 248 return getHardwareNumberOfRegisters(Vec) >> 3; 249 } 250 251 unsigned GCNTTIImpl::getRegisterBitWidth(bool Vector) const { 252 return 32; 253 } 254 255 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const { 256 return 32; 257 } 258 259 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize, 260 unsigned ChainSizeInBytes, 261 VectorType *VecTy) const { 262 unsigned VecRegBitWidth = VF * LoadSize; 263 if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32) 264 // TODO: Support element-size less than 32bit? 265 return 128 / LoadSize; 266 267 return VF; 268 } 269 270 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize, 271 unsigned ChainSizeInBytes, 272 VectorType *VecTy) const { 273 unsigned VecRegBitWidth = VF * StoreSize; 274 if (VecRegBitWidth > 128) 275 return 128 / StoreSize; 276 277 return VF; 278 } 279 280 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 281 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 282 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 283 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 284 AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) { 285 return 512; 286 } 287 288 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 289 return 8 * ST->getMaxPrivateElementSize(); 290 291 // Common to flat, global, local and region. Assume for unknown addrspace. 292 return 128; 293 } 294 295 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 296 unsigned Alignment, 297 unsigned AddrSpace) const { 298 // We allow vectorization of flat stores, even though we may need to decompose 299 // them later if they may access private memory. We don't have enough context 300 // here, and legalization can handle it. 301 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 302 return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) && 303 ChainSizeInBytes <= ST->getMaxPrivateElementSize(); 304 } 305 return true; 306 } 307 308 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 309 unsigned Alignment, 310 unsigned AddrSpace) const { 311 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 312 } 313 314 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 315 unsigned Alignment, 316 unsigned AddrSpace) const { 317 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 318 } 319 320 // FIXME: Really we would like to issue multiple 128-bit loads and stores per 321 // iteration. Should we report a larger size and let it legalize? 322 // 323 // FIXME: Should we use narrower types for local/region, or account for when 324 // unaligned access is legal? 325 // 326 // FIXME: This could use fine tuning and microbenchmarks. 327 Type *GCNTTIImpl::getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, 328 unsigned SrcAddrSpace, 329 unsigned DestAddrSpace, 330 unsigned SrcAlign, 331 unsigned DestAlign) const { 332 unsigned MinAlign = std::min(SrcAlign, DestAlign); 333 334 // A (multi-)dword access at an address == 2 (mod 4) will be decomposed by the 335 // hardware into byte accesses. If you assume all alignments are equally 336 // probable, it's more efficient on average to use short accesses for this 337 // case. 338 if (MinAlign == 2) 339 return Type::getInt16Ty(Context); 340 341 // Not all subtargets have 128-bit DS instructions, and we currently don't 342 // form them by default. 343 if (SrcAddrSpace == AMDGPUAS::LOCAL_ADDRESS || 344 SrcAddrSpace == AMDGPUAS::REGION_ADDRESS || 345 DestAddrSpace == AMDGPUAS::LOCAL_ADDRESS || 346 DestAddrSpace == AMDGPUAS::REGION_ADDRESS) { 347 return FixedVectorType::get(Type::getInt32Ty(Context), 2); 348 } 349 350 // Global memory works best with 16-byte accesses. Private memory will also 351 // hit this, although they'll be decomposed. 352 return FixedVectorType::get(Type::getInt32Ty(Context), 4); 353 } 354 355 void GCNTTIImpl::getMemcpyLoopResidualLoweringType( 356 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context, 357 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, 358 unsigned SrcAlign, unsigned DestAlign) const { 359 assert(RemainingBytes < 16); 360 361 unsigned MinAlign = std::min(SrcAlign, DestAlign); 362 363 if (MinAlign != 2) { 364 Type *I64Ty = Type::getInt64Ty(Context); 365 while (RemainingBytes >= 8) { 366 OpsOut.push_back(I64Ty); 367 RemainingBytes -= 8; 368 } 369 370 Type *I32Ty = Type::getInt32Ty(Context); 371 while (RemainingBytes >= 4) { 372 OpsOut.push_back(I32Ty); 373 RemainingBytes -= 4; 374 } 375 } 376 377 Type *I16Ty = Type::getInt16Ty(Context); 378 while (RemainingBytes >= 2) { 379 OpsOut.push_back(I16Ty); 380 RemainingBytes -= 2; 381 } 382 383 Type *I8Ty = Type::getInt8Ty(Context); 384 while (RemainingBytes) { 385 OpsOut.push_back(I8Ty); 386 --RemainingBytes; 387 } 388 } 389 390 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) { 391 // Disable unrolling if the loop is not vectorized. 392 // TODO: Enable this again. 393 if (VF == 1) 394 return 1; 395 396 return 8; 397 } 398 399 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst, 400 MemIntrinsicInfo &Info) const { 401 switch (Inst->getIntrinsicID()) { 402 case Intrinsic::amdgcn_atomic_inc: 403 case Intrinsic::amdgcn_atomic_dec: 404 case Intrinsic::amdgcn_ds_ordered_add: 405 case Intrinsic::amdgcn_ds_ordered_swap: 406 case Intrinsic::amdgcn_ds_fadd: 407 case Intrinsic::amdgcn_ds_fmin: 408 case Intrinsic::amdgcn_ds_fmax: { 409 auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2)); 410 auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4)); 411 if (!Ordering || !Volatile) 412 return false; // Invalid. 413 414 unsigned OrderingVal = Ordering->getZExtValue(); 415 if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent)) 416 return false; 417 418 Info.PtrVal = Inst->getArgOperand(0); 419 Info.Ordering = static_cast<AtomicOrdering>(OrderingVal); 420 Info.ReadMem = true; 421 Info.WriteMem = true; 422 Info.IsVolatile = !Volatile->isNullValue(); 423 return true; 424 } 425 default: 426 return false; 427 } 428 } 429 430 int GCNTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty, 431 TTI::TargetCostKind CostKind, 432 TTI::OperandValueKind Opd1Info, 433 TTI::OperandValueKind Opd2Info, 434 TTI::OperandValueProperties Opd1PropInfo, 435 TTI::OperandValueProperties Opd2PropInfo, 436 ArrayRef<const Value *> Args, 437 const Instruction *CxtI) { 438 EVT OrigTy = TLI->getValueType(DL, Ty); 439 if (!OrigTy.isSimple()) { 440 // FIXME: We're having to query the throughput cost so that the basic 441 // implementation tries to generate legalize and scalarization costs. Maybe 442 // we could hoist the scalarization code here? 443 return BaseT::getArithmeticInstrCost(Opcode, Ty, TTI::TCK_RecipThroughput, 444 Opd1Info, Opd2Info, 445 Opd1PropInfo, Opd2PropInfo); 446 } 447 448 // Legalize the type. 449 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 450 int ISD = TLI->InstructionOpcodeToISD(Opcode); 451 452 // Because we don't have any legal vector operations, but the legal types, we 453 // need to account for split vectors. 454 unsigned NElts = LT.second.isVector() ? 455 LT.second.getVectorNumElements() : 1; 456 457 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 458 459 switch (ISD) { 460 case ISD::SHL: 461 case ISD::SRL: 462 case ISD::SRA: 463 if (SLT == MVT::i64) 464 return get64BitInstrCost() * LT.first * NElts; 465 466 if (ST->has16BitInsts() && SLT == MVT::i16) 467 NElts = (NElts + 1) / 2; 468 469 // i32 470 return getFullRateInstrCost() * LT.first * NElts; 471 case ISD::ADD: 472 case ISD::SUB: 473 case ISD::AND: 474 case ISD::OR: 475 case ISD::XOR: 476 if (SLT == MVT::i64) { 477 // and, or and xor are typically split into 2 VALU instructions. 478 return 2 * getFullRateInstrCost() * LT.first * NElts; 479 } 480 481 if (ST->has16BitInsts() && SLT == MVT::i16) 482 NElts = (NElts + 1) / 2; 483 484 return LT.first * NElts * getFullRateInstrCost(); 485 case ISD::MUL: { 486 const int QuarterRateCost = getQuarterRateInstrCost(); 487 if (SLT == MVT::i64) { 488 const int FullRateCost = getFullRateInstrCost(); 489 return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts; 490 } 491 492 if (ST->has16BitInsts() && SLT == MVT::i16) 493 NElts = (NElts + 1) / 2; 494 495 // i32 496 return QuarterRateCost * NElts * LT.first; 497 } 498 case ISD::FADD: 499 case ISD::FSUB: 500 case ISD::FMUL: 501 if (SLT == MVT::f64) 502 return LT.first * NElts * get64BitInstrCost(); 503 504 if (ST->has16BitInsts() && SLT == MVT::f16) 505 NElts = (NElts + 1) / 2; 506 507 if (SLT == MVT::f32 || SLT == MVT::f16) 508 return LT.first * NElts * getFullRateInstrCost(); 509 break; 510 case ISD::FDIV: 511 case ISD::FREM: 512 // FIXME: frem should be handled separately. The fdiv in it is most of it, 513 // but the current lowering is also not entirely correct. 514 if (SLT == MVT::f64) { 515 int Cost = 4 * get64BitInstrCost() + 7 * getQuarterRateInstrCost(); 516 // Add cost of workaround. 517 if (!ST->hasUsableDivScaleConditionOutput()) 518 Cost += 3 * getFullRateInstrCost(); 519 520 return LT.first * Cost * NElts; 521 } 522 523 if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) { 524 // TODO: This is more complicated, unsafe flags etc. 525 if ((SLT == MVT::f32 && !HasFP32Denormals) || 526 (SLT == MVT::f16 && ST->has16BitInsts())) { 527 return LT.first * getQuarterRateInstrCost() * NElts; 528 } 529 } 530 531 if (SLT == MVT::f16 && ST->has16BitInsts()) { 532 // 2 x v_cvt_f32_f16 533 // f32 rcp 534 // f32 fmul 535 // v_cvt_f16_f32 536 // f16 div_fixup 537 int Cost = 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost(); 538 return LT.first * Cost * NElts; 539 } 540 541 if (SLT == MVT::f32 || SLT == MVT::f16) { 542 int Cost = 7 * getFullRateInstrCost() + 1 * getQuarterRateInstrCost(); 543 544 if (!HasFP32Denormals) { 545 // FP mode switches. 546 Cost += 2 * getFullRateInstrCost(); 547 } 548 549 return LT.first * NElts * Cost; 550 } 551 break; 552 default: 553 break; 554 } 555 556 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, 557 Opd2Info, 558 Opd1PropInfo, Opd2PropInfo); 559 } 560 561 // Return true if there's a potential benefit from using v2f16 instructions for 562 // an intrinsic, even if it requires nontrivial legalization. 563 static bool intrinsicHasPackedVectorBenefit(Intrinsic::ID ID) { 564 switch (ID) { 565 case Intrinsic::fma: // TODO: fmuladd 566 // There's a small benefit to using vector ops in the legalized code. 567 case Intrinsic::round: 568 return true; 569 default: 570 return false; 571 } 572 } 573 574 int GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 575 TTI::TargetCostKind CostKind) { 576 if (ICA.getID() == Intrinsic::fabs) 577 return 0; 578 579 if (!intrinsicHasPackedVectorBenefit(ICA.getID())) 580 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 581 582 Type *RetTy = ICA.getReturnType(); 583 EVT OrigTy = TLI->getValueType(DL, RetTy); 584 if (!OrigTy.isSimple()) { 585 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 586 } 587 588 // Legalize the type. 589 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy); 590 591 unsigned NElts = LT.second.isVector() ? 592 LT.second.getVectorNumElements() : 1; 593 594 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 595 596 if (SLT == MVT::f64) 597 return LT.first * NElts * get64BitInstrCost(); 598 599 if (ST->has16BitInsts() && SLT == MVT::f16) 600 NElts = (NElts + 1) / 2; 601 602 // TODO: Get more refined intrinsic costs? 603 unsigned InstRate = getQuarterRateInstrCost(); 604 if (ICA.getID() == Intrinsic::fma) { 605 InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost() 606 : getQuarterRateInstrCost(); 607 } 608 609 return LT.first * NElts * InstRate; 610 } 611 612 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode, 613 TTI::TargetCostKind CostKind) { 614 // XXX - For some reason this isn't called for switch. 615 switch (Opcode) { 616 case Instruction::Br: 617 case Instruction::Ret: 618 return 10; 619 default: 620 return BaseT::getCFInstrCost(Opcode, CostKind); 621 } 622 } 623 624 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, 625 bool IsPairwise, 626 TTI::TargetCostKind CostKind) { 627 EVT OrigTy = TLI->getValueType(DL, Ty); 628 629 // Computes cost on targets that have packed math instructions(which support 630 // 16-bit types only). 631 if (IsPairwise || 632 !ST->hasVOP3PInsts() || 633 OrigTy.getScalarSizeInBits() != 16) 634 return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise, CostKind); 635 636 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 637 return LT.first * getFullRateInstrCost(); 638 } 639 640 int GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, 641 bool IsPairwise, bool IsUnsigned, 642 TTI::TargetCostKind CostKind) { 643 EVT OrigTy = TLI->getValueType(DL, Ty); 644 645 // Computes cost on targets that have packed math instructions(which support 646 // 16-bit types only). 647 if (IsPairwise || 648 !ST->hasVOP3PInsts() || 649 OrigTy.getScalarSizeInBits() != 16) 650 return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned, 651 CostKind); 652 653 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 654 return LT.first * getHalfRateInstrCost(); 655 } 656 657 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 658 unsigned Index) { 659 switch (Opcode) { 660 case Instruction::ExtractElement: 661 case Instruction::InsertElement: { 662 unsigned EltSize 663 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 664 if (EltSize < 32) { 665 if (EltSize == 16 && Index == 0 && ST->has16BitInsts()) 666 return 0; 667 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 668 } 669 670 // Extracts are just reads of a subregister, so are free. Inserts are 671 // considered free because we don't want to have any cost for scalarizing 672 // operations, and we don't have to copy into a different register class. 673 674 // Dynamic indexing isn't free and is best avoided. 675 return Index == ~0u ? 2 : 0; 676 } 677 default: 678 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 679 } 680 } 681 682 static bool isArgPassedInSGPR(const Argument *A) { 683 const Function *F = A->getParent(); 684 685 // Arguments to compute shaders are never a source of divergence. 686 CallingConv::ID CC = F->getCallingConv(); 687 switch (CC) { 688 case CallingConv::AMDGPU_KERNEL: 689 case CallingConv::SPIR_KERNEL: 690 return true; 691 case CallingConv::AMDGPU_VS: 692 case CallingConv::AMDGPU_LS: 693 case CallingConv::AMDGPU_HS: 694 case CallingConv::AMDGPU_ES: 695 case CallingConv::AMDGPU_GS: 696 case CallingConv::AMDGPU_PS: 697 case CallingConv::AMDGPU_CS: 698 // For non-compute shaders, SGPR inputs are marked with either inreg or byval. 699 // Everything else is in VGPRs. 700 return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg) || 701 F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::ByVal); 702 default: 703 // TODO: Should calls support inreg for SGPR inputs? 704 return false; 705 } 706 } 707 708 /// Analyze if the results of inline asm are divergent. If \p Indices is empty, 709 /// this is analyzing the collective result of all output registers. Otherwise, 710 /// this is only querying a specific result index if this returns multiple 711 /// registers in a struct. 712 bool GCNTTIImpl::isInlineAsmSourceOfDivergence( 713 const CallInst *CI, ArrayRef<unsigned> Indices) const { 714 // TODO: Handle complex extract indices 715 if (Indices.size() > 1) 716 return true; 717 718 const DataLayout &DL = CI->getModule()->getDataLayout(); 719 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 720 TargetLowering::AsmOperandInfoVector TargetConstraints = 721 TLI->ParseConstraints(DL, ST->getRegisterInfo(), *CI); 722 723 const int TargetOutputIdx = Indices.empty() ? -1 : Indices[0]; 724 725 int OutputIdx = 0; 726 for (auto &TC : TargetConstraints) { 727 if (TC.Type != InlineAsm::isOutput) 728 continue; 729 730 // Skip outputs we don't care about. 731 if (TargetOutputIdx != -1 && TargetOutputIdx != OutputIdx++) 732 continue; 733 734 TLI->ComputeConstraintToUse(TC, SDValue()); 735 736 Register AssignedReg; 737 const TargetRegisterClass *RC; 738 std::tie(AssignedReg, RC) = TLI->getRegForInlineAsmConstraint( 739 TRI, TC.ConstraintCode, TC.ConstraintVT); 740 if (AssignedReg) { 741 // FIXME: This is a workaround for getRegForInlineAsmConstraint 742 // returning VS_32 743 RC = TRI->getPhysRegClass(AssignedReg); 744 } 745 746 // For AGPR constraints null is returned on subtargets without AGPRs, so 747 // assume divergent for null. 748 if (!RC || !TRI->isSGPRClass(RC)) 749 return true; 750 } 751 752 return false; 753 } 754 755 /// \returns true if the new GPU divergence analysis is enabled. 756 bool GCNTTIImpl::useGPUDivergenceAnalysis() const { 757 return !UseLegacyDA; 758 } 759 760 /// \returns true if the result of the value could potentially be 761 /// different across workitems in a wavefront. 762 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const { 763 if (const Argument *A = dyn_cast<Argument>(V)) 764 return !isArgPassedInSGPR(A); 765 766 // Loads from the private and flat address spaces are divergent, because 767 // threads can execute the load instruction with the same inputs and get 768 // different results. 769 // 770 // All other loads are not divergent, because if threads issue loads with the 771 // same arguments, they will always get the same result. 772 if (const LoadInst *Load = dyn_cast<LoadInst>(V)) 773 return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS || 774 Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS; 775 776 // Atomics are divergent because they are executed sequentially: when an 777 // atomic operation refers to the same address in each thread, then each 778 // thread after the first sees the value written by the previous thread as 779 // original value. 780 if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V)) 781 return true; 782 783 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) 784 return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID()); 785 786 // Assume all function calls are a source of divergence. 787 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 788 if (CI->isInlineAsm()) 789 return isInlineAsmSourceOfDivergence(CI); 790 return true; 791 } 792 793 // Assume all function calls are a source of divergence. 794 if (isa<InvokeInst>(V)) 795 return true; 796 797 return false; 798 } 799 800 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const { 801 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 802 switch (Intrinsic->getIntrinsicID()) { 803 default: 804 return false; 805 case Intrinsic::amdgcn_readfirstlane: 806 case Intrinsic::amdgcn_readlane: 807 case Intrinsic::amdgcn_icmp: 808 case Intrinsic::amdgcn_fcmp: 809 case Intrinsic::amdgcn_ballot: 810 case Intrinsic::amdgcn_if_break: 811 return true; 812 } 813 } 814 815 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 816 if (CI->isInlineAsm()) 817 return !isInlineAsmSourceOfDivergence(CI); 818 return false; 819 } 820 821 const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V); 822 if (!ExtValue) 823 return false; 824 825 const CallInst *CI = dyn_cast<CallInst>(ExtValue->getOperand(0)); 826 if (!CI) 827 return false; 828 829 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(CI)) { 830 switch (Intrinsic->getIntrinsicID()) { 831 default: 832 return false; 833 case Intrinsic::amdgcn_if: 834 case Intrinsic::amdgcn_else: { 835 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 836 return Indices.size() == 1 && Indices[0] == 1; 837 } 838 } 839 } 840 841 // If we have inline asm returning mixed SGPR and VGPR results, we inferred 842 // divergent for the overall struct return. We need to override it in the 843 // case we're extracting an SGPR component here. 844 if (CI->isInlineAsm()) 845 return !isInlineAsmSourceOfDivergence(CI, ExtValue->getIndices()); 846 847 return false; 848 } 849 850 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes, 851 Intrinsic::ID IID) const { 852 switch (IID) { 853 case Intrinsic::amdgcn_atomic_inc: 854 case Intrinsic::amdgcn_atomic_dec: 855 case Intrinsic::amdgcn_ds_fadd: 856 case Intrinsic::amdgcn_ds_fmin: 857 case Intrinsic::amdgcn_ds_fmax: 858 case Intrinsic::amdgcn_is_shared: 859 case Intrinsic::amdgcn_is_private: 860 OpIndexes.push_back(0); 861 return true; 862 default: 863 return false; 864 } 865 } 866 867 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, 868 Value *OldV, 869 Value *NewV) const { 870 auto IntrID = II->getIntrinsicID(); 871 switch (IntrID) { 872 case Intrinsic::amdgcn_atomic_inc: 873 case Intrinsic::amdgcn_atomic_dec: 874 case Intrinsic::amdgcn_ds_fadd: 875 case Intrinsic::amdgcn_ds_fmin: 876 case Intrinsic::amdgcn_ds_fmax: { 877 const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4)); 878 if (!IsVolatile->isZero()) 879 return nullptr; 880 Module *M = II->getParent()->getParent()->getParent(); 881 Type *DestTy = II->getType(); 882 Type *SrcTy = NewV->getType(); 883 Function *NewDecl = 884 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy}); 885 II->setArgOperand(0, NewV); 886 II->setCalledFunction(NewDecl); 887 return II; 888 } 889 case Intrinsic::amdgcn_is_shared: 890 case Intrinsic::amdgcn_is_private: { 891 unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ? 892 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 893 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 894 LLVMContext &Ctx = NewV->getType()->getContext(); 895 ConstantInt *NewVal = (TrueAS == NewAS) ? 896 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx); 897 return NewVal; 898 } 899 case Intrinsic::ptrmask: { 900 unsigned OldAS = OldV->getType()->getPointerAddressSpace(); 901 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 902 Value *MaskOp = II->getArgOperand(1); 903 Type *MaskTy = MaskOp->getType(); 904 905 bool DoTruncate = false; 906 if (!getTLI()->isNoopAddrSpaceCast(OldAS, NewAS)) { 907 // All valid 64-bit to 32-bit casts work by chopping off the high 908 // bits. Any masking only clearing the low bits will also apply in the new 909 // address space. 910 if (DL.getPointerSizeInBits(OldAS) != 64 || 911 DL.getPointerSizeInBits(NewAS) != 32) 912 return nullptr; 913 914 // TODO: Do we need to thread more context in here? 915 KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II); 916 if (Known.countMinLeadingOnes() < 32) 917 return nullptr; 918 919 DoTruncate = true; 920 } 921 922 IRBuilder<> B(II); 923 if (DoTruncate) { 924 MaskTy = B.getInt32Ty(); 925 MaskOp = B.CreateTrunc(MaskOp, MaskTy); 926 } 927 928 return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy}, 929 {NewV, MaskOp}); 930 } 931 default: 932 return nullptr; 933 } 934 } 935 936 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *VT, 937 int Index, VectorType *SubTp) { 938 if (ST->hasVOP3PInsts()) { 939 if (cast<FixedVectorType>(VT)->getNumElements() == 2 && 940 DL.getTypeSizeInBits(VT->getElementType()) == 16) { 941 // With op_sel VOP3P instructions freely can access the low half or high 942 // half of a register, so any swizzle is free. 943 944 switch (Kind) { 945 case TTI::SK_Broadcast: 946 case TTI::SK_Reverse: 947 case TTI::SK_PermuteSingleSrc: 948 return 0; 949 default: 950 break; 951 } 952 } 953 } 954 955 return BaseT::getShuffleCost(Kind, VT, Index, SubTp); 956 } 957 958 bool GCNTTIImpl::areInlineCompatible(const Function *Caller, 959 const Function *Callee) const { 960 const TargetMachine &TM = getTLI()->getTargetMachine(); 961 const GCNSubtarget *CallerST 962 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller)); 963 const GCNSubtarget *CalleeST 964 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee)); 965 966 const FeatureBitset &CallerBits = CallerST->getFeatureBits(); 967 const FeatureBitset &CalleeBits = CalleeST->getFeatureBits(); 968 969 FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList; 970 FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList; 971 if ((RealCallerBits & RealCalleeBits) != RealCalleeBits) 972 return false; 973 974 // FIXME: dx10_clamp can just take the caller setting, but there seems to be 975 // no way to support merge for backend defined attributes. 976 AMDGPU::SIModeRegisterDefaults CallerMode(*Caller); 977 AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee); 978 return CallerMode.isInlineCompatible(CalleeMode); 979 } 980 981 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 982 TTI::UnrollingPreferences &UP) { 983 CommonTTI.getUnrollingPreferences(L, SE, UP); 984 } 985 986 unsigned 987 GCNTTIImpl::getUserCost(const User *U, ArrayRef<const Value *> Operands, 988 TTI::TargetCostKind CostKind) { 989 const Instruction *I = dyn_cast<Instruction>(U); 990 if (!I) 991 return BaseT::getUserCost(U, Operands, CostKind); 992 993 // Estimate different operations to be optimized out 994 switch (I->getOpcode()) { 995 case Instruction::ExtractElement: { 996 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 997 unsigned Idx = -1; 998 if (CI) 999 Idx = CI->getZExtValue(); 1000 return getVectorInstrCost(I->getOpcode(), I->getOperand(0)->getType(), Idx); 1001 } 1002 case Instruction::FNeg: 1003 return getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind, 1004 TTI::OK_AnyValue, TTI::OK_AnyValue, 1005 TTI::OP_None, TTI::OP_None, Operands, I); 1006 default: 1007 break; 1008 } 1009 1010 return BaseT::getUserCost(U, Operands, CostKind); 1011 } 1012 1013 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 1014 return 4 * 128; // XXX - 4 channels. Should these count as vector instead? 1015 } 1016 1017 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const { 1018 return getHardwareNumberOfRegisters(Vec); 1019 } 1020 1021 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const { 1022 return 32; 1023 } 1024 1025 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const { 1026 return 32; 1027 } 1028 1029 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 1030 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 1031 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) 1032 return 128; 1033 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1034 AddrSpace == AMDGPUAS::REGION_ADDRESS) 1035 return 64; 1036 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 1037 return 32; 1038 1039 if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS || 1040 AddrSpace == AMDGPUAS::PARAM_I_ADDRESS || 1041 (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 && 1042 AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15))) 1043 return 128; 1044 llvm_unreachable("unhandled address space"); 1045 } 1046 1047 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 1048 unsigned Alignment, 1049 unsigned AddrSpace) const { 1050 // We allow vectorization of flat stores, even though we may need to decompose 1051 // them later if they may access private memory. We don't have enough context 1052 // here, and legalization can handle it. 1053 return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS); 1054 } 1055 1056 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 1057 unsigned Alignment, 1058 unsigned AddrSpace) const { 1059 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 1060 } 1061 1062 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 1063 unsigned Alignment, 1064 unsigned AddrSpace) const { 1065 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 1066 } 1067 1068 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) { 1069 // Disable unrolling if the loop is not vectorized. 1070 // TODO: Enable this again. 1071 if (VF == 1) 1072 return 1; 1073 1074 return 8; 1075 } 1076 1077 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode, 1078 TTI::TargetCostKind CostKind) { 1079 // XXX - For some reason this isn't called for switch. 1080 switch (Opcode) { 1081 case Instruction::Br: 1082 case Instruction::Ret: 1083 return 10; 1084 default: 1085 return BaseT::getCFInstrCost(Opcode, CostKind); 1086 } 1087 } 1088 1089 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 1090 unsigned Index) { 1091 switch (Opcode) { 1092 case Instruction::ExtractElement: 1093 case Instruction::InsertElement: { 1094 unsigned EltSize 1095 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 1096 if (EltSize < 32) { 1097 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 1098 } 1099 1100 // Extracts are just reads of a subregister, so are free. Inserts are 1101 // considered free because we don't want to have any cost for scalarizing 1102 // operations, and we don't have to copy into a different register class. 1103 1104 // Dynamic indexing isn't free and is best avoided. 1105 return Index == ~0u ? 2 : 0; 1106 } 1107 default: 1108 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 1109 } 1110 } 1111 1112 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1113 TTI::UnrollingPreferences &UP) { 1114 CommonTTI.getUnrollingPreferences(L, SE, UP); 1115 } 1116