1 //===-- AMDGPULowerModuleLDSPass.cpp ------------------------------*- C++ -*-=// 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 // This pass eliminates local data store, LDS, uses from non-kernel functions. 10 // LDS is contiguous memory allocated per kernel execution. 11 // 12 // Background. 13 // 14 // The programming model is global variables, or equivalently function local 15 // static variables, accessible from kernels or other functions. For uses from 16 // kernels this is straightforward - assign an integer to the kernel for the 17 // memory required by all the variables combined, allocate them within that. 18 // For uses from functions there are performance tradeoffs to choose between. 19 // 20 // This model means the GPU runtime can specify the amount of memory allocated. 21 // If this is more than the kernel assumed, the excess can be made available 22 // using a language specific feature, which IR represents as a variable with 23 // no initializer. This feature is referred to here as "Dynamic LDS" and is 24 // lowered slightly differently to the normal case. 25 // 26 // Consequences of this GPU feature: 27 // - memory is limited and exceeding it halts compilation 28 // - a global accessed by one kernel exists independent of other kernels 29 // - a global exists independent of simultaneous execution of the same kernel 30 // - the address of the global may be different from different kernels as they 31 // do not alias, which permits only allocating variables they use 32 // - if the address is allowed to differ, functions need help to find it 33 // 34 // Uses from kernels are implemented here by grouping them in a per-kernel 35 // struct instance. This duplicates the variables, accurately modelling their 36 // aliasing properties relative to a single global representation. It also 37 // permits control over alignment via padding. 38 // 39 // Uses from functions are more complicated and the primary purpose of this 40 // IR pass. Several different lowering are chosen between to meet requirements 41 // to avoid allocating any LDS where it is not necessary, as that impacts 42 // occupancy and may fail the compilation, while not imposing overhead on a 43 // feature whose primary advantage over global memory is performance. The basic 44 // design goal is to avoid one kernel imposing overhead on another. 45 // 46 // Implementation. 47 // 48 // LDS variables with constant annotation or non-undef initializer are passed 49 // through unchanged for simplification or error diagnostics in later passes. 50 // Non-undef initializers are not yet implemented for LDS. 51 // 52 // LDS variables that are always allocated at the same address can be found 53 // by lookup at that address. Otherwise runtime information/cost is required. 54 // 55 // The simplest strategy possible is to group all LDS variables in a single 56 // struct and allocate that struct in every kernel such that the original 57 // variables are always at the same address. LDS is however a limited resource 58 // so this strategy is unusable in practice. It is not implemented here. 59 // 60 // Strategy | Precise allocation | Zero runtime cost | General purpose | 61 // --------+--------------------+-------------------+-----------------+ 62 // Module | No | Yes | Yes | 63 // Table | Yes | No | Yes | 64 // Kernel | Yes | Yes | No | 65 // Hybrid | Yes | Partial | Yes | 66 // 67 // "Module" spends LDS memory to save cycles. "Table" spends cycles and global 68 // memory to save LDS. "Kernel" is as fast as kernel allocation but only works 69 // for variables that are known reachable from a single kernel. "Hybrid" picks 70 // between all three. When forced to choose between LDS and cycles we minimise 71 // LDS use. 72 73 // The "module" lowering implemented here finds LDS variables which are used by 74 // non-kernel functions and creates a new struct with a field for each of those 75 // LDS variables. Variables that are only used from kernels are excluded. 76 // 77 // The "table" lowering implemented here has three components. 78 // First kernels are assigned a unique integer identifier which is available in 79 // functions it calls through the intrinsic amdgcn_lds_kernel_id. The integer 80 // is passed through a specific SGPR, thus works with indirect calls. 81 // Second, each kernel allocates LDS variables independent of other kernels and 82 // writes the addresses it chose for each variable into an array in consistent 83 // order. If the kernel does not allocate a given variable, it writes undef to 84 // the corresponding array location. These arrays are written to a constant 85 // table in the order matching the kernel unique integer identifier. 86 // Third, uses from non-kernel functions are replaced with a table lookup using 87 // the intrinsic function to find the address of the variable. 88 // 89 // "Kernel" lowering is only applicable for variables that are unambiguously 90 // reachable from exactly one kernel. For those cases, accesses to the variable 91 // can be lowered to ConstantExpr address of a struct instance specific to that 92 // one kernel. This is zero cost in space and in compute. It will raise a fatal 93 // error on any variable that might be reachable from multiple kernels and is 94 // thus most easily used as part of the hybrid lowering strategy. 95 // 96 // Hybrid lowering is a mixture of the above. It uses the zero cost kernel 97 // lowering where it can. It lowers the variable accessed by the greatest 98 // number of kernels using the module strategy as that is free for the first 99 // variable. Any futher variables that can be lowered with the module strategy 100 // without incurring LDS memory overhead are. The remaining ones are lowered 101 // via table. 102 // 103 // Consequences 104 // - No heuristics or user controlled magic numbers, hybrid is the right choice 105 // - Kernels that don't use functions (or have had them all inlined) are not 106 // affected by any lowering for kernels that do. 107 // - Kernels that don't make indirect function calls are not affected by those 108 // that do. 109 // - Variables which are used by lots of kernels, e.g. those injected by a 110 // language runtime in most kernels, are expected to have no overhead 111 // - Implementations that instantiate templates per-kernel where those templates 112 // use LDS are expected to hit the "Kernel" lowering strategy 113 // - The runtime properties impose a cost in compiler implementation complexity 114 // 115 // Dynamic LDS implementation 116 // Dynamic LDS is lowered similarly to the "table" strategy above and uses the 117 // same intrinsic to identify which kernel is at the root of the dynamic call 118 // graph. This relies on the specified behaviour that all dynamic LDS variables 119 // alias one another, i.e. are at the same address, with respect to a given 120 // kernel. Therefore this pass creates new dynamic LDS variables for each kernel 121 // that allocates any dynamic LDS and builds a table of addresses out of those. 122 // The AMDGPUPromoteAlloca pass skips kernels that use dynamic LDS. 123 // The corresponding optimisation for "kernel" lowering where the table lookup 124 // is elided is not implemented. 125 // 126 // 127 // Implementation notes / limitations 128 // A single LDS global variable represents an instance per kernel that can reach 129 // said variables. This pass essentially specialises said variables per kernel. 130 // Handling ConstantExpr during the pass complicated this significantly so now 131 // all ConstantExpr uses of LDS variables are expanded to instructions. This 132 // may need amending when implementing non-undef initialisers. 133 // 134 // Lowering is split between this IR pass and the back end. This pass chooses 135 // where given variables should be allocated and marks them with metadata, 136 // MD_absolute_symbol. The backend places the variables in coincidentally the 137 // same location and raises a fatal error if something has gone awry. This works 138 // in practice because the only pass between this one and the backend that 139 // changes LDS is PromoteAlloca and the changes it makes do not conflict. 140 // 141 // Addresses are written to constant global arrays based on the same metadata. 142 // 143 // The backend lowers LDS variables in the order of traversal of the function. 144 // This is at odds with the deterministic layout required. The workaround is to 145 // allocate the fixed-address variables immediately upon starting the function 146 // where they can be placed as intended. This requires a means of mapping from 147 // the function to the variables that it allocates. For the module scope lds, 148 // this is via metadata indicating whether the variable is not required. If a 149 // pass deletes that metadata, a fatal error on disagreement with the absolute 150 // symbol metadata will occur. For kernel scope and dynamic, this is by _name_ 151 // correspondence between the function and the variable. It requires the 152 // kernel to have a name (which is only a limitation for tests in practice) and 153 // for nothing to rename the corresponding symbols. This is a hazard if the pass 154 // is run multiple times during debugging. Alternative schemes considered all 155 // involve bespoke metadata. 156 // 157 // If the name correspondence can be replaced, multiple distinct kernels that 158 // have the same memory layout can map to the same kernel id (as the address 159 // itself is handled by the absolute symbol metadata) and that will allow more 160 // uses of the "kernel" style faster lowering and reduce the size of the lookup 161 // tables. 162 // 163 // There is a test that checks this does not fire for a graphics shader. This 164 // lowering is expected to work for graphics if the isKernel test is changed. 165 // 166 // The current markUsedByKernel is sufficient for PromoteAlloca but is elided 167 // before codegen. Replacing this with an equivalent intrinsic which lasts until 168 // shortly after the machine function lowering of LDS would help break the name 169 // mapping. The other part needed is probably to amend PromoteAlloca to embed 170 // the LDS variables it creates in the same struct created here. That avoids the 171 // current hazard where a PromoteAlloca LDS variable might be allocated before 172 // the kernel scope (and thus error on the address check). Given a new invariant 173 // that no LDS variables exist outside of the structs managed here, and an 174 // intrinsic that lasts until after the LDS frame lowering, it should be 175 // possible to drop the name mapping and fold equivalent memory layouts. 176 // 177 //===----------------------------------------------------------------------===// 178 179 #include "AMDGPU.h" 180 #include "Utils/AMDGPUBaseInfo.h" 181 #include "Utils/AMDGPUMemoryUtils.h" 182 #include "llvm/ADT/BitVector.h" 183 #include "llvm/ADT/DenseMap.h" 184 #include "llvm/ADT/DenseSet.h" 185 #include "llvm/ADT/STLExtras.h" 186 #include "llvm/ADT/SetOperations.h" 187 #include "llvm/ADT/SetVector.h" 188 #include "llvm/Analysis/CallGraph.h" 189 #include "llvm/IR/Constants.h" 190 #include "llvm/IR/DerivedTypes.h" 191 #include "llvm/IR/IRBuilder.h" 192 #include "llvm/IR/InlineAsm.h" 193 #include "llvm/IR/Instructions.h" 194 #include "llvm/IR/IntrinsicsAMDGPU.h" 195 #include "llvm/IR/MDBuilder.h" 196 #include "llvm/IR/ReplaceConstant.h" 197 #include "llvm/InitializePasses.h" 198 #include "llvm/Pass.h" 199 #include "llvm/Support/CommandLine.h" 200 #include "llvm/Support/Debug.h" 201 #include "llvm/Support/OptimizedStructLayout.h" 202 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 203 #include "llvm/Transforms/Utils/ModuleUtils.h" 204 205 #include <tuple> 206 #include <vector> 207 208 #include <cstdio> 209 210 #define DEBUG_TYPE "amdgpu-lower-module-lds" 211 212 using namespace llvm; 213 214 namespace { 215 216 cl::opt<bool> SuperAlignLDSGlobals( 217 "amdgpu-super-align-lds-globals", 218 cl::desc("Increase alignment of LDS if it is not on align boundary"), 219 cl::init(true), cl::Hidden); 220 221 enum class LoweringKind { module, table, kernel, hybrid }; 222 cl::opt<LoweringKind> LoweringKindLoc( 223 "amdgpu-lower-module-lds-strategy", 224 cl::desc("Specify lowering strategy for function LDS access:"), cl::Hidden, 225 cl::init(LoweringKind::hybrid), 226 cl::values( 227 clEnumValN(LoweringKind::table, "table", "Lower via table lookup"), 228 clEnumValN(LoweringKind::module, "module", "Lower via module struct"), 229 clEnumValN( 230 LoweringKind::kernel, "kernel", 231 "Lower variables reachable from one kernel, otherwise abort"), 232 clEnumValN(LoweringKind::hybrid, "hybrid", 233 "Lower via mixture of above strategies"))); 234 235 bool isKernelLDS(const Function *F) { 236 // Some weirdness here. AMDGPU::isKernelCC does not call into 237 // AMDGPU::isKernel with the calling conv, it instead calls into 238 // isModuleEntryFunction which returns true for more calling conventions 239 // than AMDGPU::isKernel does. There's a FIXME on AMDGPU::isKernel. 240 // There's also a test that checks that the LDS lowering does not hit on 241 // a graphics shader, denoted amdgpu_ps, so stay with the limited case. 242 // Putting LDS in the name of the function to draw attention to this. 243 return AMDGPU::isKernel(F->getCallingConv()); 244 } 245 246 template <typename T> std::vector<T> sortByName(std::vector<T> &&V) { 247 llvm::sort(V.begin(), V.end(), [](const auto *L, const auto *R) { 248 return L->getName() < R->getName(); 249 }); 250 return {std::move(V)}; 251 } 252 253 class AMDGPULowerModuleLDS : public ModulePass { 254 255 static void 256 removeLocalVarsFromUsedLists(Module &M, 257 const DenseSet<GlobalVariable *> &LocalVars) { 258 // The verifier rejects used lists containing an inttoptr of a constant 259 // so remove the variables from these lists before replaceAllUsesWith 260 SmallPtrSet<Constant *, 8> LocalVarsSet; 261 for (GlobalVariable *LocalVar : LocalVars) 262 LocalVarsSet.insert(cast<Constant>(LocalVar->stripPointerCasts())); 263 264 removeFromUsedLists( 265 M, [&LocalVarsSet](Constant *C) { return LocalVarsSet.count(C); }); 266 267 for (GlobalVariable *LocalVar : LocalVars) 268 LocalVar->removeDeadConstantUsers(); 269 } 270 271 static void markUsedByKernel(IRBuilder<> &Builder, Function *Func, 272 GlobalVariable *SGV) { 273 // The llvm.amdgcn.module.lds instance is implicitly used by all kernels 274 // that might call a function which accesses a field within it. This is 275 // presently approximated to 'all kernels' if there are any such functions 276 // in the module. This implicit use is redefined as an explicit use here so 277 // that later passes, specifically PromoteAlloca, account for the required 278 // memory without any knowledge of this transform. 279 280 // An operand bundle on llvm.donothing works because the call instruction 281 // survives until after the last pass that needs to account for LDS. It is 282 // better than inline asm as the latter survives until the end of codegen. A 283 // totally robust solution would be a function with the same semantics as 284 // llvm.donothing that takes a pointer to the instance and is lowered to a 285 // no-op after LDS is allocated, but that is not presently necessary. 286 287 // This intrinsic is eliminated shortly before instruction selection. It 288 // does not suffice to indicate to ISel that a given global which is not 289 // immediately used by the kernel must still be allocated by it. An 290 // equivalent target specific intrinsic which lasts until immediately after 291 // codegen would suffice for that, but one would still need to ensure that 292 // the variables are allocated in the anticpated order. 293 294 LLVMContext &Ctx = Func->getContext(); 295 296 Builder.SetInsertPoint(Func->getEntryBlock().getFirstNonPHI()); 297 298 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), {}); 299 300 Function *Decl = 301 Intrinsic::getDeclaration(Func->getParent(), Intrinsic::donothing, {}); 302 303 Value *UseInstance[1] = {Builder.CreateInBoundsGEP( 304 SGV->getValueType(), SGV, ConstantInt::get(Type::getInt32Ty(Ctx), 0))}; 305 306 Builder.CreateCall(FTy, Decl, {}, 307 {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)}, 308 ""); 309 } 310 311 static bool eliminateConstantExprUsesOfLDSFromAllInstructions(Module &M) { 312 // Constants are uniqued within LLVM. A ConstantExpr referring to a LDS 313 // global may have uses from multiple different functions as a result. 314 // This pass specialises LDS variables with respect to the kernel that 315 // allocates them. 316 317 // This is semantically equivalent to (the unimplemented as slow): 318 // for (auto &F : M.functions()) 319 // for (auto &BB : F) 320 // for (auto &I : BB) 321 // for (Use &Op : I.operands()) 322 // if (constantExprUsesLDS(Op)) 323 // replaceConstantExprInFunction(I, Op); 324 325 SmallVector<Constant *> LDSGlobals; 326 for (auto &GV : M.globals()) 327 if (AMDGPU::isLDSVariableToLower(GV)) 328 LDSGlobals.push_back(&GV); 329 330 return convertUsersOfConstantsToInstructions(LDSGlobals); 331 } 332 333 public: 334 static char ID; 335 336 AMDGPULowerModuleLDS() : ModulePass(ID) { 337 initializeAMDGPULowerModuleLDSPass(*PassRegistry::getPassRegistry()); 338 } 339 340 using FunctionVariableMap = DenseMap<Function *, DenseSet<GlobalVariable *>>; 341 342 using VariableFunctionMap = DenseMap<GlobalVariable *, DenseSet<Function *>>; 343 344 static void getUsesOfLDSByFunction(CallGraph const &CG, Module &M, 345 FunctionVariableMap &kernels, 346 FunctionVariableMap &functions) { 347 348 // Get uses from the current function, excluding uses by called functions 349 // Two output variables to avoid walking the globals list twice 350 for (auto &GV : M.globals()) { 351 if (!AMDGPU::isLDSVariableToLower(GV)) { 352 continue; 353 } 354 355 if (GV.isAbsoluteSymbolRef()) { 356 report_fatal_error( 357 "LDS variables with absolute addresses are unimplemented."); 358 } 359 360 for (User *V : GV.users()) { 361 if (auto *I = dyn_cast<Instruction>(V)) { 362 Function *F = I->getFunction(); 363 if (isKernelLDS(F)) { 364 kernels[F].insert(&GV); 365 } else { 366 functions[F].insert(&GV); 367 } 368 } 369 } 370 } 371 } 372 373 struct LDSUsesInfoTy { 374 FunctionVariableMap direct_access; 375 FunctionVariableMap indirect_access; 376 }; 377 378 static LDSUsesInfoTy getTransitiveUsesOfLDS(CallGraph const &CG, Module &M) { 379 380 FunctionVariableMap direct_map_kernel; 381 FunctionVariableMap direct_map_function; 382 getUsesOfLDSByFunction(CG, M, direct_map_kernel, direct_map_function); 383 384 // Collect variables that are used by functions whose address has escaped 385 DenseSet<GlobalVariable *> VariablesReachableThroughFunctionPointer; 386 for (Function &F : M.functions()) { 387 if (!isKernelLDS(&F)) 388 if (F.hasAddressTaken(nullptr, 389 /* IgnoreCallbackUses */ false, 390 /* IgnoreAssumeLikeCalls */ false, 391 /* IgnoreLLVMUsed */ true, 392 /* IgnoreArcAttachedCall */ false)) { 393 set_union(VariablesReachableThroughFunctionPointer, 394 direct_map_function[&F]); 395 } 396 } 397 398 auto functionMakesUnknownCall = [&](const Function *F) -> bool { 399 assert(!F->isDeclaration()); 400 for (const CallGraphNode::CallRecord &R : *CG[F]) { 401 if (!R.second->getFunction()) { 402 return true; 403 } 404 } 405 return false; 406 }; 407 408 // Work out which variables are reachable through function calls 409 FunctionVariableMap transitive_map_function = direct_map_function; 410 411 // If the function makes any unknown call, assume the worst case that it can 412 // access all variables accessed by functions whose address escaped 413 for (Function &F : M.functions()) { 414 if (!F.isDeclaration() && functionMakesUnknownCall(&F)) { 415 if (!isKernelLDS(&F)) { 416 set_union(transitive_map_function[&F], 417 VariablesReachableThroughFunctionPointer); 418 } 419 } 420 } 421 422 // Direct implementation of collecting all variables reachable from each 423 // function 424 for (Function &Func : M.functions()) { 425 if (Func.isDeclaration() || isKernelLDS(&Func)) 426 continue; 427 428 DenseSet<Function *> seen; // catches cycles 429 SmallVector<Function *, 4> wip{&Func}; 430 431 while (!wip.empty()) { 432 Function *F = wip.pop_back_val(); 433 434 // Can accelerate this by referring to transitive map for functions that 435 // have already been computed, with more care than this 436 set_union(transitive_map_function[&Func], direct_map_function[F]); 437 438 for (const CallGraphNode::CallRecord &R : *CG[F]) { 439 Function *ith = R.second->getFunction(); 440 if (ith) { 441 if (!seen.contains(ith)) { 442 seen.insert(ith); 443 wip.push_back(ith); 444 } 445 } 446 } 447 } 448 } 449 450 // direct_map_kernel lists which variables are used by the kernel 451 // find the variables which are used through a function call 452 FunctionVariableMap indirect_map_kernel; 453 454 for (Function &Func : M.functions()) { 455 if (Func.isDeclaration() || !isKernelLDS(&Func)) 456 continue; 457 458 for (const CallGraphNode::CallRecord &R : *CG[&Func]) { 459 Function *ith = R.second->getFunction(); 460 if (ith) { 461 set_union(indirect_map_kernel[&Func], transitive_map_function[ith]); 462 } else { 463 set_union(indirect_map_kernel[&Func], 464 VariablesReachableThroughFunctionPointer); 465 } 466 } 467 } 468 469 return {std::move(direct_map_kernel), std::move(indirect_map_kernel)}; 470 } 471 472 struct LDSVariableReplacement { 473 GlobalVariable *SGV = nullptr; 474 DenseMap<GlobalVariable *, Constant *> LDSVarsToConstantGEP; 475 }; 476 477 // remap from lds global to a constantexpr gep to where it has been moved to 478 // for each kernel 479 // an array with an element for each kernel containing where the corresponding 480 // variable was remapped to 481 482 static Constant *getAddressesOfVariablesInKernel( 483 LLVMContext &Ctx, ArrayRef<GlobalVariable *> Variables, 484 const DenseMap<GlobalVariable *, Constant *> &LDSVarsToConstantGEP) { 485 // Create a ConstantArray containing the address of each Variable within the 486 // kernel corresponding to LDSVarsToConstantGEP, or poison if that kernel 487 // does not allocate it 488 // TODO: Drop the ptrtoint conversion 489 490 Type *I32 = Type::getInt32Ty(Ctx); 491 492 ArrayType *KernelOffsetsType = ArrayType::get(I32, Variables.size()); 493 494 SmallVector<Constant *> Elements; 495 for (size_t i = 0; i < Variables.size(); i++) { 496 GlobalVariable *GV = Variables[i]; 497 auto ConstantGepIt = LDSVarsToConstantGEP.find(GV); 498 if (ConstantGepIt != LDSVarsToConstantGEP.end()) { 499 auto elt = ConstantExpr::getPtrToInt(ConstantGepIt->second, I32); 500 Elements.push_back(elt); 501 } else { 502 Elements.push_back(PoisonValue::get(I32)); 503 } 504 } 505 return ConstantArray::get(KernelOffsetsType, Elements); 506 } 507 508 static GlobalVariable *buildLookupTable( 509 Module &M, ArrayRef<GlobalVariable *> Variables, 510 ArrayRef<Function *> kernels, 511 DenseMap<Function *, LDSVariableReplacement> &KernelToReplacement) { 512 if (Variables.empty()) { 513 return nullptr; 514 } 515 LLVMContext &Ctx = M.getContext(); 516 517 const size_t NumberVariables = Variables.size(); 518 const size_t NumberKernels = kernels.size(); 519 520 ArrayType *KernelOffsetsType = 521 ArrayType::get(Type::getInt32Ty(Ctx), NumberVariables); 522 523 ArrayType *AllKernelsOffsetsType = 524 ArrayType::get(KernelOffsetsType, NumberKernels); 525 526 Constant *Missing = PoisonValue::get(KernelOffsetsType); 527 std::vector<Constant *> overallConstantExprElts(NumberKernels); 528 for (size_t i = 0; i < NumberKernels; i++) { 529 auto Replacement = KernelToReplacement.find(kernels[i]); 530 overallConstantExprElts[i] = 531 (Replacement == KernelToReplacement.end()) 532 ? Missing 533 : getAddressesOfVariablesInKernel( 534 Ctx, Variables, Replacement->second.LDSVarsToConstantGEP); 535 } 536 537 Constant *init = 538 ConstantArray::get(AllKernelsOffsetsType, overallConstantExprElts); 539 540 return new GlobalVariable( 541 M, AllKernelsOffsetsType, true, GlobalValue::InternalLinkage, init, 542 "llvm.amdgcn.lds.offset.table", nullptr, GlobalValue::NotThreadLocal, 543 AMDGPUAS::CONSTANT_ADDRESS); 544 } 545 546 void replaceUseWithTableLookup(Module &M, IRBuilder<> &Builder, 547 GlobalVariable *LookupTable, 548 GlobalVariable *GV, Use &U, 549 Value *OptionalIndex) { 550 // Table is a constant array of the same length as OrderedKernels 551 LLVMContext &Ctx = M.getContext(); 552 Type *I32 = Type::getInt32Ty(Ctx); 553 auto *I = cast<Instruction>(U.getUser()); 554 555 Value *tableKernelIndex = getTableLookupKernelIndex(M, I->getFunction()); 556 557 if (auto *Phi = dyn_cast<PHINode>(I)) { 558 BasicBlock *BB = Phi->getIncomingBlock(U); 559 Builder.SetInsertPoint(&(*(BB->getFirstInsertionPt()))); 560 } else { 561 Builder.SetInsertPoint(I); 562 } 563 564 SmallVector<Value *, 3> GEPIdx = { 565 ConstantInt::get(I32, 0), 566 tableKernelIndex, 567 }; 568 if (OptionalIndex) 569 GEPIdx.push_back(OptionalIndex); 570 571 Value *Address = Builder.CreateInBoundsGEP( 572 LookupTable->getValueType(), LookupTable, GEPIdx, GV->getName()); 573 574 Value *loaded = Builder.CreateLoad(I32, Address); 575 576 Value *replacement = 577 Builder.CreateIntToPtr(loaded, GV->getType(), GV->getName()); 578 579 U.set(replacement); 580 } 581 582 void replaceUsesInInstructionsWithTableLookup( 583 Module &M, ArrayRef<GlobalVariable *> ModuleScopeVariables, 584 GlobalVariable *LookupTable) { 585 586 LLVMContext &Ctx = M.getContext(); 587 IRBuilder<> Builder(Ctx); 588 Type *I32 = Type::getInt32Ty(Ctx); 589 590 for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) { 591 auto *GV = ModuleScopeVariables[Index]; 592 593 for (Use &U : make_early_inc_range(GV->uses())) { 594 auto *I = dyn_cast<Instruction>(U.getUser()); 595 if (!I) 596 continue; 597 598 replaceUseWithTableLookup(M, Builder, LookupTable, GV, U, 599 ConstantInt::get(I32, Index)); 600 } 601 } 602 } 603 604 static DenseSet<Function *> kernelsThatIndirectlyAccessAnyOfPassedVariables( 605 Module &M, LDSUsesInfoTy &LDSUsesInfo, 606 DenseSet<GlobalVariable *> const &VariableSet) { 607 608 DenseSet<Function *> KernelSet; 609 610 if (VariableSet.empty()) 611 return KernelSet; 612 613 for (Function &Func : M.functions()) { 614 if (Func.isDeclaration() || !isKernelLDS(&Func)) 615 continue; 616 for (GlobalVariable *GV : LDSUsesInfo.indirect_access[&Func]) { 617 if (VariableSet.contains(GV)) { 618 KernelSet.insert(&Func); 619 break; 620 } 621 } 622 } 623 624 return KernelSet; 625 } 626 627 static GlobalVariable * 628 chooseBestVariableForModuleStrategy(const DataLayout &DL, 629 VariableFunctionMap &LDSVars) { 630 // Find the global variable with the most indirect uses from kernels 631 632 struct CandidateTy { 633 GlobalVariable *GV = nullptr; 634 size_t UserCount = 0; 635 size_t Size = 0; 636 637 CandidateTy() = default; 638 639 CandidateTy(GlobalVariable *GV, uint64_t UserCount, uint64_t AllocSize) 640 : GV(GV), UserCount(UserCount), Size(AllocSize) {} 641 642 bool operator<(const CandidateTy &Other) const { 643 // Fewer users makes module scope variable less attractive 644 if (UserCount < Other.UserCount) { 645 return true; 646 } 647 if (UserCount > Other.UserCount) { 648 return false; 649 } 650 651 // Bigger makes module scope variable less attractive 652 if (Size < Other.Size) { 653 return false; 654 } 655 656 if (Size > Other.Size) { 657 return true; 658 } 659 660 // Arbitrary but consistent 661 return GV->getName() < Other.GV->getName(); 662 } 663 }; 664 665 CandidateTy MostUsed; 666 667 for (auto &K : LDSVars) { 668 GlobalVariable *GV = K.first; 669 if (K.second.size() <= 1) { 670 // A variable reachable by only one kernel is best lowered with kernel 671 // strategy 672 continue; 673 } 674 CandidateTy Candidate( 675 GV, K.second.size(), 676 DL.getTypeAllocSize(GV->getValueType()).getFixedValue()); 677 if (MostUsed < Candidate) 678 MostUsed = Candidate; 679 } 680 681 return MostUsed.GV; 682 } 683 684 static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV, 685 uint32_t Address) { 686 // Write the specified address into metadata where it can be retrieved by 687 // the assembler. Format is a half open range, [Address Address+1) 688 LLVMContext &Ctx = M->getContext(); 689 auto *IntTy = 690 M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS); 691 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address)); 692 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1)); 693 GV->setMetadata(LLVMContext::MD_absolute_symbol, 694 MDNode::get(Ctx, {MinC, MaxC})); 695 } 696 697 DenseMap<Function *, Value *> tableKernelIndexCache; 698 Value *getTableLookupKernelIndex(Module &M, Function *F) { 699 // Accesses from a function use the amdgcn_lds_kernel_id intrinsic which 700 // lowers to a read from a live in register. Emit it once in the entry 701 // block to spare deduplicating it later. 702 if (tableKernelIndexCache.count(F) == 0) { 703 LLVMContext &Ctx = M.getContext(); 704 IRBuilder<> Builder(Ctx); 705 FunctionType *FTy = FunctionType::get(Type::getInt32Ty(Ctx), {}); 706 Function *Decl = 707 Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_lds_kernel_id, {}); 708 709 BasicBlock::iterator it = 710 F->getEntryBlock().getFirstNonPHIOrDbgOrAlloca(); 711 Instruction &i = *it; 712 Builder.SetInsertPoint(&i); 713 714 tableKernelIndexCache[F] = Builder.CreateCall(FTy, Decl, {}); 715 } 716 717 return tableKernelIndexCache[F]; 718 } 719 720 static std::vector<Function *> assignLDSKernelIDToEachKernel( 721 Module *M, DenseSet<Function *> const &KernelsThatAllocateTableLDS, 722 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS) { 723 // Associate kernels in the set with an arbirary but reproducible order and 724 // annotate them with that order in metadata. This metadata is recognised by 725 // the backend and lowered to a SGPR which can be read from using 726 // amdgcn_lds_kernel_id. 727 728 std::vector<Function *> OrderedKernels; 729 if (!KernelsThatAllocateTableLDS.empty() || 730 !KernelsThatIndirectlyAllocateDynamicLDS.empty()) { 731 732 for (Function &Func : M->functions()) { 733 if (Func.isDeclaration()) 734 continue; 735 if (!isKernelLDS(&Func)) 736 continue; 737 738 if (KernelsThatAllocateTableLDS.contains(&Func) || 739 KernelsThatIndirectlyAllocateDynamicLDS.contains(&Func)) { 740 assert(Func.hasName()); // else fatal error earlier 741 OrderedKernels.push_back(&Func); 742 } 743 } 744 745 // Put them in an arbitrary but reproducible order 746 OrderedKernels = sortByName(std::move(OrderedKernels)); 747 748 // Annotate the kernels with their order in this vector 749 LLVMContext &Ctx = M->getContext(); 750 IRBuilder<> Builder(Ctx); 751 752 if (OrderedKernels.size() > UINT32_MAX) { 753 // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU 754 report_fatal_error("Unimplemented LDS lowering for > 2**32 kernels"); 755 } 756 757 for (size_t i = 0; i < OrderedKernels.size(); i++) { 758 Metadata *AttrMDArgs[1] = { 759 ConstantAsMetadata::get(Builder.getInt32(i)), 760 }; 761 OrderedKernels[i]->setMetadata("llvm.amdgcn.lds.kernel.id", 762 MDNode::get(Ctx, AttrMDArgs)); 763 } 764 } 765 return OrderedKernels; 766 } 767 768 static void partitionVariablesIntoIndirectStrategies( 769 Module &M, LDSUsesInfoTy const &LDSUsesInfo, 770 VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly, 771 DenseSet<GlobalVariable *> &ModuleScopeVariables, 772 DenseSet<GlobalVariable *> &TableLookupVariables, 773 DenseSet<GlobalVariable *> &KernelAccessVariables, 774 DenseSet<GlobalVariable *> &DynamicVariables) { 775 776 GlobalVariable *HybridModuleRoot = 777 LoweringKindLoc != LoweringKind::hybrid 778 ? nullptr 779 : chooseBestVariableForModuleStrategy( 780 M.getDataLayout(), LDSToKernelsThatNeedToAccessItIndirectly); 781 782 DenseSet<Function *> const EmptySet; 783 DenseSet<Function *> const &HybridModuleRootKernels = 784 HybridModuleRoot 785 ? LDSToKernelsThatNeedToAccessItIndirectly[HybridModuleRoot] 786 : EmptySet; 787 788 for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) { 789 // Each iteration of this loop assigns exactly one global variable to 790 // exactly one of the implementation strategies. 791 792 GlobalVariable *GV = K.first; 793 assert(AMDGPU::isLDSVariableToLower(*GV)); 794 assert(K.second.size() != 0); 795 796 if (AMDGPU::isDynamicLDS(*GV)) { 797 DynamicVariables.insert(GV); 798 continue; 799 } 800 801 switch (LoweringKindLoc) { 802 case LoweringKind::module: 803 ModuleScopeVariables.insert(GV); 804 break; 805 806 case LoweringKind::table: 807 TableLookupVariables.insert(GV); 808 break; 809 810 case LoweringKind::kernel: 811 if (K.second.size() == 1) { 812 KernelAccessVariables.insert(GV); 813 } else { 814 report_fatal_error( 815 "cannot lower LDS '" + GV->getName() + 816 "' to kernel access as it is reachable from multiple kernels"); 817 } 818 break; 819 820 case LoweringKind::hybrid: { 821 if (GV == HybridModuleRoot) { 822 assert(K.second.size() != 1); 823 ModuleScopeVariables.insert(GV); 824 } else if (K.second.size() == 1) { 825 KernelAccessVariables.insert(GV); 826 } else if (set_is_subset(K.second, HybridModuleRootKernels)) { 827 ModuleScopeVariables.insert(GV); 828 } else { 829 TableLookupVariables.insert(GV); 830 } 831 break; 832 } 833 } 834 } 835 836 // All LDS variables accessed indirectly have now been partitioned into 837 // the distinct lowering strategies. 838 assert(ModuleScopeVariables.size() + TableLookupVariables.size() + 839 KernelAccessVariables.size() + DynamicVariables.size() == 840 LDSToKernelsThatNeedToAccessItIndirectly.size()); 841 } 842 843 static GlobalVariable *lowerModuleScopeStructVariables( 844 Module &M, DenseSet<GlobalVariable *> const &ModuleScopeVariables, 845 DenseSet<Function *> const &KernelsThatAllocateModuleLDS) { 846 // Create a struct to hold the ModuleScopeVariables 847 // Replace all uses of those variables from non-kernel functions with the 848 // new struct instance Replace only the uses from kernel functions that will 849 // allocate this instance. That is a space optimisation - kernels that use a 850 // subset of the module scope struct and do not need to allocate it for 851 // indirect calls will only allocate the subset they use (they do so as part 852 // of the per-kernel lowering). 853 if (ModuleScopeVariables.empty()) { 854 return nullptr; 855 } 856 857 LLVMContext &Ctx = M.getContext(); 858 859 LDSVariableReplacement ModuleScopeReplacement = 860 createLDSVariableReplacement(M, "llvm.amdgcn.module.lds", 861 ModuleScopeVariables); 862 863 appendToCompilerUsed(M, {static_cast<GlobalValue *>( 864 ConstantExpr::getPointerBitCastOrAddrSpaceCast( 865 cast<Constant>(ModuleScopeReplacement.SGV), 866 Type::getInt8PtrTy(Ctx)))}); 867 868 // module.lds will be allocated at zero in any kernel that allocates it 869 recordLDSAbsoluteAddress(&M, ModuleScopeReplacement.SGV, 0); 870 871 // historic 872 removeLocalVarsFromUsedLists(M, ModuleScopeVariables); 873 874 // Replace all uses of module scope variable from non-kernel functions 875 replaceLDSVariablesWithStruct( 876 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) { 877 Instruction *I = dyn_cast<Instruction>(U.getUser()); 878 if (!I) { 879 return false; 880 } 881 Function *F = I->getFunction(); 882 return !isKernelLDS(F); 883 }); 884 885 // Replace uses of module scope variable from kernel functions that 886 // allocate the module scope variable, otherwise leave them unchanged 887 // Record on each kernel whether the module scope global is used by it 888 889 IRBuilder<> Builder(Ctx); 890 891 for (Function &Func : M.functions()) { 892 if (Func.isDeclaration() || !isKernelLDS(&Func)) 893 continue; 894 895 if (KernelsThatAllocateModuleLDS.contains(&Func)) { 896 replaceLDSVariablesWithStruct( 897 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) { 898 Instruction *I = dyn_cast<Instruction>(U.getUser()); 899 if (!I) { 900 return false; 901 } 902 Function *F = I->getFunction(); 903 return F == &Func; 904 }); 905 906 markUsedByKernel(Builder, &Func, ModuleScopeReplacement.SGV); 907 } 908 } 909 910 return ModuleScopeReplacement.SGV; 911 } 912 913 static DenseMap<Function *, LDSVariableReplacement> 914 lowerKernelScopeStructVariables( 915 Module &M, LDSUsesInfoTy &LDSUsesInfo, 916 DenseSet<GlobalVariable *> const &ModuleScopeVariables, 917 DenseSet<Function *> const &KernelsThatAllocateModuleLDS, 918 GlobalVariable *MaybeModuleScopeStruct) { 919 920 // Create a struct for each kernel for the non-module-scope variables. 921 922 IRBuilder<> Builder(M.getContext()); 923 DenseMap<Function *, LDSVariableReplacement> KernelToReplacement; 924 for (Function &Func : M.functions()) { 925 if (Func.isDeclaration() || !isKernelLDS(&Func)) 926 continue; 927 928 DenseSet<GlobalVariable *> KernelUsedVariables; 929 // Allocating variables that are used directly in this struct to get 930 // alignment aware allocation and predictable frame size. 931 for (auto &v : LDSUsesInfo.direct_access[&Func]) { 932 if (!AMDGPU::isDynamicLDS(*v)) { 933 KernelUsedVariables.insert(v); 934 } 935 } 936 937 // Allocating variables that are accessed indirectly so that a lookup of 938 // this struct instance can find them from nested functions. 939 for (auto &v : LDSUsesInfo.indirect_access[&Func]) { 940 if (!AMDGPU::isDynamicLDS(*v)) { 941 KernelUsedVariables.insert(v); 942 } 943 } 944 945 // Variables allocated in module lds must all resolve to that struct, 946 // not to the per-kernel instance. 947 if (KernelsThatAllocateModuleLDS.contains(&Func)) { 948 for (GlobalVariable *v : ModuleScopeVariables) { 949 KernelUsedVariables.erase(v); 950 } 951 } 952 953 if (KernelUsedVariables.empty()) { 954 // Either used no LDS, or the LDS it used was all in the module struct 955 // or dynamically sized 956 continue; 957 } 958 959 // The association between kernel function and LDS struct is done by 960 // symbol name, which only works if the function in question has a 961 // name This is not expected to be a problem in practice as kernels 962 // are called by name making anonymous ones (which are named by the 963 // backend) difficult to use. This does mean that llvm test cases need 964 // to name the kernels. 965 if (!Func.hasName()) { 966 report_fatal_error("Anonymous kernels cannot use LDS variables"); 967 } 968 969 std::string VarName = 970 (Twine("llvm.amdgcn.kernel.") + Func.getName() + ".lds").str(); 971 972 auto Replacement = 973 createLDSVariableReplacement(M, VarName, KernelUsedVariables); 974 975 // If any indirect uses, create a direct use to ensure allocation 976 // TODO: Simpler to unconditionally mark used but that regresses 977 // codegen in test/CodeGen/AMDGPU/noclobber-barrier.ll 978 auto Accesses = LDSUsesInfo.indirect_access.find(&Func); 979 if ((Accesses != LDSUsesInfo.indirect_access.end()) && 980 !Accesses->second.empty()) 981 markUsedByKernel(Builder, &Func, Replacement.SGV); 982 983 // remove preserves existing codegen 984 removeLocalVarsFromUsedLists(M, KernelUsedVariables); 985 KernelToReplacement[&Func] = Replacement; 986 987 // Rewrite uses within kernel to the new struct 988 replaceLDSVariablesWithStruct( 989 M, KernelUsedVariables, Replacement, [&Func](Use &U) { 990 Instruction *I = dyn_cast<Instruction>(U.getUser()); 991 return I && I->getFunction() == &Func; 992 }); 993 } 994 return KernelToReplacement; 995 } 996 997 static GlobalVariable * 998 buildRepresentativeDynamicLDSInstance(Module &M, LDSUsesInfoTy &LDSUsesInfo, 999 Function *func) { 1000 // Create a dynamic lds variable with a name associated with the passed 1001 // function that has the maximum alignment of any dynamic lds variable 1002 // reachable from this kernel. Dynamic LDS is allocated after the static LDS 1003 // allocation, possibly after alignment padding. The representative variable 1004 // created here has the maximum alignment of any other dynamic variable 1005 // reachable by that kernel. All dynamic LDS variables are allocated at the 1006 // same address in each kernel in order to provide the documented aliasing 1007 // semantics. Setting the alignment here allows this IR pass to accurately 1008 // predict the exact constant at which it will be allocated. 1009 1010 assert(isKernelLDS(func)); 1011 1012 LLVMContext &Ctx = M.getContext(); 1013 const DataLayout &DL = M.getDataLayout(); 1014 Align MaxDynamicAlignment(1); 1015 1016 auto UpdateMaxAlignment = [&MaxDynamicAlignment, &DL](GlobalVariable *GV) { 1017 if (AMDGPU::isDynamicLDS(*GV)) { 1018 MaxDynamicAlignment = 1019 std::max(MaxDynamicAlignment, AMDGPU::getAlign(DL, GV)); 1020 } 1021 }; 1022 1023 for (GlobalVariable *GV : LDSUsesInfo.indirect_access[func]) { 1024 UpdateMaxAlignment(GV); 1025 } 1026 1027 for (GlobalVariable *GV : LDSUsesInfo.direct_access[func]) { 1028 UpdateMaxAlignment(GV); 1029 } 1030 1031 assert(func->hasName()); // Checked by caller 1032 auto emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0); 1033 GlobalVariable *N = new GlobalVariable( 1034 M, emptyCharArray, false, GlobalValue::ExternalLinkage, nullptr, 1035 Twine("llvm.amdgcn." + func->getName() + ".dynlds"), nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, 1036 false); 1037 N->setAlignment(MaxDynamicAlignment); 1038 1039 assert(AMDGPU::isDynamicLDS(*N)); 1040 return N; 1041 } 1042 1043 DenseMap<Function *, GlobalVariable *> lowerDynamicLDSVariables( 1044 Module &M, LDSUsesInfoTy &LDSUsesInfo, 1045 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS, 1046 DenseSet<GlobalVariable *> const &DynamicVariables, 1047 std::vector<Function *> const &OrderedKernels) { 1048 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS; 1049 if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) { 1050 LLVMContext &Ctx = M.getContext(); 1051 IRBuilder<> Builder(Ctx); 1052 Type *I32 = Type::getInt32Ty(Ctx); 1053 1054 std::vector<Constant *> newDynamicLDS; 1055 1056 // Table is built in the same order as OrderedKernels 1057 for (auto &func : OrderedKernels) { 1058 1059 if (KernelsThatIndirectlyAllocateDynamicLDS.contains(func)) { 1060 assert(isKernelLDS(func)); 1061 if (!func->hasName()) { 1062 report_fatal_error("Anonymous kernels cannot use LDS variables"); 1063 } 1064 1065 GlobalVariable *N = 1066 buildRepresentativeDynamicLDSInstance(M, LDSUsesInfo, func); 1067 1068 KernelToCreatedDynamicLDS[func] = N; 1069 1070 markUsedByKernel(Builder, func, N); 1071 1072 auto emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0); 1073 auto GEP = ConstantExpr::getGetElementPtr( 1074 emptyCharArray, N, ConstantInt::get(I32, 0), true); 1075 newDynamicLDS.push_back(ConstantExpr::getPtrToInt(GEP, I32)); 1076 } else { 1077 newDynamicLDS.push_back(PoisonValue::get(I32)); 1078 } 1079 } 1080 assert(OrderedKernels.size() == newDynamicLDS.size()); 1081 1082 ArrayType *t = ArrayType::get(I32, newDynamicLDS.size()); 1083 Constant *init = ConstantArray::get(t, newDynamicLDS); 1084 GlobalVariable *table = new GlobalVariable( 1085 M, t, true, GlobalValue::InternalLinkage, init, 1086 "llvm.amdgcn.dynlds.offset.table", nullptr, 1087 GlobalValue::NotThreadLocal, AMDGPUAS::CONSTANT_ADDRESS); 1088 1089 for (GlobalVariable *GV : DynamicVariables) { 1090 for (Use &U : make_early_inc_range(GV->uses())) { 1091 auto *I = dyn_cast<Instruction>(U.getUser()); 1092 if (!I) 1093 continue; 1094 if (isKernelLDS(I->getFunction())) 1095 continue; 1096 1097 replaceUseWithTableLookup(M, Builder, table, GV, U, nullptr); 1098 } 1099 } 1100 } 1101 return KernelToCreatedDynamicLDS; 1102 } 1103 1104 bool runOnModule(Module &M) override { 1105 CallGraph CG = CallGraph(M); 1106 bool Changed = superAlignLDSGlobals(M); 1107 1108 Changed |= eliminateConstantExprUsesOfLDSFromAllInstructions(M); 1109 1110 Changed = true; // todo: narrow this down 1111 1112 // For each kernel, what variables does it access directly or through 1113 // callees 1114 LDSUsesInfoTy LDSUsesInfo = getTransitiveUsesOfLDS(CG, M); 1115 1116 // For each variable accessed through callees, which kernels access it 1117 VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly; 1118 for (auto &K : LDSUsesInfo.indirect_access) { 1119 Function *F = K.first; 1120 assert(isKernelLDS(F)); 1121 for (GlobalVariable *GV : K.second) { 1122 LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(F); 1123 } 1124 } 1125 1126 // Partition variables accessed indirectly into the different strategies 1127 DenseSet<GlobalVariable *> ModuleScopeVariables; 1128 DenseSet<GlobalVariable *> TableLookupVariables; 1129 DenseSet<GlobalVariable *> KernelAccessVariables; 1130 DenseSet<GlobalVariable *> DynamicVariables; 1131 partitionVariablesIntoIndirectStrategies( 1132 M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly, 1133 ModuleScopeVariables, TableLookupVariables, KernelAccessVariables, 1134 DynamicVariables); 1135 1136 // If the kernel accesses a variable that is going to be stored in the 1137 // module instance through a call then that kernel needs to allocate the 1138 // module instance 1139 const DenseSet<Function *> KernelsThatAllocateModuleLDS = 1140 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo, 1141 ModuleScopeVariables); 1142 const DenseSet<Function *> KernelsThatAllocateTableLDS = 1143 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo, 1144 TableLookupVariables); 1145 1146 const DenseSet<Function *> KernelsThatIndirectlyAllocateDynamicLDS = 1147 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo, 1148 DynamicVariables); 1149 1150 GlobalVariable *MaybeModuleScopeStruct = lowerModuleScopeStructVariables( 1151 M, ModuleScopeVariables, KernelsThatAllocateModuleLDS); 1152 1153 DenseMap<Function *, LDSVariableReplacement> KernelToReplacement = 1154 lowerKernelScopeStructVariables(M, LDSUsesInfo, ModuleScopeVariables, 1155 KernelsThatAllocateModuleLDS, 1156 MaybeModuleScopeStruct); 1157 1158 // Lower zero cost accesses to the kernel instances just created 1159 for (auto &GV : KernelAccessVariables) { 1160 auto &funcs = LDSToKernelsThatNeedToAccessItIndirectly[GV]; 1161 assert(funcs.size() == 1); // Only one kernel can access it 1162 LDSVariableReplacement Replacement = 1163 KernelToReplacement[*(funcs.begin())]; 1164 1165 DenseSet<GlobalVariable *> Vec; 1166 Vec.insert(GV); 1167 1168 replaceLDSVariablesWithStruct(M, Vec, Replacement, [](Use &U) { 1169 return isa<Instruction>(U.getUser()); 1170 }); 1171 } 1172 1173 // The ith element of this vector is kernel id i 1174 std::vector<Function *> OrderedKernels = 1175 assignLDSKernelIDToEachKernel(&M, KernelsThatAllocateTableLDS, 1176 KernelsThatIndirectlyAllocateDynamicLDS); 1177 1178 if (!KernelsThatAllocateTableLDS.empty()) { 1179 LLVMContext &Ctx = M.getContext(); 1180 IRBuilder<> Builder(Ctx); 1181 1182 // The order must be consistent between lookup table and accesses to 1183 // lookup table 1184 auto TableLookupVariablesOrdered = 1185 sortByName(std::vector<GlobalVariable *>(TableLookupVariables.begin(), 1186 TableLookupVariables.end())); 1187 1188 GlobalVariable *LookupTable = buildLookupTable( 1189 M, TableLookupVariablesOrdered, OrderedKernels, KernelToReplacement); 1190 replaceUsesInInstructionsWithTableLookup(M, TableLookupVariablesOrdered, 1191 LookupTable); 1192 } 1193 1194 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS = 1195 lowerDynamicLDSVariables(M, LDSUsesInfo, 1196 KernelsThatIndirectlyAllocateDynamicLDS, 1197 DynamicVariables, OrderedKernels); 1198 1199 // All kernel frames have been allocated. Calculate and record the 1200 // addresses. 1201 { 1202 const DataLayout &DL = M.getDataLayout(); 1203 1204 for (Function &Func : M.functions()) { 1205 if (Func.isDeclaration() || !isKernelLDS(&Func)) 1206 continue; 1207 1208 // All three of these are optional. The first variable is allocated at 1209 // zero. They are allocated by AMDGPUMachineFunction as one block. 1210 // Layout: 1211 //{ 1212 // module.lds 1213 // alignment padding 1214 // kernel instance 1215 // alignment padding 1216 // dynamic lds variables 1217 //} 1218 1219 const bool AllocateModuleScopeStruct = 1220 MaybeModuleScopeStruct && 1221 KernelsThatAllocateModuleLDS.contains(&Func); 1222 1223 auto Replacement = KernelToReplacement.find(&Func); 1224 const bool AllocateKernelScopeStruct = 1225 Replacement != KernelToReplacement.end(); 1226 1227 const bool AllocateDynamicVariable = 1228 KernelToCreatedDynamicLDS.contains(&Func); 1229 1230 uint32_t Offset = 0; 1231 1232 if (AllocateModuleScopeStruct) { 1233 // Allocated at zero, recorded once on construction, not once per 1234 // kernel 1235 Offset += DL.getTypeAllocSize(MaybeModuleScopeStruct->getValueType()); 1236 } 1237 1238 if (AllocateKernelScopeStruct) { 1239 GlobalVariable *KernelStruct = Replacement->second.SGV; 1240 Offset = alignTo(Offset, AMDGPU::getAlign(DL, KernelStruct)); 1241 recordLDSAbsoluteAddress(&M, KernelStruct, Offset); 1242 Offset += DL.getTypeAllocSize(KernelStruct->getValueType()); 1243 } 1244 1245 // If there is dynamic allocation, the alignment needed is included in 1246 // the static frame size. There may be no reference to the dynamic 1247 // variable in the kernel itself, so without including it here, that 1248 // alignment padding could be missed. 1249 if (AllocateDynamicVariable) { 1250 GlobalVariable *DynamicVariable = KernelToCreatedDynamicLDS[&Func]; 1251 Offset = alignTo(Offset, AMDGPU::getAlign(DL, DynamicVariable)); 1252 recordLDSAbsoluteAddress(&M, DynamicVariable, Offset); 1253 } 1254 1255 if (Offset != 0) 1256 Func.addFnAttr("amdgpu-lds-size", std::to_string(Offset)); 1257 } 1258 } 1259 1260 for (auto &GV : make_early_inc_range(M.globals())) 1261 if (AMDGPU::isLDSVariableToLower(GV)) { 1262 // probably want to remove from used lists 1263 GV.removeDeadConstantUsers(); 1264 if (GV.use_empty()) 1265 GV.eraseFromParent(); 1266 } 1267 1268 return Changed; 1269 } 1270 1271 private: 1272 // Increase the alignment of LDS globals if necessary to maximise the chance 1273 // that we can use aligned LDS instructions to access them. 1274 static bool superAlignLDSGlobals(Module &M) { 1275 const DataLayout &DL = M.getDataLayout(); 1276 bool Changed = false; 1277 if (!SuperAlignLDSGlobals) { 1278 return Changed; 1279 } 1280 1281 for (auto &GV : M.globals()) { 1282 if (GV.getType()->getPointerAddressSpace() != AMDGPUAS::LOCAL_ADDRESS) { 1283 // Only changing alignment of LDS variables 1284 continue; 1285 } 1286 if (!GV.hasInitializer()) { 1287 // cuda/hip extern __shared__ variable, leave alignment alone 1288 continue; 1289 } 1290 1291 Align Alignment = AMDGPU::getAlign(DL, &GV); 1292 TypeSize GVSize = DL.getTypeAllocSize(GV.getValueType()); 1293 1294 if (GVSize > 8) { 1295 // We might want to use a b96 or b128 load/store 1296 Alignment = std::max(Alignment, Align(16)); 1297 } else if (GVSize > 4) { 1298 // We might want to use a b64 load/store 1299 Alignment = std::max(Alignment, Align(8)); 1300 } else if (GVSize > 2) { 1301 // We might want to use a b32 load/store 1302 Alignment = std::max(Alignment, Align(4)); 1303 } else if (GVSize > 1) { 1304 // We might want to use a b16 load/store 1305 Alignment = std::max(Alignment, Align(2)); 1306 } 1307 1308 if (Alignment != AMDGPU::getAlign(DL, &GV)) { 1309 Changed = true; 1310 GV.setAlignment(Alignment); 1311 } 1312 } 1313 return Changed; 1314 } 1315 1316 static LDSVariableReplacement createLDSVariableReplacement( 1317 Module &M, std::string VarName, 1318 DenseSet<GlobalVariable *> const &LDSVarsToTransform) { 1319 // Create a struct instance containing LDSVarsToTransform and map from those 1320 // variables to ConstantExprGEP 1321 // Variables may be introduced to meet alignment requirements. No aliasing 1322 // metadata is useful for these as they have no uses. Erased before return. 1323 1324 LLVMContext &Ctx = M.getContext(); 1325 const DataLayout &DL = M.getDataLayout(); 1326 assert(!LDSVarsToTransform.empty()); 1327 1328 SmallVector<OptimizedStructLayoutField, 8> LayoutFields; 1329 LayoutFields.reserve(LDSVarsToTransform.size()); 1330 { 1331 // The order of fields in this struct depends on the order of 1332 // varables in the argument which varies when changing how they 1333 // are identified, leading to spurious test breakage. 1334 auto Sorted = sortByName(std::vector<GlobalVariable *>( 1335 LDSVarsToTransform.begin(), LDSVarsToTransform.end())); 1336 1337 for (GlobalVariable *GV : Sorted) { 1338 OptimizedStructLayoutField F(GV, 1339 DL.getTypeAllocSize(GV->getValueType()), 1340 AMDGPU::getAlign(DL, GV)); 1341 LayoutFields.emplace_back(F); 1342 } 1343 } 1344 1345 performOptimizedStructLayout(LayoutFields); 1346 1347 std::vector<GlobalVariable *> LocalVars; 1348 BitVector IsPaddingField; 1349 LocalVars.reserve(LDSVarsToTransform.size()); // will be at least this large 1350 IsPaddingField.reserve(LDSVarsToTransform.size()); 1351 { 1352 uint64_t CurrentOffset = 0; 1353 for (size_t I = 0; I < LayoutFields.size(); I++) { 1354 GlobalVariable *FGV = static_cast<GlobalVariable *>( 1355 const_cast<void *>(LayoutFields[I].Id)); 1356 Align DataAlign = LayoutFields[I].Alignment; 1357 1358 uint64_t DataAlignV = DataAlign.value(); 1359 if (uint64_t Rem = CurrentOffset % DataAlignV) { 1360 uint64_t Padding = DataAlignV - Rem; 1361 1362 // Append an array of padding bytes to meet alignment requested 1363 // Note (o + (a - (o % a)) ) % a == 0 1364 // (offset + Padding ) % align == 0 1365 1366 Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding); 1367 LocalVars.push_back(new GlobalVariable( 1368 M, ATy, false, GlobalValue::InternalLinkage, UndefValue::get(ATy), 1369 "", nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, 1370 false)); 1371 IsPaddingField.push_back(true); 1372 CurrentOffset += Padding; 1373 } 1374 1375 LocalVars.push_back(FGV); 1376 IsPaddingField.push_back(false); 1377 CurrentOffset += LayoutFields[I].Size; 1378 } 1379 } 1380 1381 std::vector<Type *> LocalVarTypes; 1382 LocalVarTypes.reserve(LocalVars.size()); 1383 std::transform( 1384 LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes), 1385 [](const GlobalVariable *V) -> Type * { return V->getValueType(); }); 1386 1387 StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t"); 1388 1389 Align StructAlign = AMDGPU::getAlign(DL, LocalVars[0]); 1390 1391 GlobalVariable *SGV = new GlobalVariable( 1392 M, LDSTy, false, GlobalValue::InternalLinkage, UndefValue::get(LDSTy), 1393 VarName, nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, 1394 false); 1395 SGV->setAlignment(StructAlign); 1396 1397 DenseMap<GlobalVariable *, Constant *> Map; 1398 Type *I32 = Type::getInt32Ty(Ctx); 1399 for (size_t I = 0; I < LocalVars.size(); I++) { 1400 GlobalVariable *GV = LocalVars[I]; 1401 Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)}; 1402 Constant *GEP = ConstantExpr::getGetElementPtr(LDSTy, SGV, GEPIdx, true); 1403 if (IsPaddingField[I]) { 1404 assert(GV->use_empty()); 1405 GV->eraseFromParent(); 1406 } else { 1407 Map[GV] = GEP; 1408 } 1409 } 1410 assert(Map.size() == LDSVarsToTransform.size()); 1411 return {SGV, std::move(Map)}; 1412 } 1413 1414 template <typename PredicateTy> 1415 static void replaceLDSVariablesWithStruct( 1416 Module &M, DenseSet<GlobalVariable *> const &LDSVarsToTransformArg, 1417 const LDSVariableReplacement &Replacement, PredicateTy Predicate) { 1418 LLVMContext &Ctx = M.getContext(); 1419 const DataLayout &DL = M.getDataLayout(); 1420 1421 // A hack... we need to insert the aliasing info in a predictable order for 1422 // lit tests. Would like to have them in a stable order already, ideally the 1423 // same order they get allocated, which might mean an ordered set container 1424 auto LDSVarsToTransform = sortByName(std::vector<GlobalVariable *>( 1425 LDSVarsToTransformArg.begin(), LDSVarsToTransformArg.end())); 1426 1427 // Create alias.scope and their lists. Each field in the new structure 1428 // does not alias with all other fields. 1429 SmallVector<MDNode *> AliasScopes; 1430 SmallVector<Metadata *> NoAliasList; 1431 const size_t NumberVars = LDSVarsToTransform.size(); 1432 if (NumberVars > 1) { 1433 MDBuilder MDB(Ctx); 1434 AliasScopes.reserve(NumberVars); 1435 MDNode *Domain = MDB.createAnonymousAliasScopeDomain(); 1436 for (size_t I = 0; I < NumberVars; I++) { 1437 MDNode *Scope = MDB.createAnonymousAliasScope(Domain); 1438 AliasScopes.push_back(Scope); 1439 } 1440 NoAliasList.append(&AliasScopes[1], AliasScopes.end()); 1441 } 1442 1443 // Replace uses of ith variable with a constantexpr to the corresponding 1444 // field of the instance that will be allocated by AMDGPUMachineFunction 1445 for (size_t I = 0; I < NumberVars; I++) { 1446 GlobalVariable *GV = LDSVarsToTransform[I]; 1447 Constant *GEP = Replacement.LDSVarsToConstantGEP.at(GV); 1448 1449 GV->replaceUsesWithIf(GEP, Predicate); 1450 1451 APInt APOff(DL.getIndexTypeSizeInBits(GEP->getType()), 0); 1452 GEP->stripAndAccumulateInBoundsConstantOffsets(DL, APOff); 1453 uint64_t Offset = APOff.getZExtValue(); 1454 1455 Align A = 1456 commonAlignment(Replacement.SGV->getAlign().valueOrOne(), Offset); 1457 1458 if (I) 1459 NoAliasList[I - 1] = AliasScopes[I - 1]; 1460 MDNode *NoAlias = 1461 NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList); 1462 MDNode *AliasScope = 1463 AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]}); 1464 1465 refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias); 1466 } 1467 } 1468 1469 static void refineUsesAlignmentAndAA(Value *Ptr, Align A, 1470 const DataLayout &DL, MDNode *AliasScope, 1471 MDNode *NoAlias, unsigned MaxDepth = 5) { 1472 if (!MaxDepth || (A == 1 && !AliasScope)) 1473 return; 1474 1475 for (User *U : Ptr->users()) { 1476 if (auto *I = dyn_cast<Instruction>(U)) { 1477 if (AliasScope && I->mayReadOrWriteMemory()) { 1478 MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope); 1479 AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope) 1480 : AliasScope); 1481 I->setMetadata(LLVMContext::MD_alias_scope, AS); 1482 1483 MDNode *NA = I->getMetadata(LLVMContext::MD_noalias); 1484 NA = (NA ? MDNode::intersect(NA, NoAlias) : NoAlias); 1485 I->setMetadata(LLVMContext::MD_noalias, NA); 1486 } 1487 } 1488 1489 if (auto *LI = dyn_cast<LoadInst>(U)) { 1490 LI->setAlignment(std::max(A, LI->getAlign())); 1491 continue; 1492 } 1493 if (auto *SI = dyn_cast<StoreInst>(U)) { 1494 if (SI->getPointerOperand() == Ptr) 1495 SI->setAlignment(std::max(A, SI->getAlign())); 1496 continue; 1497 } 1498 if (auto *AI = dyn_cast<AtomicRMWInst>(U)) { 1499 // None of atomicrmw operations can work on pointers, but let's 1500 // check it anyway in case it will or we will process ConstantExpr. 1501 if (AI->getPointerOperand() == Ptr) 1502 AI->setAlignment(std::max(A, AI->getAlign())); 1503 continue; 1504 } 1505 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) { 1506 if (AI->getPointerOperand() == Ptr) 1507 AI->setAlignment(std::max(A, AI->getAlign())); 1508 continue; 1509 } 1510 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { 1511 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType()); 1512 APInt Off(BitWidth, 0); 1513 if (GEP->getPointerOperand() == Ptr) { 1514 Align GA; 1515 if (GEP->accumulateConstantOffset(DL, Off)) 1516 GA = commonAlignment(A, Off.getLimitedValue()); 1517 refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias, 1518 MaxDepth - 1); 1519 } 1520 continue; 1521 } 1522 if (auto *I = dyn_cast<Instruction>(U)) { 1523 if (I->getOpcode() == Instruction::BitCast || 1524 I->getOpcode() == Instruction::AddrSpaceCast) 1525 refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1); 1526 } 1527 } 1528 } 1529 }; 1530 1531 } // namespace 1532 char AMDGPULowerModuleLDS::ID = 0; 1533 1534 char &llvm::AMDGPULowerModuleLDSID = AMDGPULowerModuleLDS::ID; 1535 1536 INITIALIZE_PASS(AMDGPULowerModuleLDS, DEBUG_TYPE, 1537 "Lower uses of LDS variables from non-kernel functions", false, 1538 false) 1539 1540 ModulePass *llvm::createAMDGPULowerModuleLDSPass() { 1541 return new AMDGPULowerModuleLDS(); 1542 } 1543 1544 PreservedAnalyses AMDGPULowerModuleLDSPass::run(Module &M, 1545 ModuleAnalysisManager &) { 1546 return AMDGPULowerModuleLDS().runOnModule(M) ? PreservedAnalyses::none() 1547 : PreservedAnalyses::all(); 1548 } 1549