1 //===-- AMDGPUSubtarget.cpp - AMDGPU Subtarget Information ----------------===// 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 /// Implements the AMDGPU specific subclass of TargetSubtarget. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AMDGPUSubtarget.h" 15 #include "AMDGPUCallLowering.h" 16 #include "AMDGPUInstructionSelector.h" 17 #include "AMDGPULegalizerInfo.h" 18 #include "AMDGPURegisterBankInfo.h" 19 #include "AMDGPUTargetMachine.h" 20 #include "R600Subtarget.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "Utils/AMDGPUBaseInfo.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h" 25 #include "llvm/CodeGen/MachineScheduler.h" 26 #include "llvm/CodeGen/TargetFrameLowering.h" 27 #include "llvm/IR/IntrinsicsAMDGPU.h" 28 #include "llvm/IR/IntrinsicsR600.h" 29 #include "llvm/IR/MDBuilder.h" 30 #include "llvm/MC/MCSubtargetInfo.h" 31 #include <algorithm> 32 33 using namespace llvm; 34 35 #define DEBUG_TYPE "amdgpu-subtarget" 36 37 #define GET_SUBTARGETINFO_TARGET_DESC 38 #define GET_SUBTARGETINFO_CTOR 39 #define AMDGPUSubtarget GCNSubtarget 40 #include "AMDGPUGenSubtargetInfo.inc" 41 #undef AMDGPUSubtarget 42 43 static cl::opt<bool> EnablePowerSched( 44 "amdgpu-enable-power-sched", 45 cl::desc("Enable scheduling to minimize mAI power bursts"), 46 cl::init(false)); 47 48 static cl::opt<bool> EnableVGPRIndexMode( 49 "amdgpu-vgpr-index-mode", 50 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 51 cl::init(false)); 52 53 static cl::opt<bool> UseAA("amdgpu-use-aa-in-codegen", 54 cl::desc("Enable the use of AA during codegen."), 55 cl::init(true)); 56 57 static cl::opt<unsigned> NSAThreshold("amdgpu-nsa-threshold", 58 cl::desc("Number of addresses from which to enable MIMG NSA."), 59 cl::init(3), cl::Hidden); 60 61 GCNSubtarget::~GCNSubtarget() = default; 62 63 GCNSubtarget & 64 GCNSubtarget::initializeSubtargetDependencies(const Triple &TT, 65 StringRef GPU, StringRef FS) { 66 // Determine default and user-specified characteristics 67 // 68 // We want to be able to turn these off, but making this a subtarget feature 69 // for SI has the unhelpful behavior that it unsets everything else if you 70 // disable it. 71 // 72 // Similarly we want enable-prt-strict-null to be on by default and not to 73 // unset everything else if it is disabled 74 75 SmallString<256> FullFS("+promote-alloca,+load-store-opt,+enable-ds128,"); 76 77 // Turn on features that HSA ABI requires. Also turn on FlatForGlobal by default 78 if (isAmdHsaOS()) 79 FullFS += "+flat-for-global,+unaligned-access-mode,+trap-handler,"; 80 81 FullFS += "+enable-prt-strict-null,"; // This is overridden by a disable in FS 82 83 // Disable mutually exclusive bits. 84 if (FS.contains_insensitive("+wavefrontsize")) { 85 if (!FS.contains_insensitive("wavefrontsize16")) 86 FullFS += "-wavefrontsize16,"; 87 if (!FS.contains_insensitive("wavefrontsize32")) 88 FullFS += "-wavefrontsize32,"; 89 if (!FS.contains_insensitive("wavefrontsize64")) 90 FullFS += "-wavefrontsize64,"; 91 } 92 93 FullFS += FS; 94 95 ParseSubtargetFeatures(GPU, /*TuneCPU*/ GPU, FullFS); 96 97 // Implement the "generic" processors, which acts as the default when no 98 // generation features are enabled (e.g for -mcpu=''). HSA OS defaults to 99 // the first amdgcn target that supports flat addressing. Other OSes defaults 100 // to the first amdgcn target. 101 if (Gen == AMDGPUSubtarget::INVALID) { 102 Gen = TT.getOS() == Triple::AMDHSA ? AMDGPUSubtarget::SEA_ISLANDS 103 : AMDGPUSubtarget::SOUTHERN_ISLANDS; 104 } 105 106 // We don't support FP64 for EG/NI atm. 107 assert(!hasFP64() || (getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS)); 108 109 // Targets must either support 64-bit offsets for MUBUF instructions, and/or 110 // support flat operations, otherwise they cannot access a 64-bit global 111 // address space 112 assert(hasAddr64() || hasFlat()); 113 // Unless +-flat-for-global is specified, turn on FlatForGlobal for targets 114 // that do not support ADDR64 variants of MUBUF instructions. Such targets 115 // cannot use a 64 bit offset with a MUBUF instruction to access the global 116 // address space 117 if (!hasAddr64() && !FS.contains("flat-for-global") && !FlatForGlobal) { 118 ToggleFeature(AMDGPU::FeatureFlatForGlobal); 119 FlatForGlobal = true; 120 } 121 // Unless +-flat-for-global is specified, use MUBUF instructions for global 122 // address space access if flat operations are not available. 123 if (!hasFlat() && !FS.contains("flat-for-global") && FlatForGlobal) { 124 ToggleFeature(AMDGPU::FeatureFlatForGlobal); 125 FlatForGlobal = false; 126 } 127 128 // Set defaults if needed. 129 if (MaxPrivateElementSize == 0) 130 MaxPrivateElementSize = 4; 131 132 if (LDSBankCount == 0) 133 LDSBankCount = 32; 134 135 if (TT.getArch() == Triple::amdgcn) { 136 if (LocalMemorySize == 0) 137 LocalMemorySize = 32768; 138 139 // Do something sensible for unspecified target. 140 if (!HasMovrel && !HasVGPRIndexMode) 141 HasMovrel = true; 142 } 143 144 AddressableLocalMemorySize = LocalMemorySize; 145 146 if (AMDGPU::isGFX10Plus(*this) && 147 !getFeatureBits().test(AMDGPU::FeatureCuMode)) 148 LocalMemorySize *= 2; 149 150 // Don't crash on invalid devices. 151 if (WavefrontSizeLog2 == 0) 152 WavefrontSizeLog2 = 5; 153 154 HasFminFmaxLegacy = getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS; 155 HasSMulHi = getGeneration() >= AMDGPUSubtarget::GFX9; 156 157 TargetID.setTargetIDFromFeaturesString(FS); 158 159 LLVM_DEBUG(dbgs() << "xnack setting for subtarget: " 160 << TargetID.getXnackSetting() << '\n'); 161 LLVM_DEBUG(dbgs() << "sramecc setting for subtarget: " 162 << TargetID.getSramEccSetting() << '\n'); 163 164 return *this; 165 } 166 167 AMDGPUSubtarget::AMDGPUSubtarget(const Triple &TT) : TargetTriple(TT) {} 168 169 GCNSubtarget::GCNSubtarget(const Triple &TT, StringRef GPU, StringRef FS, 170 const GCNTargetMachine &TM) 171 : // clang-format off 172 AMDGPUGenSubtargetInfo(TT, GPU, /*TuneCPU*/ GPU, FS), 173 AMDGPUSubtarget(TT), 174 TargetTriple(TT), 175 TargetID(*this), 176 InstrItins(getInstrItineraryForCPU(GPU)), 177 InstrInfo(initializeSubtargetDependencies(TT, GPU, FS)), 178 TLInfo(TM, *this), 179 FrameLowering(TargetFrameLowering::StackGrowsUp, getStackAlignment(), 0) { 180 // clang-format on 181 MaxWavesPerEU = AMDGPU::IsaInfo::getMaxWavesPerEU(this); 182 EUsPerCU = AMDGPU::IsaInfo::getEUsPerCU(this); 183 CallLoweringInfo.reset(new AMDGPUCallLowering(*getTargetLowering())); 184 InlineAsmLoweringInfo.reset(new InlineAsmLowering(getTargetLowering())); 185 Legalizer.reset(new AMDGPULegalizerInfo(*this, TM)); 186 RegBankInfo.reset(new AMDGPURegisterBankInfo(*this)); 187 InstSelector.reset(new AMDGPUInstructionSelector( 188 *this, *static_cast<AMDGPURegisterBankInfo *>(RegBankInfo.get()), TM)); 189 } 190 191 unsigned GCNSubtarget::getConstantBusLimit(unsigned Opcode) const { 192 if (getGeneration() < GFX10) 193 return 1; 194 195 switch (Opcode) { 196 case AMDGPU::V_LSHLREV_B64_e64: 197 case AMDGPU::V_LSHLREV_B64_gfx10: 198 case AMDGPU::V_LSHLREV_B64_e64_gfx11: 199 case AMDGPU::V_LSHL_B64_e64: 200 case AMDGPU::V_LSHRREV_B64_e64: 201 case AMDGPU::V_LSHRREV_B64_gfx10: 202 case AMDGPU::V_LSHRREV_B64_e64_gfx11: 203 case AMDGPU::V_LSHR_B64_e64: 204 case AMDGPU::V_ASHRREV_I64_e64: 205 case AMDGPU::V_ASHRREV_I64_gfx10: 206 case AMDGPU::V_ASHRREV_I64_e64_gfx11: 207 case AMDGPU::V_ASHR_I64_e64: 208 return 1; 209 } 210 211 return 2; 212 } 213 214 /// This list was mostly derived from experimentation. 215 bool GCNSubtarget::zeroesHigh16BitsOfDest(unsigned Opcode) const { 216 switch (Opcode) { 217 case AMDGPU::V_CVT_F16_F32_e32: 218 case AMDGPU::V_CVT_F16_F32_e64: 219 case AMDGPU::V_CVT_F16_U16_e32: 220 case AMDGPU::V_CVT_F16_U16_e64: 221 case AMDGPU::V_CVT_F16_I16_e32: 222 case AMDGPU::V_CVT_F16_I16_e64: 223 case AMDGPU::V_RCP_F16_e64: 224 case AMDGPU::V_RCP_F16_e32: 225 case AMDGPU::V_RSQ_F16_e64: 226 case AMDGPU::V_RSQ_F16_e32: 227 case AMDGPU::V_SQRT_F16_e64: 228 case AMDGPU::V_SQRT_F16_e32: 229 case AMDGPU::V_LOG_F16_e64: 230 case AMDGPU::V_LOG_F16_e32: 231 case AMDGPU::V_EXP_F16_e64: 232 case AMDGPU::V_EXP_F16_e32: 233 case AMDGPU::V_SIN_F16_e64: 234 case AMDGPU::V_SIN_F16_e32: 235 case AMDGPU::V_COS_F16_e64: 236 case AMDGPU::V_COS_F16_e32: 237 case AMDGPU::V_FLOOR_F16_e64: 238 case AMDGPU::V_FLOOR_F16_e32: 239 case AMDGPU::V_CEIL_F16_e64: 240 case AMDGPU::V_CEIL_F16_e32: 241 case AMDGPU::V_TRUNC_F16_e64: 242 case AMDGPU::V_TRUNC_F16_e32: 243 case AMDGPU::V_RNDNE_F16_e64: 244 case AMDGPU::V_RNDNE_F16_e32: 245 case AMDGPU::V_FRACT_F16_e64: 246 case AMDGPU::V_FRACT_F16_e32: 247 case AMDGPU::V_FREXP_MANT_F16_e64: 248 case AMDGPU::V_FREXP_MANT_F16_e32: 249 case AMDGPU::V_FREXP_EXP_I16_F16_e64: 250 case AMDGPU::V_FREXP_EXP_I16_F16_e32: 251 case AMDGPU::V_LDEXP_F16_e64: 252 case AMDGPU::V_LDEXP_F16_e32: 253 case AMDGPU::V_LSHLREV_B16_e64: 254 case AMDGPU::V_LSHLREV_B16_e32: 255 case AMDGPU::V_LSHRREV_B16_e64: 256 case AMDGPU::V_LSHRREV_B16_e32: 257 case AMDGPU::V_ASHRREV_I16_e64: 258 case AMDGPU::V_ASHRREV_I16_e32: 259 case AMDGPU::V_ADD_U16_e64: 260 case AMDGPU::V_ADD_U16_e32: 261 case AMDGPU::V_SUB_U16_e64: 262 case AMDGPU::V_SUB_U16_e32: 263 case AMDGPU::V_SUBREV_U16_e64: 264 case AMDGPU::V_SUBREV_U16_e32: 265 case AMDGPU::V_MUL_LO_U16_e64: 266 case AMDGPU::V_MUL_LO_U16_e32: 267 case AMDGPU::V_ADD_F16_e64: 268 case AMDGPU::V_ADD_F16_e32: 269 case AMDGPU::V_SUB_F16_e64: 270 case AMDGPU::V_SUB_F16_e32: 271 case AMDGPU::V_SUBREV_F16_e64: 272 case AMDGPU::V_SUBREV_F16_e32: 273 case AMDGPU::V_MUL_F16_e64: 274 case AMDGPU::V_MUL_F16_e32: 275 case AMDGPU::V_MAX_F16_e64: 276 case AMDGPU::V_MAX_F16_e32: 277 case AMDGPU::V_MIN_F16_e64: 278 case AMDGPU::V_MIN_F16_e32: 279 case AMDGPU::V_MAX_U16_e64: 280 case AMDGPU::V_MAX_U16_e32: 281 case AMDGPU::V_MIN_U16_e64: 282 case AMDGPU::V_MIN_U16_e32: 283 case AMDGPU::V_MAX_I16_e64: 284 case AMDGPU::V_MAX_I16_e32: 285 case AMDGPU::V_MIN_I16_e64: 286 case AMDGPU::V_MIN_I16_e32: 287 case AMDGPU::V_MAD_F16_e64: 288 case AMDGPU::V_MAD_U16_e64: 289 case AMDGPU::V_MAD_I16_e64: 290 case AMDGPU::V_FMA_F16_e64: 291 case AMDGPU::V_DIV_FIXUP_F16_e64: 292 // On gfx10, all 16-bit instructions preserve the high bits. 293 return getGeneration() <= AMDGPUSubtarget::GFX9; 294 case AMDGPU::V_MADAK_F16: 295 case AMDGPU::V_MADMK_F16: 296 case AMDGPU::V_MAC_F16_e64: 297 case AMDGPU::V_MAC_F16_e32: 298 case AMDGPU::V_FMAMK_F16: 299 case AMDGPU::V_FMAAK_F16: 300 case AMDGPU::V_FMAC_F16_e64: 301 case AMDGPU::V_FMAC_F16_e32: 302 // In gfx9, the preferred handling of the unused high 16-bits changed. Most 303 // instructions maintain the legacy behavior of 0ing. Some instructions 304 // changed to preserving the high bits. 305 return getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS; 306 case AMDGPU::V_MAD_MIXLO_F16: 307 case AMDGPU::V_MAD_MIXHI_F16: 308 default: 309 return false; 310 } 311 } 312 313 // Returns the maximum per-workgroup LDS allocation size (in bytes) that still 314 // allows the given function to achieve an occupancy of NWaves waves per 315 // SIMD / EU, taking into account only the function's *maximum* workgroup size. 316 unsigned 317 AMDGPUSubtarget::getMaxLocalMemSizeWithWaveCount(unsigned NWaves, 318 const Function &F) const { 319 const unsigned WaveSize = getWavefrontSize(); 320 const unsigned WorkGroupSize = getFlatWorkGroupSizes(F).second; 321 const unsigned WavesPerWorkgroup = 322 std::max(1u, (WorkGroupSize + WaveSize - 1) / WaveSize); 323 324 const unsigned WorkGroupsPerCU = 325 std::max(1u, (NWaves * getEUsPerCU()) / WavesPerWorkgroup); 326 327 return getLocalMemorySize() / WorkGroupsPerCU; 328 } 329 330 // FIXME: Should return min,max range. 331 // 332 // Returns the maximum occupancy, in number of waves per SIMD / EU, that can 333 // be achieved when only the given function is running on the machine; and 334 // taking into account the overall number of wave slots, the (maximum) workgroup 335 // size, and the per-workgroup LDS allocation size. 336 unsigned AMDGPUSubtarget::getOccupancyWithLocalMemSize(uint32_t Bytes, 337 const Function &F) const { 338 const unsigned MaxWorkGroupSize = getFlatWorkGroupSizes(F).second; 339 const unsigned MaxWorkGroupsPerCu = getMaxWorkGroupsPerCU(MaxWorkGroupSize); 340 if (!MaxWorkGroupsPerCu) 341 return 0; 342 343 const unsigned WaveSize = getWavefrontSize(); 344 345 // FIXME: Do we need to account for alignment requirement of LDS rounding the 346 // size up? 347 // Compute restriction based on LDS usage 348 unsigned NumGroups = getLocalMemorySize() / (Bytes ? Bytes : 1u); 349 350 // This can be queried with more LDS than is possible, so just assume the 351 // worst. 352 if (NumGroups == 0) 353 return 1; 354 355 NumGroups = std::min(MaxWorkGroupsPerCu, NumGroups); 356 357 // Round to the number of waves per CU. 358 const unsigned MaxGroupNumWaves = divideCeil(MaxWorkGroupSize, WaveSize); 359 unsigned MaxWaves = NumGroups * MaxGroupNumWaves; 360 361 // Number of waves per EU (SIMD). 362 MaxWaves = divideCeil(MaxWaves, getEUsPerCU()); 363 364 // Clamp to the maximum possible number of waves. 365 MaxWaves = std::min(MaxWaves, getMaxWavesPerEU()); 366 367 // FIXME: Needs to be a multiple of the group size? 368 //MaxWaves = MaxGroupNumWaves * (MaxWaves / MaxGroupNumWaves); 369 370 assert(MaxWaves > 0 && MaxWaves <= getMaxWavesPerEU() && 371 "computed invalid occupancy"); 372 return MaxWaves; 373 } 374 375 unsigned 376 AMDGPUSubtarget::getOccupancyWithLocalMemSize(const MachineFunction &MF) const { 377 const auto *MFI = MF.getInfo<SIMachineFunctionInfo>(); 378 return getOccupancyWithLocalMemSize(MFI->getLDSSize(), MF.getFunction()); 379 } 380 381 std::pair<unsigned, unsigned> 382 AMDGPUSubtarget::getDefaultFlatWorkGroupSize(CallingConv::ID CC) const { 383 switch (CC) { 384 case CallingConv::AMDGPU_VS: 385 case CallingConv::AMDGPU_LS: 386 case CallingConv::AMDGPU_HS: 387 case CallingConv::AMDGPU_ES: 388 case CallingConv::AMDGPU_GS: 389 case CallingConv::AMDGPU_PS: 390 return std::pair(1, getWavefrontSize()); 391 default: 392 return std::pair(1u, getMaxFlatWorkGroupSize()); 393 } 394 } 395 396 std::pair<unsigned, unsigned> AMDGPUSubtarget::getFlatWorkGroupSizes( 397 const Function &F) const { 398 // Default minimum/maximum flat work group sizes. 399 std::pair<unsigned, unsigned> Default = 400 getDefaultFlatWorkGroupSize(F.getCallingConv()); 401 402 // Requested minimum/maximum flat work group sizes. 403 std::pair<unsigned, unsigned> Requested = AMDGPU::getIntegerPairAttribute( 404 F, "amdgpu-flat-work-group-size", Default); 405 406 // Make sure requested minimum is less than requested maximum. 407 if (Requested.first > Requested.second) 408 return Default; 409 410 // Make sure requested values do not violate subtarget's specifications. 411 if (Requested.first < getMinFlatWorkGroupSize()) 412 return Default; 413 if (Requested.second > getMaxFlatWorkGroupSize()) 414 return Default; 415 416 return Requested; 417 } 418 419 std::pair<unsigned, unsigned> AMDGPUSubtarget::getEffectiveWavesPerEU( 420 std::pair<unsigned, unsigned> Requested, 421 std::pair<unsigned, unsigned> FlatWorkGroupSizes) const { 422 // Default minimum/maximum number of waves per execution unit. 423 std::pair<unsigned, unsigned> Default(1, getMaxWavesPerEU()); 424 425 // If minimum/maximum flat work group sizes were explicitly requested using 426 // "amdgpu-flat-work-group-size" attribute, then set default minimum/maximum 427 // number of waves per execution unit to values implied by requested 428 // minimum/maximum flat work group sizes. 429 unsigned MinImpliedByFlatWorkGroupSize = 430 getWavesPerEUForWorkGroup(FlatWorkGroupSizes.second); 431 Default.first = MinImpliedByFlatWorkGroupSize; 432 433 // Make sure requested minimum is less than requested maximum. 434 if (Requested.second && Requested.first > Requested.second) 435 return Default; 436 437 // Make sure requested values do not violate subtarget's specifications. 438 if (Requested.first < getMinWavesPerEU() || 439 Requested.second > getMaxWavesPerEU()) 440 return Default; 441 442 // Make sure requested values are compatible with values implied by requested 443 // minimum/maximum flat work group sizes. 444 if (Requested.first < MinImpliedByFlatWorkGroupSize) 445 return Default; 446 447 return Requested; 448 } 449 450 std::pair<unsigned, unsigned> AMDGPUSubtarget::getWavesPerEU( 451 const Function &F, std::pair<unsigned, unsigned> FlatWorkGroupSizes) const { 452 // Default minimum/maximum number of waves per execution unit. 453 std::pair<unsigned, unsigned> Default(1, getMaxWavesPerEU()); 454 455 // Requested minimum/maximum number of waves per execution unit. 456 std::pair<unsigned, unsigned> Requested = 457 AMDGPU::getIntegerPairAttribute(F, "amdgpu-waves-per-eu", Default, true); 458 return getEffectiveWavesPerEU(Requested, FlatWorkGroupSizes); 459 } 460 461 static unsigned getReqdWorkGroupSize(const Function &Kernel, unsigned Dim) { 462 auto Node = Kernel.getMetadata("reqd_work_group_size"); 463 if (Node && Node->getNumOperands() == 3) 464 return mdconst::extract<ConstantInt>(Node->getOperand(Dim))->getZExtValue(); 465 return std::numeric_limits<unsigned>::max(); 466 } 467 468 bool AMDGPUSubtarget::isMesaKernel(const Function &F) const { 469 return isMesa3DOS() && !AMDGPU::isShader(F.getCallingConv()); 470 } 471 472 unsigned AMDGPUSubtarget::getMaxWorkitemID(const Function &Kernel, 473 unsigned Dimension) const { 474 unsigned ReqdSize = getReqdWorkGroupSize(Kernel, Dimension); 475 if (ReqdSize != std::numeric_limits<unsigned>::max()) 476 return ReqdSize - 1; 477 return getFlatWorkGroupSizes(Kernel).second - 1; 478 } 479 480 bool AMDGPUSubtarget::isSingleLaneExecution(const Function &Func) const { 481 for (int I = 0; I < 3; ++I) { 482 if (getMaxWorkitemID(Func, I) > 0) 483 return false; 484 } 485 486 return true; 487 } 488 489 bool AMDGPUSubtarget::makeLIDRangeMetadata(Instruction *I) const { 490 Function *Kernel = I->getParent()->getParent(); 491 unsigned MinSize = 0; 492 unsigned MaxSize = getFlatWorkGroupSizes(*Kernel).second; 493 bool IdQuery = false; 494 495 // If reqd_work_group_size is present it narrows value down. 496 if (auto *CI = dyn_cast<CallInst>(I)) { 497 const Function *F = CI->getCalledFunction(); 498 if (F) { 499 unsigned Dim = UINT_MAX; 500 switch (F->getIntrinsicID()) { 501 case Intrinsic::amdgcn_workitem_id_x: 502 case Intrinsic::r600_read_tidig_x: 503 IdQuery = true; 504 [[fallthrough]]; 505 case Intrinsic::r600_read_local_size_x: 506 Dim = 0; 507 break; 508 case Intrinsic::amdgcn_workitem_id_y: 509 case Intrinsic::r600_read_tidig_y: 510 IdQuery = true; 511 [[fallthrough]]; 512 case Intrinsic::r600_read_local_size_y: 513 Dim = 1; 514 break; 515 case Intrinsic::amdgcn_workitem_id_z: 516 case Intrinsic::r600_read_tidig_z: 517 IdQuery = true; 518 [[fallthrough]]; 519 case Intrinsic::r600_read_local_size_z: 520 Dim = 2; 521 break; 522 default: 523 break; 524 } 525 526 if (Dim <= 3) { 527 unsigned ReqdSize = getReqdWorkGroupSize(*Kernel, Dim); 528 if (ReqdSize != std::numeric_limits<unsigned>::max()) 529 MinSize = MaxSize = ReqdSize; 530 } 531 } 532 } 533 534 if (!MaxSize) 535 return false; 536 537 // Range metadata is [Lo, Hi). For ID query we need to pass max size 538 // as Hi. For size query we need to pass Hi + 1. 539 if (IdQuery) 540 MinSize = 0; 541 else 542 ++MaxSize; 543 544 MDBuilder MDB(I->getContext()); 545 MDNode *MaxWorkGroupSizeRange = MDB.createRange(APInt(32, MinSize), 546 APInt(32, MaxSize)); 547 I->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange); 548 return true; 549 } 550 551 unsigned AMDGPUSubtarget::getImplicitArgNumBytes(const Function &F) const { 552 assert(AMDGPU::isKernel(F.getCallingConv())); 553 554 // We don't allocate the segment if we know the implicit arguments weren't 555 // used, even if the ABI implies we need them. 556 if (F.hasFnAttribute("amdgpu-no-implicitarg-ptr")) 557 return 0; 558 559 if (isMesaKernel(F)) 560 return 16; 561 562 // Assume all implicit inputs are used by default 563 const Module *M = F.getParent(); 564 unsigned NBytes = 565 AMDGPU::getCodeObjectVersion(*M) >= AMDGPU::AMDHSA_COV5 ? 256 : 56; 566 return F.getFnAttributeAsParsedInteger("amdgpu-implicitarg-num-bytes", 567 NBytes); 568 } 569 570 uint64_t AMDGPUSubtarget::getExplicitKernArgSize(const Function &F, 571 Align &MaxAlign) const { 572 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 573 F.getCallingConv() == CallingConv::SPIR_KERNEL); 574 575 const DataLayout &DL = F.getParent()->getDataLayout(); 576 uint64_t ExplicitArgBytes = 0; 577 MaxAlign = Align(1); 578 579 for (const Argument &Arg : F.args()) { 580 const bool IsByRef = Arg.hasByRefAttr(); 581 Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType(); 582 Align Alignment = DL.getValueOrABITypeAlignment( 583 IsByRef ? Arg.getParamAlign() : std::nullopt, ArgTy); 584 uint64_t AllocSize = DL.getTypeAllocSize(ArgTy); 585 ExplicitArgBytes = alignTo(ExplicitArgBytes, Alignment) + AllocSize; 586 MaxAlign = std::max(MaxAlign, Alignment); 587 } 588 589 return ExplicitArgBytes; 590 } 591 592 unsigned AMDGPUSubtarget::getKernArgSegmentSize(const Function &F, 593 Align &MaxAlign) const { 594 if (F.getCallingConv() != CallingConv::AMDGPU_KERNEL && 595 F.getCallingConv() != CallingConv::SPIR_KERNEL) 596 return 0; 597 598 uint64_t ExplicitArgBytes = getExplicitKernArgSize(F, MaxAlign); 599 600 unsigned ExplicitOffset = getExplicitKernelArgOffset(); 601 602 uint64_t TotalSize = ExplicitOffset + ExplicitArgBytes; 603 unsigned ImplicitBytes = getImplicitArgNumBytes(F); 604 if (ImplicitBytes != 0) { 605 const Align Alignment = getAlignmentForImplicitArgPtr(); 606 TotalSize = alignTo(ExplicitArgBytes, Alignment) + ImplicitBytes; 607 MaxAlign = std::max(MaxAlign, Alignment); 608 } 609 610 // Being able to dereference past the end is useful for emitting scalar loads. 611 return alignTo(TotalSize, 4); 612 } 613 614 AMDGPUDwarfFlavour AMDGPUSubtarget::getAMDGPUDwarfFlavour() const { 615 return getWavefrontSize() == 32 ? AMDGPUDwarfFlavour::Wave32 616 : AMDGPUDwarfFlavour::Wave64; 617 } 618 619 void GCNSubtarget::overrideSchedPolicy(MachineSchedPolicy &Policy, 620 unsigned NumRegionInstrs) const { 621 // Track register pressure so the scheduler can try to decrease 622 // pressure once register usage is above the threshold defined by 623 // SIRegisterInfo::getRegPressureSetLimit() 624 Policy.ShouldTrackPressure = true; 625 626 // Enabling both top down and bottom up scheduling seems to give us less 627 // register spills than just using one of these approaches on its own. 628 Policy.OnlyTopDown = false; 629 Policy.OnlyBottomUp = false; 630 631 // Enabling ShouldTrackLaneMasks crashes the SI Machine Scheduler. 632 if (!enableSIScheduler()) 633 Policy.ShouldTrackLaneMasks = true; 634 } 635 636 bool GCNSubtarget::hasMadF16() const { 637 return InstrInfo.pseudoToMCOpcode(AMDGPU::V_MAD_F16_e64) != -1; 638 } 639 640 bool GCNSubtarget::useVGPRIndexMode() const { 641 return !hasMovrel() || (EnableVGPRIndexMode && hasVGPRIndexMode()); 642 } 643 644 bool GCNSubtarget::useAA() const { return UseAA; } 645 646 unsigned GCNSubtarget::getOccupancyWithNumSGPRs(unsigned SGPRs) const { 647 if (getGeneration() >= AMDGPUSubtarget::GFX10) 648 return getMaxWavesPerEU(); 649 650 if (getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 651 if (SGPRs <= 80) 652 return 10; 653 if (SGPRs <= 88) 654 return 9; 655 if (SGPRs <= 100) 656 return 8; 657 return 7; 658 } 659 if (SGPRs <= 48) 660 return 10; 661 if (SGPRs <= 56) 662 return 9; 663 if (SGPRs <= 64) 664 return 8; 665 if (SGPRs <= 72) 666 return 7; 667 if (SGPRs <= 80) 668 return 6; 669 return 5; 670 } 671 672 unsigned GCNSubtarget::getOccupancyWithNumVGPRs(unsigned NumVGPRs) const { 673 return AMDGPU::IsaInfo::getNumWavesPerEUWithNumVGPRs(this, NumVGPRs); 674 } 675 676 unsigned 677 GCNSubtarget::getBaseReservedNumSGPRs(const bool HasFlatScratch) const { 678 if (getGeneration() >= AMDGPUSubtarget::GFX10) 679 return 2; // VCC. FLAT_SCRATCH and XNACK are no longer in SGPRs. 680 681 if (HasFlatScratch || HasArchitectedFlatScratch) { 682 if (getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 683 return 6; // FLAT_SCRATCH, XNACK, VCC (in that order). 684 if (getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) 685 return 4; // FLAT_SCRATCH, VCC (in that order). 686 } 687 688 if (isXNACKEnabled()) 689 return 4; // XNACK, VCC (in that order). 690 return 2; // VCC. 691 } 692 693 unsigned GCNSubtarget::getReservedNumSGPRs(const MachineFunction &MF) const { 694 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 695 return getBaseReservedNumSGPRs(MFI.hasFlatScratchInit()); 696 } 697 698 unsigned GCNSubtarget::getReservedNumSGPRs(const Function &F) const { 699 // In principle we do not need to reserve SGPR pair used for flat_scratch if 700 // we know flat instructions do not access the stack anywhere in the 701 // program. For now assume it's needed if we have flat instructions. 702 const bool KernelUsesFlatScratch = hasFlatAddressSpace(); 703 return getBaseReservedNumSGPRs(KernelUsesFlatScratch); 704 } 705 706 unsigned GCNSubtarget::computeOccupancy(const Function &F, unsigned LDSSize, 707 unsigned NumSGPRs, 708 unsigned NumVGPRs) const { 709 unsigned Occupancy = 710 std::min(getMaxWavesPerEU(), 711 getOccupancyWithLocalMemSize(LDSSize, F)); 712 if (NumSGPRs) 713 Occupancy = std::min(Occupancy, getOccupancyWithNumSGPRs(NumSGPRs)); 714 if (NumVGPRs) 715 Occupancy = std::min(Occupancy, getOccupancyWithNumVGPRs(NumVGPRs)); 716 return Occupancy; 717 } 718 719 unsigned GCNSubtarget::getBaseMaxNumSGPRs( 720 const Function &F, std::pair<unsigned, unsigned> WavesPerEU, 721 unsigned PreloadedSGPRs, unsigned ReservedNumSGPRs) const { 722 // Compute maximum number of SGPRs function can use using default/requested 723 // minimum number of waves per execution unit. 724 unsigned MaxNumSGPRs = getMaxNumSGPRs(WavesPerEU.first, false); 725 unsigned MaxAddressableNumSGPRs = getMaxNumSGPRs(WavesPerEU.first, true); 726 727 // Check if maximum number of SGPRs was explicitly requested using 728 // "amdgpu-num-sgpr" attribute. 729 if (F.hasFnAttribute("amdgpu-num-sgpr")) { 730 unsigned Requested = 731 F.getFnAttributeAsParsedInteger("amdgpu-num-sgpr", MaxNumSGPRs); 732 733 // Make sure requested value does not violate subtarget's specifications. 734 if (Requested && (Requested <= ReservedNumSGPRs)) 735 Requested = 0; 736 737 // If more SGPRs are required to support the input user/system SGPRs, 738 // increase to accommodate them. 739 // 740 // FIXME: This really ends up using the requested number of SGPRs + number 741 // of reserved special registers in total. Theoretically you could re-use 742 // the last input registers for these special registers, but this would 743 // require a lot of complexity to deal with the weird aliasing. 744 unsigned InputNumSGPRs = PreloadedSGPRs; 745 if (Requested && Requested < InputNumSGPRs) 746 Requested = InputNumSGPRs; 747 748 // Make sure requested value is compatible with values implied by 749 // default/requested minimum/maximum number of waves per execution unit. 750 if (Requested && Requested > getMaxNumSGPRs(WavesPerEU.first, false)) 751 Requested = 0; 752 if (WavesPerEU.second && 753 Requested && Requested < getMinNumSGPRs(WavesPerEU.second)) 754 Requested = 0; 755 756 if (Requested) 757 MaxNumSGPRs = Requested; 758 } 759 760 if (hasSGPRInitBug()) 761 MaxNumSGPRs = AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 762 763 return std::min(MaxNumSGPRs - ReservedNumSGPRs, MaxAddressableNumSGPRs); 764 } 765 766 unsigned GCNSubtarget::getMaxNumSGPRs(const MachineFunction &MF) const { 767 const Function &F = MF.getFunction(); 768 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 769 return getBaseMaxNumSGPRs(F, MFI.getWavesPerEU(), MFI.getNumPreloadedSGPRs(), 770 getReservedNumSGPRs(MF)); 771 } 772 773 static unsigned getMaxNumPreloadedSGPRs() { 774 // Max number of user SGPRs 775 unsigned MaxUserSGPRs = 4 + // private segment buffer 776 2 + // Dispatch ptr 777 2 + // queue ptr 778 2 + // kernel segment ptr 779 2 + // dispatch ID 780 2 + // flat scratch init 781 2; // Implicit buffer ptr 782 783 // Max number of system SGPRs 784 unsigned MaxSystemSGPRs = 1 + // WorkGroupIDX 785 1 + // WorkGroupIDY 786 1 + // WorkGroupIDZ 787 1 + // WorkGroupInfo 788 1; // private segment wave byte offset 789 790 // Max number of synthetic SGPRs 791 unsigned SyntheticSGPRs = 1; // LDSKernelId 792 793 return MaxUserSGPRs + MaxSystemSGPRs + SyntheticSGPRs; 794 } 795 796 unsigned GCNSubtarget::getMaxNumSGPRs(const Function &F) const { 797 return getBaseMaxNumSGPRs(F, getWavesPerEU(F), getMaxNumPreloadedSGPRs(), 798 getReservedNumSGPRs(F)); 799 } 800 801 unsigned GCNSubtarget::getBaseMaxNumVGPRs( 802 const Function &F, std::pair<unsigned, unsigned> WavesPerEU) const { 803 // Compute maximum number of VGPRs function can use using default/requested 804 // minimum number of waves per execution unit. 805 unsigned MaxNumVGPRs = getMaxNumVGPRs(WavesPerEU.first); 806 807 // Check if maximum number of VGPRs was explicitly requested using 808 // "amdgpu-num-vgpr" attribute. 809 if (F.hasFnAttribute("amdgpu-num-vgpr")) { 810 unsigned Requested = 811 F.getFnAttributeAsParsedInteger("amdgpu-num-vgpr", MaxNumVGPRs); 812 813 if (hasGFX90AInsts()) 814 Requested *= 2; 815 816 // Make sure requested value is compatible with values implied by 817 // default/requested minimum/maximum number of waves per execution unit. 818 if (Requested && Requested > getMaxNumVGPRs(WavesPerEU.first)) 819 Requested = 0; 820 if (WavesPerEU.second && 821 Requested && Requested < getMinNumVGPRs(WavesPerEU.second)) 822 Requested = 0; 823 824 if (Requested) 825 MaxNumVGPRs = Requested; 826 } 827 828 return MaxNumVGPRs; 829 } 830 831 unsigned GCNSubtarget::getMaxNumVGPRs(const Function &F) const { 832 return getBaseMaxNumVGPRs(F, getWavesPerEU(F)); 833 } 834 835 unsigned GCNSubtarget::getMaxNumVGPRs(const MachineFunction &MF) const { 836 const Function &F = MF.getFunction(); 837 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 838 return getBaseMaxNumVGPRs(F, MFI.getWavesPerEU()); 839 } 840 841 void GCNSubtarget::adjustSchedDependency(SUnit *Def, int DefOpIdx, SUnit *Use, 842 int UseOpIdx, SDep &Dep) const { 843 if (Dep.getKind() != SDep::Kind::Data || !Dep.getReg() || 844 !Def->isInstr() || !Use->isInstr()) 845 return; 846 847 MachineInstr *DefI = Def->getInstr(); 848 MachineInstr *UseI = Use->getInstr(); 849 850 if (DefI->isBundle()) { 851 const SIRegisterInfo *TRI = getRegisterInfo(); 852 auto Reg = Dep.getReg(); 853 MachineBasicBlock::const_instr_iterator I(DefI->getIterator()); 854 MachineBasicBlock::const_instr_iterator E(DefI->getParent()->instr_end()); 855 unsigned Lat = 0; 856 for (++I; I != E && I->isBundledWithPred(); ++I) { 857 if (I->modifiesRegister(Reg, TRI)) 858 Lat = InstrInfo.getInstrLatency(getInstrItineraryData(), *I); 859 else if (Lat) 860 --Lat; 861 } 862 Dep.setLatency(Lat); 863 } else if (UseI->isBundle()) { 864 const SIRegisterInfo *TRI = getRegisterInfo(); 865 auto Reg = Dep.getReg(); 866 MachineBasicBlock::const_instr_iterator I(UseI->getIterator()); 867 MachineBasicBlock::const_instr_iterator E(UseI->getParent()->instr_end()); 868 unsigned Lat = InstrInfo.getInstrLatency(getInstrItineraryData(), *DefI); 869 for (++I; I != E && I->isBundledWithPred() && Lat; ++I) { 870 if (I->readsRegister(Reg, TRI)) 871 break; 872 --Lat; 873 } 874 Dep.setLatency(Lat); 875 } else if (Dep.getLatency() == 0 && Dep.getReg() == AMDGPU::VCC_LO) { 876 // Work around the fact that SIInstrInfo::fixImplicitOperands modifies 877 // implicit operands which come from the MCInstrDesc, which can fool 878 // ScheduleDAGInstrs::addPhysRegDataDeps into treating them as implicit 879 // pseudo operands. 880 Dep.setLatency(InstrInfo.getSchedModel().computeOperandLatency( 881 DefI, DefOpIdx, UseI, UseOpIdx)); 882 } 883 } 884 885 namespace { 886 struct FillMFMAShadowMutation : ScheduleDAGMutation { 887 const SIInstrInfo *TII; 888 889 ScheduleDAGMI *DAG; 890 891 FillMFMAShadowMutation(const SIInstrInfo *tii) : TII(tii) {} 892 893 bool isSALU(const SUnit *SU) const { 894 const MachineInstr *MI = SU->getInstr(); 895 return MI && TII->isSALU(*MI) && !MI->isTerminator(); 896 } 897 898 bool isVALU(const SUnit *SU) const { 899 const MachineInstr *MI = SU->getInstr(); 900 return MI && TII->isVALU(*MI); 901 } 902 903 // Link as many SALU instructions in chain as possible. Return the size 904 // of the chain. Links up to MaxChain instructions. 905 unsigned linkSALUChain(SUnit *From, SUnit *To, unsigned MaxChain, 906 SmallPtrSetImpl<SUnit *> &Visited) const { 907 SmallVector<SUnit *, 8> Worklist({To}); 908 unsigned Linked = 0; 909 910 while (!Worklist.empty() && MaxChain-- > 0) { 911 SUnit *SU = Worklist.pop_back_val(); 912 if (!Visited.insert(SU).second) 913 continue; 914 915 LLVM_DEBUG(dbgs() << "Inserting edge from\n" ; DAG->dumpNode(*From); 916 dbgs() << "to\n"; DAG->dumpNode(*SU); dbgs() << '\n'); 917 918 if (SU != From && From != &DAG->ExitSU && DAG->canAddEdge(SU, From)) 919 if (DAG->addEdge(SU, SDep(From, SDep::Artificial))) 920 ++Linked; 921 922 for (SDep &SI : From->Succs) { 923 SUnit *SUv = SI.getSUnit(); 924 if (SUv != From && SU != &DAG->ExitSU && isVALU(SUv) && 925 DAG->canAddEdge(SUv, SU)) 926 DAG->addEdge(SUv, SDep(SU, SDep::Artificial)); 927 } 928 929 for (SDep &SI : SU->Succs) { 930 SUnit *Succ = SI.getSUnit(); 931 if (Succ != SU && isSALU(Succ)) 932 Worklist.push_back(Succ); 933 } 934 } 935 936 return Linked; 937 } 938 939 void apply(ScheduleDAGInstrs *DAGInstrs) override { 940 const GCNSubtarget &ST = DAGInstrs->MF.getSubtarget<GCNSubtarget>(); 941 if (!ST.hasMAIInsts()) 942 return; 943 DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); 944 const TargetSchedModel *TSchedModel = DAGInstrs->getSchedModel(); 945 if (!TSchedModel || DAG->SUnits.empty()) 946 return; 947 948 // Scan for MFMA long latency instructions and try to add a dependency 949 // of available SALU instructions to give them a chance to fill MFMA 950 // shadow. That is desirable to fill MFMA shadow with SALU instructions 951 // rather than VALU to prevent power consumption bursts and throttle. 952 auto LastSALU = DAG->SUnits.begin(); 953 auto E = DAG->SUnits.end(); 954 SmallPtrSet<SUnit*, 32> Visited; 955 for (SUnit &SU : DAG->SUnits) { 956 MachineInstr &MAI = *SU.getInstr(); 957 if (!TII->isMAI(MAI) || 958 MAI.getOpcode() == AMDGPU::V_ACCVGPR_WRITE_B32_e64 || 959 MAI.getOpcode() == AMDGPU::V_ACCVGPR_READ_B32_e64) 960 continue; 961 962 unsigned Lat = TSchedModel->computeInstrLatency(&MAI) - 1; 963 964 LLVM_DEBUG(dbgs() << "Found MFMA: "; DAG->dumpNode(SU); 965 dbgs() << "Need " << Lat 966 << " instructions to cover latency.\n"); 967 968 // Find up to Lat independent scalar instructions as early as 969 // possible such that they can be scheduled after this MFMA. 970 for ( ; Lat && LastSALU != E; ++LastSALU) { 971 if (Visited.count(&*LastSALU)) 972 continue; 973 974 if (&SU == &DAG->ExitSU || &SU == &*LastSALU || !isSALU(&*LastSALU) || 975 !DAG->canAddEdge(&*LastSALU, &SU)) 976 continue; 977 978 Lat -= linkSALUChain(&SU, &*LastSALU, Lat, Visited); 979 } 980 } 981 } 982 }; 983 } // namespace 984 985 void GCNSubtarget::getPostRAMutations( 986 std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const { 987 Mutations.push_back(std::make_unique<FillMFMAShadowMutation>(&InstrInfo)); 988 } 989 990 std::unique_ptr<ScheduleDAGMutation> 991 GCNSubtarget::createFillMFMAShadowMutation(const TargetInstrInfo *TII) const { 992 return EnablePowerSched ? std::make_unique<FillMFMAShadowMutation>(&InstrInfo) 993 : nullptr; 994 } 995 996 unsigned GCNSubtarget::getNSAThreshold(const MachineFunction &MF) const { 997 if (NSAThreshold.getNumOccurrences() > 0) 998 return std::max(NSAThreshold.getValue(), 2u); 999 1000 int Value = MF.getFunction().getFnAttributeAsParsedInteger( 1001 "amdgpu-nsa-threshold", -1); 1002 if (Value > 0) 1003 return std::max(Value, 2); 1004 1005 return 3; 1006 } 1007 1008 const AMDGPUSubtarget &AMDGPUSubtarget::get(const MachineFunction &MF) { 1009 if (MF.getTarget().getTargetTriple().getArch() == Triple::amdgcn) 1010 return static_cast<const AMDGPUSubtarget&>(MF.getSubtarget<GCNSubtarget>()); 1011 else 1012 return static_cast<const AMDGPUSubtarget&>(MF.getSubtarget<R600Subtarget>()); 1013 } 1014 1015 const AMDGPUSubtarget &AMDGPUSubtarget::get(const TargetMachine &TM, const Function &F) { 1016 if (TM.getTargetTriple().getArch() == Triple::amdgcn) 1017 return static_cast<const AMDGPUSubtarget&>(TM.getSubtarget<GCNSubtarget>(F)); 1018 else 1019 return static_cast<const AMDGPUSubtarget&>(TM.getSubtarget<R600Subtarget>(F)); 1020 } 1021