1 //===- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI pass -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // \file 11 // This file implements a TargetTransformInfo analysis pass specific to the 12 // AMDGPU target machine. It uses the target's detailed information to provide 13 // more precise answers to certain TTI queries, while letting the target 14 // independent and default TTI implementations handle the rest. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "AMDGPUTargetTransformInfo.h" 19 #include "AMDGPUSubtarget.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/MachineValueType.h" 26 #include "llvm/CodeGen/ValueTypes.h" 27 #include "llvm/IR/Argument.h" 28 #include "llvm/IR/Attributes.h" 29 #include "llvm/IR/BasicBlock.h" 30 #include "llvm/IR/CallingConv.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/DerivedTypes.h" 33 #include "llvm/IR/Function.h" 34 #include "llvm/IR/Instruction.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/Module.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/raw_ostream.h" 46 #include "llvm/Target/TargetMachine.h" 47 #include <algorithm> 48 #include <cassert> 49 #include <limits> 50 #include <utility> 51 52 using namespace llvm; 53 54 #define DEBUG_TYPE "AMDGPUtti" 55 56 static cl::opt<unsigned> UnrollThresholdPrivate( 57 "amdgpu-unroll-threshold-private", 58 cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"), 59 cl::init(2500), cl::Hidden); 60 61 static cl::opt<unsigned> UnrollThresholdLocal( 62 "amdgpu-unroll-threshold-local", 63 cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"), 64 cl::init(1000), cl::Hidden); 65 66 static cl::opt<unsigned> UnrollThresholdIf( 67 "amdgpu-unroll-threshold-if", 68 cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"), 69 cl::init(150), cl::Hidden); 70 71 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond, 72 unsigned Depth = 0) { 73 const Instruction *I = dyn_cast<Instruction>(Cond); 74 if (!I) 75 return false; 76 77 for (const Value *V : I->operand_values()) { 78 if (!L->contains(I)) 79 continue; 80 if (const PHINode *PHI = dyn_cast<PHINode>(V)) { 81 if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) { 82 return SubLoop->contains(PHI); })) 83 return true; 84 } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1)) 85 return true; 86 } 87 return false; 88 } 89 90 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 91 TTI::UnrollingPreferences &UP) { 92 UP.Threshold = 300; // Twice the default. 93 UP.MaxCount = std::numeric_limits<unsigned>::max(); 94 UP.Partial = true; 95 96 // TODO: Do we want runtime unrolling? 97 98 // Maximum alloca size than can fit registers. Reserve 16 registers. 99 const unsigned MaxAlloca = (256 - 16) * 4; 100 unsigned ThresholdPrivate = UnrollThresholdPrivate; 101 unsigned ThresholdLocal = UnrollThresholdLocal; 102 unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal); 103 AMDGPUAS ASST = ST->getAMDGPUAS(); 104 for (const BasicBlock *BB : L->getBlocks()) { 105 const DataLayout &DL = BB->getModule()->getDataLayout(); 106 unsigned LocalGEPsSeen = 0; 107 108 if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) { 109 return SubLoop->contains(BB); })) 110 continue; // Block belongs to an inner loop. 111 112 for (const Instruction &I : *BB) { 113 // Unroll a loop which contains an "if" statement whose condition 114 // defined by a PHI belonging to the loop. This may help to eliminate 115 // if region and potentially even PHI itself, saving on both divergence 116 // and registers used for the PHI. 117 // Add a small bonus for each of such "if" statements. 118 if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) { 119 if (UP.Threshold < MaxBoost && Br->isConditional()) { 120 if (L->isLoopExiting(Br->getSuccessor(0)) || 121 L->isLoopExiting(Br->getSuccessor(1))) 122 continue; 123 if (dependsOnLocalPhi(L, Br->getCondition())) { 124 UP.Threshold += UnrollThresholdIf; 125 DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold 126 << " for loop:\n" << *L << " due to " << *Br << '\n'); 127 if (UP.Threshold >= MaxBoost) 128 return; 129 } 130 } 131 continue; 132 } 133 134 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I); 135 if (!GEP) 136 continue; 137 138 unsigned AS = GEP->getAddressSpace(); 139 unsigned Threshold = 0; 140 if (AS == ASST.PRIVATE_ADDRESS) 141 Threshold = ThresholdPrivate; 142 else if (AS == ASST.LOCAL_ADDRESS) 143 Threshold = ThresholdLocal; 144 else 145 continue; 146 147 if (UP.Threshold >= Threshold) 148 continue; 149 150 if (AS == ASST.PRIVATE_ADDRESS) { 151 const Value *Ptr = GEP->getPointerOperand(); 152 const AllocaInst *Alloca = 153 dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr, DL)); 154 if (!Alloca || !Alloca->isStaticAlloca()) 155 continue; 156 Type *Ty = Alloca->getAllocatedType(); 157 unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0; 158 if (AllocaSize > MaxAlloca) 159 continue; 160 } else if (AS == ASST.LOCAL_ADDRESS) { 161 LocalGEPsSeen++; 162 // Inhibit unroll for local memory if we have seen addressing not to 163 // a variable, most likely we will be unable to combine it. 164 // Do not unroll too deep inner loops for local memory to give a chance 165 // to unroll an outer loop for a more important reason. 166 if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 || 167 (!isa<GlobalVariable>(GEP->getPointerOperand()) && 168 !isa<Argument>(GEP->getPointerOperand()))) 169 continue; 170 } 171 172 // Check if GEP depends on a value defined by this loop itself. 173 bool HasLoopDef = false; 174 for (const Value *Op : GEP->operands()) { 175 const Instruction *Inst = dyn_cast<Instruction>(Op); 176 if (!Inst || L->isLoopInvariant(Op)) 177 continue; 178 179 if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) { 180 return SubLoop->contains(Inst); })) 181 continue; 182 HasLoopDef = true; 183 break; 184 } 185 if (!HasLoopDef) 186 continue; 187 188 // We want to do whatever we can to limit the number of alloca 189 // instructions that make it through to the code generator. allocas 190 // require us to use indirect addressing, which is slow and prone to 191 // compiler bugs. If this loop does an address calculation on an 192 // alloca ptr, then we want to use a higher than normal loop unroll 193 // threshold. This will give SROA a better chance to eliminate these 194 // allocas. 195 // 196 // We also want to have more unrolling for local memory to let ds 197 // instructions with different offsets combine. 198 // 199 // Don't use the maximum allowed value here as it will make some 200 // programs way too big. 201 UP.Threshold = Threshold; 202 DEBUG(dbgs() << "Set unroll threshold " << Threshold << " for loop:\n" 203 << *L << " due to " << *GEP << '\n'); 204 if (UP.Threshold >= MaxBoost) 205 return; 206 } 207 } 208 } 209 210 unsigned AMDGPUTTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 211 // The concept of vector registers doesn't really exist. Some packed vector 212 // operations operate on the normal 32-bit registers. 213 214 // Number of VGPRs on SI. 215 if (ST->getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) 216 return 256; 217 218 return 4 * 128; // XXX - 4 channels. Should these count as vector instead? 219 } 220 221 unsigned AMDGPUTTIImpl::getNumberOfRegisters(bool Vec) const { 222 // This is really the number of registers to fill when vectorizing / 223 // interleaving loops, so we lie to avoid trying to use all registers. 224 return getHardwareNumberOfRegisters(Vec) >> 3; 225 } 226 227 unsigned AMDGPUTTIImpl::getRegisterBitWidth(bool Vector) const { 228 return 32; 229 } 230 231 unsigned AMDGPUTTIImpl::getMinVectorRegisterBitWidth() const { 232 return 32; 233 } 234 235 unsigned AMDGPUTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 236 AMDGPUAS AS = ST->getAMDGPUAS(); 237 if (AddrSpace == AS.GLOBAL_ADDRESS || 238 AddrSpace == AS.CONSTANT_ADDRESS || 239 AddrSpace == AS.FLAT_ADDRESS) 240 return 128; 241 if (AddrSpace == AS.LOCAL_ADDRESS || 242 AddrSpace == AS.REGION_ADDRESS) 243 return 64; 244 if (AddrSpace == AS.PRIVATE_ADDRESS) 245 return 8 * ST->getMaxPrivateElementSize(); 246 247 if (ST->getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS && 248 (AddrSpace == AS.PARAM_D_ADDRESS || 249 AddrSpace == AS.PARAM_I_ADDRESS || 250 (AddrSpace >= AS.CONSTANT_BUFFER_0 && 251 AddrSpace <= AS.CONSTANT_BUFFER_15))) 252 return 128; 253 llvm_unreachable("unhandled address space"); 254 } 255 256 bool AMDGPUTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 257 unsigned Alignment, 258 unsigned AddrSpace) const { 259 // We allow vectorization of flat stores, even though we may need to decompose 260 // them later if they may access private memory. We don't have enough context 261 // here, and legalization can handle it. 262 if (AddrSpace == ST->getAMDGPUAS().PRIVATE_ADDRESS) { 263 return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) && 264 ChainSizeInBytes <= ST->getMaxPrivateElementSize(); 265 } 266 return true; 267 } 268 269 bool AMDGPUTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 270 unsigned Alignment, 271 unsigned AddrSpace) const { 272 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 273 } 274 275 bool AMDGPUTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 276 unsigned Alignment, 277 unsigned AddrSpace) const { 278 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 279 } 280 281 unsigned AMDGPUTTIImpl::getMaxInterleaveFactor(unsigned VF) { 282 // Disable unrolling if the loop is not vectorized. 283 // TODO: Enable this again. 284 if (VF == 1) 285 return 1; 286 287 return 8; 288 } 289 290 int AMDGPUTTIImpl::getArithmeticInstrCost( 291 unsigned Opcode, Type *Ty, TTI::OperandValueKind Opd1Info, 292 TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo, 293 TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args ) { 294 EVT OrigTy = TLI->getValueType(DL, Ty); 295 if (!OrigTy.isSimple()) { 296 return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, 297 Opd1PropInfo, Opd2PropInfo); 298 } 299 300 // Legalize the type. 301 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 302 int ISD = TLI->InstructionOpcodeToISD(Opcode); 303 304 // Because we don't have any legal vector operations, but the legal types, we 305 // need to account for split vectors. 306 unsigned NElts = LT.second.isVector() ? 307 LT.second.getVectorNumElements() : 1; 308 309 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 310 311 switch (ISD) { 312 case ISD::SHL: 313 case ISD::SRL: 314 case ISD::SRA: 315 if (SLT == MVT::i64) 316 return get64BitInstrCost() * LT.first * NElts; 317 318 // i32 319 return getFullRateInstrCost() * LT.first * NElts; 320 case ISD::ADD: 321 case ISD::SUB: 322 case ISD::AND: 323 case ISD::OR: 324 case ISD::XOR: 325 if (SLT == MVT::i64){ 326 // and, or and xor are typically split into 2 VALU instructions. 327 return 2 * getFullRateInstrCost() * LT.first * NElts; 328 } 329 330 return LT.first * NElts * getFullRateInstrCost(); 331 case ISD::MUL: { 332 const int QuarterRateCost = getQuarterRateInstrCost(); 333 if (SLT == MVT::i64) { 334 const int FullRateCost = getFullRateInstrCost(); 335 return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts; 336 } 337 338 // i32 339 return QuarterRateCost * NElts * LT.first; 340 } 341 case ISD::FADD: 342 case ISD::FSUB: 343 case ISD::FMUL: 344 if (SLT == MVT::f64) 345 return LT.first * NElts * get64BitInstrCost(); 346 347 if (SLT == MVT::f32 || SLT == MVT::f16) 348 return LT.first * NElts * getFullRateInstrCost(); 349 break; 350 case ISD::FDIV: 351 case ISD::FREM: 352 // FIXME: frem should be handled separately. The fdiv in it is most of it, 353 // but the current lowering is also not entirely correct. 354 if (SLT == MVT::f64) { 355 int Cost = 4 * get64BitInstrCost() + 7 * getQuarterRateInstrCost(); 356 357 // Add cost of workaround. 358 if (ST->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) 359 Cost += 3 * getFullRateInstrCost(); 360 361 return LT.first * Cost * NElts; 362 } 363 364 // Assuming no fp32 denormals lowering. 365 if (SLT == MVT::f32 || SLT == MVT::f16) { 366 assert(!ST->hasFP32Denormals() && "will change when supported"); 367 int Cost = 7 * getFullRateInstrCost() + 1 * getQuarterRateInstrCost(); 368 return LT.first * NElts * Cost; 369 } 370 break; 371 default: 372 break; 373 } 374 375 return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, 376 Opd1PropInfo, Opd2PropInfo); 377 } 378 379 unsigned AMDGPUTTIImpl::getCFInstrCost(unsigned Opcode) { 380 // XXX - For some reason this isn't called for switch. 381 switch (Opcode) { 382 case Instruction::Br: 383 case Instruction::Ret: 384 return 10; 385 default: 386 return BaseT::getCFInstrCost(Opcode); 387 } 388 } 389 390 int AMDGPUTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 391 unsigned Index) { 392 switch (Opcode) { 393 case Instruction::ExtractElement: 394 case Instruction::InsertElement: { 395 unsigned EltSize 396 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 397 if (EltSize < 32) { 398 if (EltSize == 16 && Index == 0 && ST->has16BitInsts()) 399 return 0; 400 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 401 } 402 403 // Extracts are just reads of a subregister, so are free. Inserts are 404 // considered free because we don't want to have any cost for scalarizing 405 // operations, and we don't have to copy into a different register class. 406 407 // Dynamic indexing isn't free and is best avoided. 408 return Index == ~0u ? 2 : 0; 409 } 410 default: 411 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 412 } 413 } 414 415 static bool isIntrinsicSourceOfDivergence(const IntrinsicInst *I) { 416 switch (I->getIntrinsicID()) { 417 case Intrinsic::amdgcn_workitem_id_x: 418 case Intrinsic::amdgcn_workitem_id_y: 419 case Intrinsic::amdgcn_workitem_id_z: 420 case Intrinsic::amdgcn_interp_mov: 421 case Intrinsic::amdgcn_interp_p1: 422 case Intrinsic::amdgcn_interp_p2: 423 case Intrinsic::amdgcn_mbcnt_hi: 424 case Intrinsic::amdgcn_mbcnt_lo: 425 case Intrinsic::r600_read_tidig_x: 426 case Intrinsic::r600_read_tidig_y: 427 case Intrinsic::r600_read_tidig_z: 428 case Intrinsic::amdgcn_atomic_inc: 429 case Intrinsic::amdgcn_atomic_dec: 430 case Intrinsic::amdgcn_image_atomic_swap: 431 case Intrinsic::amdgcn_image_atomic_add: 432 case Intrinsic::amdgcn_image_atomic_sub: 433 case Intrinsic::amdgcn_image_atomic_smin: 434 case Intrinsic::amdgcn_image_atomic_umin: 435 case Intrinsic::amdgcn_image_atomic_smax: 436 case Intrinsic::amdgcn_image_atomic_umax: 437 case Intrinsic::amdgcn_image_atomic_and: 438 case Intrinsic::amdgcn_image_atomic_or: 439 case Intrinsic::amdgcn_image_atomic_xor: 440 case Intrinsic::amdgcn_image_atomic_inc: 441 case Intrinsic::amdgcn_image_atomic_dec: 442 case Intrinsic::amdgcn_image_atomic_cmpswap: 443 case Intrinsic::amdgcn_buffer_atomic_swap: 444 case Intrinsic::amdgcn_buffer_atomic_add: 445 case Intrinsic::amdgcn_buffer_atomic_sub: 446 case Intrinsic::amdgcn_buffer_atomic_smin: 447 case Intrinsic::amdgcn_buffer_atomic_umin: 448 case Intrinsic::amdgcn_buffer_atomic_smax: 449 case Intrinsic::amdgcn_buffer_atomic_umax: 450 case Intrinsic::amdgcn_buffer_atomic_and: 451 case Intrinsic::amdgcn_buffer_atomic_or: 452 case Intrinsic::amdgcn_buffer_atomic_xor: 453 case Intrinsic::amdgcn_buffer_atomic_cmpswap: 454 case Intrinsic::amdgcn_ps_live: 455 case Intrinsic::amdgcn_ds_swizzle: 456 return true; 457 default: 458 return false; 459 } 460 } 461 462 static bool isArgPassedInSGPR(const Argument *A) { 463 const Function *F = A->getParent(); 464 465 // Arguments to compute shaders are never a source of divergence. 466 CallingConv::ID CC = F->getCallingConv(); 467 switch (CC) { 468 case CallingConv::AMDGPU_KERNEL: 469 case CallingConv::SPIR_KERNEL: 470 return true; 471 case CallingConv::AMDGPU_VS: 472 case CallingConv::AMDGPU_HS: 473 case CallingConv::AMDGPU_GS: 474 case CallingConv::AMDGPU_PS: 475 case CallingConv::AMDGPU_CS: 476 // For non-compute shaders, SGPR inputs are marked with either inreg or byval. 477 // Everything else is in VGPRs. 478 return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg) || 479 F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::ByVal); 480 default: 481 // TODO: Should calls support inreg for SGPR inputs? 482 return false; 483 } 484 } 485 486 /// \returns true if the result of the value could potentially be 487 /// different across workitems in a wavefront. 488 bool AMDGPUTTIImpl::isSourceOfDivergence(const Value *V) const { 489 if (const Argument *A = dyn_cast<Argument>(V)) 490 return !isArgPassedInSGPR(A); 491 492 // Loads from the private address space are divergent, because threads 493 // can execute the load instruction with the same inputs and get different 494 // results. 495 // 496 // All other loads are not divergent, because if threads issue loads with the 497 // same arguments, they will always get the same result. 498 if (const LoadInst *Load = dyn_cast<LoadInst>(V)) 499 return Load->getPointerAddressSpace() == ST->getAMDGPUAS().PRIVATE_ADDRESS; 500 501 // Atomics are divergent because they are executed sequentially: when an 502 // atomic operation refers to the same address in each thread, then each 503 // thread after the first sees the value written by the previous thread as 504 // original value. 505 if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V)) 506 return true; 507 508 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) 509 return isIntrinsicSourceOfDivergence(Intrinsic); 510 511 // Assume all function calls are a source of divergence. 512 if (isa<CallInst>(V) || isa<InvokeInst>(V)) 513 return true; 514 515 return false; 516 } 517 518 bool AMDGPUTTIImpl::isAlwaysUniform(const Value *V) const { 519 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 520 switch (Intrinsic->getIntrinsicID()) { 521 default: 522 return false; 523 case Intrinsic::amdgcn_readfirstlane: 524 case Intrinsic::amdgcn_readlane: 525 return true; 526 } 527 } 528 return false; 529 } 530 531 unsigned AMDGPUTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index, 532 Type *SubTp) { 533 if (ST->hasVOP3PInsts()) { 534 VectorType *VT = cast<VectorType>(Tp); 535 if (VT->getNumElements() == 2 && 536 DL.getTypeSizeInBits(VT->getElementType()) == 16) { 537 // With op_sel VOP3P instructions freely can access the low half or high 538 // half of a register, so any swizzle is free. 539 540 switch (Kind) { 541 case TTI::SK_Broadcast: 542 case TTI::SK_Reverse: 543 case TTI::SK_PermuteSingleSrc: 544 return 0; 545 default: 546 break; 547 } 548 } 549 } 550 551 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp); 552 } 553 554 bool AMDGPUTTIImpl::areInlineCompatible(const Function *Caller, 555 const Function *Callee) const { 556 const TargetMachine &TM = getTLI()->getTargetMachine(); 557 const FeatureBitset &CallerBits = 558 TM.getSubtargetImpl(*Caller)->getFeatureBits(); 559 const FeatureBitset &CalleeBits = 560 TM.getSubtargetImpl(*Callee)->getFeatureBits(); 561 562 FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList; 563 FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList; 564 return ((RealCallerBits & RealCalleeBits) == RealCalleeBits); 565 } 566