1fe6060f1SDimitry Andric //===-- AMDGPULowerModuleLDSPass.cpp ------------------------------*- C++ -*-=// 2fe6060f1SDimitry Andric // 3fe6060f1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4fe6060f1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5fe6060f1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6fe6060f1SDimitry Andric // 7fe6060f1SDimitry Andric //===----------------------------------------------------------------------===// 8fe6060f1SDimitry Andric // 9bdd1243dSDimitry Andric // This pass eliminates local data store, LDS, uses from non-kernel functions. 10bdd1243dSDimitry Andric // LDS is contiguous memory allocated per kernel execution. 11fe6060f1SDimitry Andric // 12bdd1243dSDimitry Andric // Background. 13fe6060f1SDimitry Andric // 14bdd1243dSDimitry Andric // The programming model is global variables, or equivalently function local 15bdd1243dSDimitry Andric // static variables, accessible from kernels or other functions. For uses from 16bdd1243dSDimitry Andric // kernels this is straightforward - assign an integer to the kernel for the 17bdd1243dSDimitry Andric // memory required by all the variables combined, allocate them within that. 18bdd1243dSDimitry Andric // For uses from functions there are performance tradeoffs to choose between. 19bdd1243dSDimitry Andric // 20bdd1243dSDimitry Andric // This model means the GPU runtime can specify the amount of memory allocated. 21bdd1243dSDimitry Andric // If this is more than the kernel assumed, the excess can be made available 22bdd1243dSDimitry Andric // using a language specific feature, which IR represents as a variable with 2306c3fb27SDimitry Andric // no initializer. This feature is referred to here as "Dynamic LDS" and is 2406c3fb27SDimitry Andric // lowered slightly differently to the normal case. 25bdd1243dSDimitry Andric // 26bdd1243dSDimitry Andric // Consequences of this GPU feature: 27bdd1243dSDimitry Andric // - memory is limited and exceeding it halts compilation 28bdd1243dSDimitry Andric // - a global accessed by one kernel exists independent of other kernels 29bdd1243dSDimitry Andric // - a global exists independent of simultaneous execution of the same kernel 30bdd1243dSDimitry Andric // - the address of the global may be different from different kernels as they 31bdd1243dSDimitry Andric // do not alias, which permits only allocating variables they use 32bdd1243dSDimitry Andric // - if the address is allowed to differ, functions need help to find it 33bdd1243dSDimitry Andric // 34bdd1243dSDimitry Andric // Uses from kernels are implemented here by grouping them in a per-kernel 35bdd1243dSDimitry Andric // struct instance. This duplicates the variables, accurately modelling their 36bdd1243dSDimitry Andric // aliasing properties relative to a single global representation. It also 37bdd1243dSDimitry Andric // permits control over alignment via padding. 38bdd1243dSDimitry Andric // 39bdd1243dSDimitry Andric // Uses from functions are more complicated and the primary purpose of this 40bdd1243dSDimitry Andric // IR pass. Several different lowering are chosen between to meet requirements 41bdd1243dSDimitry Andric // to avoid allocating any LDS where it is not necessary, as that impacts 42bdd1243dSDimitry Andric // occupancy and may fail the compilation, while not imposing overhead on a 43bdd1243dSDimitry Andric // feature whose primary advantage over global memory is performance. The basic 44bdd1243dSDimitry Andric // design goal is to avoid one kernel imposing overhead on another. 45bdd1243dSDimitry Andric // 46bdd1243dSDimitry Andric // Implementation. 47bdd1243dSDimitry Andric // 48bdd1243dSDimitry Andric // LDS variables with constant annotation or non-undef initializer are passed 4981ad6265SDimitry Andric // through unchanged for simplification or error diagnostics in later passes. 50bdd1243dSDimitry Andric // Non-undef initializers are not yet implemented for LDS. 51fe6060f1SDimitry Andric // 52bdd1243dSDimitry Andric // LDS variables that are always allocated at the same address can be found 53bdd1243dSDimitry Andric // by lookup at that address. Otherwise runtime information/cost is required. 54fe6060f1SDimitry Andric // 55bdd1243dSDimitry Andric // The simplest strategy possible is to group all LDS variables in a single 56bdd1243dSDimitry Andric // struct and allocate that struct in every kernel such that the original 57bdd1243dSDimitry Andric // variables are always at the same address. LDS is however a limited resource 58bdd1243dSDimitry Andric // so this strategy is unusable in practice. It is not implemented here. 59bdd1243dSDimitry Andric // 60bdd1243dSDimitry Andric // Strategy | Precise allocation | Zero runtime cost | General purpose | 61bdd1243dSDimitry Andric // --------+--------------------+-------------------+-----------------+ 62bdd1243dSDimitry Andric // Module | No | Yes | Yes | 63bdd1243dSDimitry Andric // Table | Yes | No | Yes | 64bdd1243dSDimitry Andric // Kernel | Yes | Yes | No | 65bdd1243dSDimitry Andric // Hybrid | Yes | Partial | Yes | 66bdd1243dSDimitry Andric // 6706c3fb27SDimitry Andric // "Module" spends LDS memory to save cycles. "Table" spends cycles and global 6806c3fb27SDimitry Andric // memory to save LDS. "Kernel" is as fast as kernel allocation but only works 6906c3fb27SDimitry Andric // for variables that are known reachable from a single kernel. "Hybrid" picks 7006c3fb27SDimitry Andric // between all three. When forced to choose between LDS and cycles we minimise 71bdd1243dSDimitry Andric // LDS use. 72bdd1243dSDimitry Andric 73bdd1243dSDimitry Andric // The "module" lowering implemented here finds LDS variables which are used by 74bdd1243dSDimitry Andric // non-kernel functions and creates a new struct with a field for each of those 75bdd1243dSDimitry Andric // LDS variables. Variables that are only used from kernels are excluded. 76bdd1243dSDimitry Andric // 77bdd1243dSDimitry Andric // The "table" lowering implemented here has three components. 78bdd1243dSDimitry Andric // First kernels are assigned a unique integer identifier which is available in 79bdd1243dSDimitry Andric // functions it calls through the intrinsic amdgcn_lds_kernel_id. The integer 80bdd1243dSDimitry Andric // is passed through a specific SGPR, thus works with indirect calls. 81bdd1243dSDimitry Andric // Second, each kernel allocates LDS variables independent of other kernels and 82bdd1243dSDimitry Andric // writes the addresses it chose for each variable into an array in consistent 83bdd1243dSDimitry Andric // order. If the kernel does not allocate a given variable, it writes undef to 84bdd1243dSDimitry Andric // the corresponding array location. These arrays are written to a constant 85bdd1243dSDimitry Andric // table in the order matching the kernel unique integer identifier. 86bdd1243dSDimitry Andric // Third, uses from non-kernel functions are replaced with a table lookup using 87bdd1243dSDimitry Andric // the intrinsic function to find the address of the variable. 88bdd1243dSDimitry Andric // 89bdd1243dSDimitry Andric // "Kernel" lowering is only applicable for variables that are unambiguously 90bdd1243dSDimitry Andric // reachable from exactly one kernel. For those cases, accesses to the variable 91bdd1243dSDimitry Andric // can be lowered to ConstantExpr address of a struct instance specific to that 92bdd1243dSDimitry Andric // one kernel. This is zero cost in space and in compute. It will raise a fatal 93bdd1243dSDimitry Andric // error on any variable that might be reachable from multiple kernels and is 94bdd1243dSDimitry Andric // thus most easily used as part of the hybrid lowering strategy. 95bdd1243dSDimitry Andric // 96bdd1243dSDimitry Andric // Hybrid lowering is a mixture of the above. It uses the zero cost kernel 97bdd1243dSDimitry Andric // lowering where it can. It lowers the variable accessed by the greatest 98bdd1243dSDimitry Andric // number of kernels using the module strategy as that is free for the first 99bdd1243dSDimitry Andric // variable. Any futher variables that can be lowered with the module strategy 100bdd1243dSDimitry Andric // without incurring LDS memory overhead are. The remaining ones are lowered 101bdd1243dSDimitry Andric // via table. 102bdd1243dSDimitry Andric // 103bdd1243dSDimitry Andric // Consequences 104bdd1243dSDimitry Andric // - No heuristics or user controlled magic numbers, hybrid is the right choice 105bdd1243dSDimitry Andric // - Kernels that don't use functions (or have had them all inlined) are not 106bdd1243dSDimitry Andric // affected by any lowering for kernels that do. 107bdd1243dSDimitry Andric // - Kernels that don't make indirect function calls are not affected by those 108bdd1243dSDimitry Andric // that do. 109bdd1243dSDimitry Andric // - Variables which are used by lots of kernels, e.g. those injected by a 110bdd1243dSDimitry Andric // language runtime in most kernels, are expected to have no overhead 111bdd1243dSDimitry Andric // - Implementations that instantiate templates per-kernel where those templates 112bdd1243dSDimitry Andric // use LDS are expected to hit the "Kernel" lowering strategy 113bdd1243dSDimitry Andric // - The runtime properties impose a cost in compiler implementation complexity 114fe6060f1SDimitry Andric // 11506c3fb27SDimitry Andric // Dynamic LDS implementation 11606c3fb27SDimitry Andric // Dynamic LDS is lowered similarly to the "table" strategy above and uses the 11706c3fb27SDimitry Andric // same intrinsic to identify which kernel is at the root of the dynamic call 11806c3fb27SDimitry Andric // graph. This relies on the specified behaviour that all dynamic LDS variables 11906c3fb27SDimitry Andric // alias one another, i.e. are at the same address, with respect to a given 12006c3fb27SDimitry Andric // kernel. Therefore this pass creates new dynamic LDS variables for each kernel 12106c3fb27SDimitry Andric // that allocates any dynamic LDS and builds a table of addresses out of those. 12206c3fb27SDimitry Andric // The AMDGPUPromoteAlloca pass skips kernels that use dynamic LDS. 12306c3fb27SDimitry Andric // The corresponding optimisation for "kernel" lowering where the table lookup 12406c3fb27SDimitry Andric // is elided is not implemented. 12506c3fb27SDimitry Andric // 12606c3fb27SDimitry Andric // 12706c3fb27SDimitry Andric // Implementation notes / limitations 12806c3fb27SDimitry Andric // A single LDS global variable represents an instance per kernel that can reach 12906c3fb27SDimitry Andric // said variables. This pass essentially specialises said variables per kernel. 13006c3fb27SDimitry Andric // Handling ConstantExpr during the pass complicated this significantly so now 13106c3fb27SDimitry Andric // all ConstantExpr uses of LDS variables are expanded to instructions. This 13206c3fb27SDimitry Andric // may need amending when implementing non-undef initialisers. 13306c3fb27SDimitry Andric // 13406c3fb27SDimitry Andric // Lowering is split between this IR pass and the back end. This pass chooses 13506c3fb27SDimitry Andric // where given variables should be allocated and marks them with metadata, 13606c3fb27SDimitry Andric // MD_absolute_symbol. The backend places the variables in coincidentally the 13706c3fb27SDimitry Andric // same location and raises a fatal error if something has gone awry. This works 13806c3fb27SDimitry Andric // in practice because the only pass between this one and the backend that 13906c3fb27SDimitry Andric // changes LDS is PromoteAlloca and the changes it makes do not conflict. 14006c3fb27SDimitry Andric // 14106c3fb27SDimitry Andric // Addresses are written to constant global arrays based on the same metadata. 14206c3fb27SDimitry Andric // 14306c3fb27SDimitry Andric // The backend lowers LDS variables in the order of traversal of the function. 14406c3fb27SDimitry Andric // This is at odds with the deterministic layout required. The workaround is to 14506c3fb27SDimitry Andric // allocate the fixed-address variables immediately upon starting the function 14606c3fb27SDimitry Andric // where they can be placed as intended. This requires a means of mapping from 14706c3fb27SDimitry Andric // the function to the variables that it allocates. For the module scope lds, 14806c3fb27SDimitry Andric // this is via metadata indicating whether the variable is not required. If a 14906c3fb27SDimitry Andric // pass deletes that metadata, a fatal error on disagreement with the absolute 15006c3fb27SDimitry Andric // symbol metadata will occur. For kernel scope and dynamic, this is by _name_ 15106c3fb27SDimitry Andric // correspondence between the function and the variable. It requires the 15206c3fb27SDimitry Andric // kernel to have a name (which is only a limitation for tests in practice) and 15306c3fb27SDimitry Andric // for nothing to rename the corresponding symbols. This is a hazard if the pass 15406c3fb27SDimitry Andric // is run multiple times during debugging. Alternative schemes considered all 15506c3fb27SDimitry Andric // involve bespoke metadata. 15606c3fb27SDimitry Andric // 15706c3fb27SDimitry Andric // If the name correspondence can be replaced, multiple distinct kernels that 15806c3fb27SDimitry Andric // have the same memory layout can map to the same kernel id (as the address 15906c3fb27SDimitry Andric // itself is handled by the absolute symbol metadata) and that will allow more 16006c3fb27SDimitry Andric // uses of the "kernel" style faster lowering and reduce the size of the lookup 16106c3fb27SDimitry Andric // tables. 16206c3fb27SDimitry Andric // 16306c3fb27SDimitry Andric // There is a test that checks this does not fire for a graphics shader. This 16406c3fb27SDimitry Andric // lowering is expected to work for graphics if the isKernel test is changed. 16506c3fb27SDimitry Andric // 16606c3fb27SDimitry Andric // The current markUsedByKernel is sufficient for PromoteAlloca but is elided 16706c3fb27SDimitry Andric // before codegen. Replacing this with an equivalent intrinsic which lasts until 16806c3fb27SDimitry Andric // shortly after the machine function lowering of LDS would help break the name 16906c3fb27SDimitry Andric // mapping. The other part needed is probably to amend PromoteAlloca to embed 17006c3fb27SDimitry Andric // the LDS variables it creates in the same struct created here. That avoids the 17106c3fb27SDimitry Andric // current hazard where a PromoteAlloca LDS variable might be allocated before 17206c3fb27SDimitry Andric // the kernel scope (and thus error on the address check). Given a new invariant 17306c3fb27SDimitry Andric // that no LDS variables exist outside of the structs managed here, and an 17406c3fb27SDimitry Andric // intrinsic that lasts until after the LDS frame lowering, it should be 17506c3fb27SDimitry Andric // possible to drop the name mapping and fold equivalent memory layouts. 17606c3fb27SDimitry Andric // 177fe6060f1SDimitry Andric //===----------------------------------------------------------------------===// 178fe6060f1SDimitry Andric 179fe6060f1SDimitry Andric #include "AMDGPU.h" 1805f757f3fSDimitry Andric #include "AMDGPUTargetMachine.h" 181fe6060f1SDimitry Andric #include "Utils/AMDGPUBaseInfo.h" 18281ad6265SDimitry Andric #include "Utils/AMDGPUMemoryUtils.h" 183972a253aSDimitry Andric #include "llvm/ADT/BitVector.h" 184972a253aSDimitry Andric #include "llvm/ADT/DenseMap.h" 185bdd1243dSDimitry Andric #include "llvm/ADT/DenseSet.h" 186fe6060f1SDimitry Andric #include "llvm/ADT/STLExtras.h" 187bdd1243dSDimitry Andric #include "llvm/ADT/SetOperations.h" 18881ad6265SDimitry Andric #include "llvm/Analysis/CallGraph.h" 1895f757f3fSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 190fe6060f1SDimitry Andric #include "llvm/IR/Constants.h" 191fe6060f1SDimitry Andric #include "llvm/IR/DerivedTypes.h" 192fe6060f1SDimitry Andric #include "llvm/IR/IRBuilder.h" 193fe6060f1SDimitry Andric #include "llvm/IR/InlineAsm.h" 194fe6060f1SDimitry Andric #include "llvm/IR/Instructions.h" 195bdd1243dSDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h" 196349cc55cSDimitry Andric #include "llvm/IR/MDBuilder.h" 19706c3fb27SDimitry Andric #include "llvm/IR/ReplaceConstant.h" 198fe6060f1SDimitry Andric #include "llvm/InitializePasses.h" 199fe6060f1SDimitry Andric #include "llvm/Pass.h" 200fe6060f1SDimitry Andric #include "llvm/Support/CommandLine.h" 201fe6060f1SDimitry Andric #include "llvm/Support/Debug.h" 20206c3fb27SDimitry Andric #include "llvm/Support/Format.h" 203fe6060f1SDimitry Andric #include "llvm/Support/OptimizedStructLayout.h" 20406c3fb27SDimitry Andric #include "llvm/Support/raw_ostream.h" 205bdd1243dSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 206fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h" 207bdd1243dSDimitry Andric 208fe6060f1SDimitry Andric #include <vector> 209fe6060f1SDimitry Andric 210bdd1243dSDimitry Andric #include <cstdio> 211bdd1243dSDimitry Andric 212fe6060f1SDimitry Andric #define DEBUG_TYPE "amdgpu-lower-module-lds" 213fe6060f1SDimitry Andric 214fe6060f1SDimitry Andric using namespace llvm; 215*0fca6ea1SDimitry Andric using namespace AMDGPU; 216fe6060f1SDimitry Andric 217bdd1243dSDimitry Andric namespace { 218bdd1243dSDimitry Andric 219bdd1243dSDimitry Andric cl::opt<bool> SuperAlignLDSGlobals( 220fe6060f1SDimitry Andric "amdgpu-super-align-lds-globals", 221fe6060f1SDimitry Andric cl::desc("Increase alignment of LDS if it is not on align boundary"), 222fe6060f1SDimitry Andric cl::init(true), cl::Hidden); 223fe6060f1SDimitry Andric 224bdd1243dSDimitry Andric enum class LoweringKind { module, table, kernel, hybrid }; 225bdd1243dSDimitry Andric cl::opt<LoweringKind> LoweringKindLoc( 226bdd1243dSDimitry Andric "amdgpu-lower-module-lds-strategy", 227bdd1243dSDimitry Andric cl::desc("Specify lowering strategy for function LDS access:"), cl::Hidden, 22806c3fb27SDimitry Andric cl::init(LoweringKind::hybrid), 229bdd1243dSDimitry Andric cl::values( 230bdd1243dSDimitry Andric clEnumValN(LoweringKind::table, "table", "Lower via table lookup"), 231bdd1243dSDimitry Andric clEnumValN(LoweringKind::module, "module", "Lower via module struct"), 232bdd1243dSDimitry Andric clEnumValN( 233bdd1243dSDimitry Andric LoweringKind::kernel, "kernel", 234bdd1243dSDimitry Andric "Lower variables reachable from one kernel, otherwise abort"), 235bdd1243dSDimitry Andric clEnumValN(LoweringKind::hybrid, "hybrid", 236bdd1243dSDimitry Andric "Lower via mixture of above strategies"))); 237bdd1243dSDimitry Andric 23806c3fb27SDimitry Andric template <typename T> std::vector<T> sortByName(std::vector<T> &&V) { 23906c3fb27SDimitry Andric llvm::sort(V.begin(), V.end(), [](const auto *L, const auto *R) { 24006c3fb27SDimitry Andric return L->getName() < R->getName(); 24106c3fb27SDimitry Andric }); 24206c3fb27SDimitry Andric return {std::move(V)}; 24306c3fb27SDimitry Andric } 24406c3fb27SDimitry Andric 2455f757f3fSDimitry Andric class AMDGPULowerModuleLDS { 2465f757f3fSDimitry Andric const AMDGPUTargetMachine &TM; 247fe6060f1SDimitry Andric 248fe6060f1SDimitry Andric static void 249bdd1243dSDimitry Andric removeLocalVarsFromUsedLists(Module &M, 250bdd1243dSDimitry Andric const DenseSet<GlobalVariable *> &LocalVars) { 251972a253aSDimitry Andric // The verifier rejects used lists containing an inttoptr of a constant 252972a253aSDimitry Andric // so remove the variables from these lists before replaceAllUsesWith 253bdd1243dSDimitry Andric SmallPtrSet<Constant *, 8> LocalVarsSet; 2540eae32dcSDimitry Andric for (GlobalVariable *LocalVar : LocalVars) 255bdd1243dSDimitry Andric LocalVarsSet.insert(cast<Constant>(LocalVar->stripPointerCasts())); 256bdd1243dSDimitry Andric 257bdd1243dSDimitry Andric removeFromUsedLists( 258bdd1243dSDimitry Andric M, [&LocalVarsSet](Constant *C) { return LocalVarsSet.count(C); }); 259bdd1243dSDimitry Andric 260bdd1243dSDimitry Andric for (GlobalVariable *LocalVar : LocalVars) 261bdd1243dSDimitry Andric LocalVar->removeDeadConstantUsers(); 262fe6060f1SDimitry Andric } 263fe6060f1SDimitry Andric 26406c3fb27SDimitry Andric static void markUsedByKernel(Function *Func, GlobalVariable *SGV) { 265fe6060f1SDimitry Andric // The llvm.amdgcn.module.lds instance is implicitly used by all kernels 266fe6060f1SDimitry Andric // that might call a function which accesses a field within it. This is 267fe6060f1SDimitry Andric // presently approximated to 'all kernels' if there are any such functions 268349cc55cSDimitry Andric // in the module. This implicit use is redefined as an explicit use here so 269fe6060f1SDimitry Andric // that later passes, specifically PromoteAlloca, account for the required 270fe6060f1SDimitry Andric // memory without any knowledge of this transform. 271fe6060f1SDimitry Andric 272fe6060f1SDimitry Andric // An operand bundle on llvm.donothing works because the call instruction 273fe6060f1SDimitry Andric // survives until after the last pass that needs to account for LDS. It is 274fe6060f1SDimitry Andric // better than inline asm as the latter survives until the end of codegen. A 275fe6060f1SDimitry Andric // totally robust solution would be a function with the same semantics as 276fe6060f1SDimitry Andric // llvm.donothing that takes a pointer to the instance and is lowered to a 277fe6060f1SDimitry Andric // no-op after LDS is allocated, but that is not presently necessary. 278fe6060f1SDimitry Andric 27906c3fb27SDimitry Andric // This intrinsic is eliminated shortly before instruction selection. It 28006c3fb27SDimitry Andric // does not suffice to indicate to ISel that a given global which is not 28106c3fb27SDimitry Andric // immediately used by the kernel must still be allocated by it. An 28206c3fb27SDimitry Andric // equivalent target specific intrinsic which lasts until immediately after 28306c3fb27SDimitry Andric // codegen would suffice for that, but one would still need to ensure that 284*0fca6ea1SDimitry Andric // the variables are allocated in the anticipated order. 2855f757f3fSDimitry Andric BasicBlock *Entry = &Func->getEntryBlock(); 2865f757f3fSDimitry Andric IRBuilder<> Builder(Entry, Entry->getFirstNonPHIIt()); 287fe6060f1SDimitry Andric 288fe6060f1SDimitry Andric Function *Decl = 289fe6060f1SDimitry Andric Intrinsic::getDeclaration(Func->getParent(), Intrinsic::donothing, {}); 290fe6060f1SDimitry Andric 29106c3fb27SDimitry Andric Value *UseInstance[1] = { 29206c3fb27SDimitry Andric Builder.CreateConstInBoundsGEP1_32(SGV->getValueType(), SGV, 0)}; 293fe6060f1SDimitry Andric 29406c3fb27SDimitry Andric Builder.CreateCall( 29506c3fb27SDimitry Andric Decl, {}, {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)}); 296fe6060f1SDimitry Andric } 297fe6060f1SDimitry Andric 298fe6060f1SDimitry Andric public: 2995f757f3fSDimitry Andric AMDGPULowerModuleLDS(const AMDGPUTargetMachine &TM_) : TM(TM_) {} 300fe6060f1SDimitry Andric 301bdd1243dSDimitry Andric struct LDSVariableReplacement { 302bdd1243dSDimitry Andric GlobalVariable *SGV = nullptr; 303bdd1243dSDimitry Andric DenseMap<GlobalVariable *, Constant *> LDSVarsToConstantGEP; 304bdd1243dSDimitry Andric }; 305bdd1243dSDimitry Andric 306bdd1243dSDimitry Andric // remap from lds global to a constantexpr gep to where it has been moved to 307bdd1243dSDimitry Andric // for each kernel 308bdd1243dSDimitry Andric // an array with an element for each kernel containing where the corresponding 309bdd1243dSDimitry Andric // variable was remapped to 310bdd1243dSDimitry Andric 311bdd1243dSDimitry Andric static Constant *getAddressesOfVariablesInKernel( 312bdd1243dSDimitry Andric LLVMContext &Ctx, ArrayRef<GlobalVariable *> Variables, 31306c3fb27SDimitry Andric const DenseMap<GlobalVariable *, Constant *> &LDSVarsToConstantGEP) { 314bdd1243dSDimitry Andric // Create a ConstantArray containing the address of each Variable within the 315bdd1243dSDimitry Andric // kernel corresponding to LDSVarsToConstantGEP, or poison if that kernel 316bdd1243dSDimitry Andric // does not allocate it 317bdd1243dSDimitry Andric // TODO: Drop the ptrtoint conversion 318bdd1243dSDimitry Andric 319bdd1243dSDimitry Andric Type *I32 = Type::getInt32Ty(Ctx); 320bdd1243dSDimitry Andric 321bdd1243dSDimitry Andric ArrayType *KernelOffsetsType = ArrayType::get(I32, Variables.size()); 322bdd1243dSDimitry Andric 323bdd1243dSDimitry Andric SmallVector<Constant *> Elements; 324*0fca6ea1SDimitry Andric for (GlobalVariable *GV : Variables) { 32506c3fb27SDimitry Andric auto ConstantGepIt = LDSVarsToConstantGEP.find(GV); 32606c3fb27SDimitry Andric if (ConstantGepIt != LDSVarsToConstantGEP.end()) { 32706c3fb27SDimitry Andric auto elt = ConstantExpr::getPtrToInt(ConstantGepIt->second, I32); 328bdd1243dSDimitry Andric Elements.push_back(elt); 329bdd1243dSDimitry Andric } else { 330bdd1243dSDimitry Andric Elements.push_back(PoisonValue::get(I32)); 331bdd1243dSDimitry Andric } 332bdd1243dSDimitry Andric } 333bdd1243dSDimitry Andric return ConstantArray::get(KernelOffsetsType, Elements); 334bdd1243dSDimitry Andric } 335bdd1243dSDimitry Andric 336bdd1243dSDimitry Andric static GlobalVariable *buildLookupTable( 337bdd1243dSDimitry Andric Module &M, ArrayRef<GlobalVariable *> Variables, 338bdd1243dSDimitry Andric ArrayRef<Function *> kernels, 339bdd1243dSDimitry Andric DenseMap<Function *, LDSVariableReplacement> &KernelToReplacement) { 340bdd1243dSDimitry Andric if (Variables.empty()) { 341bdd1243dSDimitry Andric return nullptr; 342bdd1243dSDimitry Andric } 343bdd1243dSDimitry Andric LLVMContext &Ctx = M.getContext(); 344bdd1243dSDimitry Andric 345bdd1243dSDimitry Andric const size_t NumberVariables = Variables.size(); 346bdd1243dSDimitry Andric const size_t NumberKernels = kernels.size(); 347bdd1243dSDimitry Andric 348bdd1243dSDimitry Andric ArrayType *KernelOffsetsType = 349bdd1243dSDimitry Andric ArrayType::get(Type::getInt32Ty(Ctx), NumberVariables); 350bdd1243dSDimitry Andric 351bdd1243dSDimitry Andric ArrayType *AllKernelsOffsetsType = 352bdd1243dSDimitry Andric ArrayType::get(KernelOffsetsType, NumberKernels); 353bdd1243dSDimitry Andric 35406c3fb27SDimitry Andric Constant *Missing = PoisonValue::get(KernelOffsetsType); 355bdd1243dSDimitry Andric std::vector<Constant *> overallConstantExprElts(NumberKernels); 356bdd1243dSDimitry Andric for (size_t i = 0; i < NumberKernels; i++) { 35706c3fb27SDimitry Andric auto Replacement = KernelToReplacement.find(kernels[i]); 35806c3fb27SDimitry Andric overallConstantExprElts[i] = 35906c3fb27SDimitry Andric (Replacement == KernelToReplacement.end()) 36006c3fb27SDimitry Andric ? Missing 36106c3fb27SDimitry Andric : getAddressesOfVariablesInKernel( 36206c3fb27SDimitry Andric Ctx, Variables, Replacement->second.LDSVarsToConstantGEP); 363bdd1243dSDimitry Andric } 364bdd1243dSDimitry Andric 365bdd1243dSDimitry Andric Constant *init = 366bdd1243dSDimitry Andric ConstantArray::get(AllKernelsOffsetsType, overallConstantExprElts); 367bdd1243dSDimitry Andric 368bdd1243dSDimitry Andric return new GlobalVariable( 369bdd1243dSDimitry Andric M, AllKernelsOffsetsType, true, GlobalValue::InternalLinkage, init, 370bdd1243dSDimitry Andric "llvm.amdgcn.lds.offset.table", nullptr, GlobalValue::NotThreadLocal, 371bdd1243dSDimitry Andric AMDGPUAS::CONSTANT_ADDRESS); 372bdd1243dSDimitry Andric } 373bdd1243dSDimitry Andric 37406c3fb27SDimitry Andric void replaceUseWithTableLookup(Module &M, IRBuilder<> &Builder, 37506c3fb27SDimitry Andric GlobalVariable *LookupTable, 37606c3fb27SDimitry Andric GlobalVariable *GV, Use &U, 37706c3fb27SDimitry Andric Value *OptionalIndex) { 37806c3fb27SDimitry Andric // Table is a constant array of the same length as OrderedKernels 379bdd1243dSDimitry Andric LLVMContext &Ctx = M.getContext(); 380bdd1243dSDimitry Andric Type *I32 = Type::getInt32Ty(Ctx); 38106c3fb27SDimitry Andric auto *I = cast<Instruction>(U.getUser()); 382bdd1243dSDimitry Andric 38306c3fb27SDimitry Andric Value *tableKernelIndex = getTableLookupKernelIndex(M, I->getFunction()); 384bdd1243dSDimitry Andric 385bdd1243dSDimitry Andric if (auto *Phi = dyn_cast<PHINode>(I)) { 386bdd1243dSDimitry Andric BasicBlock *BB = Phi->getIncomingBlock(U); 387bdd1243dSDimitry Andric Builder.SetInsertPoint(&(*(BB->getFirstInsertionPt()))); 388bdd1243dSDimitry Andric } else { 389bdd1243dSDimitry Andric Builder.SetInsertPoint(I); 390bdd1243dSDimitry Andric } 391bdd1243dSDimitry Andric 39206c3fb27SDimitry Andric SmallVector<Value *, 3> GEPIdx = { 393bdd1243dSDimitry Andric ConstantInt::get(I32, 0), 394bdd1243dSDimitry Andric tableKernelIndex, 395bdd1243dSDimitry Andric }; 39606c3fb27SDimitry Andric if (OptionalIndex) 39706c3fb27SDimitry Andric GEPIdx.push_back(OptionalIndex); 398bdd1243dSDimitry Andric 399bdd1243dSDimitry Andric Value *Address = Builder.CreateInBoundsGEP( 400bdd1243dSDimitry Andric LookupTable->getValueType(), LookupTable, GEPIdx, GV->getName()); 401bdd1243dSDimitry Andric 402bdd1243dSDimitry Andric Value *loaded = Builder.CreateLoad(I32, Address); 403bdd1243dSDimitry Andric 404bdd1243dSDimitry Andric Value *replacement = 405bdd1243dSDimitry Andric Builder.CreateIntToPtr(loaded, GV->getType(), GV->getName()); 406bdd1243dSDimitry Andric 407bdd1243dSDimitry Andric U.set(replacement); 408bdd1243dSDimitry Andric } 40906c3fb27SDimitry Andric 41006c3fb27SDimitry Andric void replaceUsesInInstructionsWithTableLookup( 41106c3fb27SDimitry Andric Module &M, ArrayRef<GlobalVariable *> ModuleScopeVariables, 41206c3fb27SDimitry Andric GlobalVariable *LookupTable) { 41306c3fb27SDimitry Andric 41406c3fb27SDimitry Andric LLVMContext &Ctx = M.getContext(); 41506c3fb27SDimitry Andric IRBuilder<> Builder(Ctx); 41606c3fb27SDimitry Andric Type *I32 = Type::getInt32Ty(Ctx); 41706c3fb27SDimitry Andric 41806c3fb27SDimitry Andric for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) { 41906c3fb27SDimitry Andric auto *GV = ModuleScopeVariables[Index]; 42006c3fb27SDimitry Andric 42106c3fb27SDimitry Andric for (Use &U : make_early_inc_range(GV->uses())) { 42206c3fb27SDimitry Andric auto *I = dyn_cast<Instruction>(U.getUser()); 42306c3fb27SDimitry Andric if (!I) 42406c3fb27SDimitry Andric continue; 42506c3fb27SDimitry Andric 42606c3fb27SDimitry Andric replaceUseWithTableLookup(M, Builder, LookupTable, GV, U, 42706c3fb27SDimitry Andric ConstantInt::get(I32, Index)); 42806c3fb27SDimitry Andric } 429bdd1243dSDimitry Andric } 430bdd1243dSDimitry Andric } 431bdd1243dSDimitry Andric 432bdd1243dSDimitry Andric static DenseSet<Function *> kernelsThatIndirectlyAccessAnyOfPassedVariables( 433bdd1243dSDimitry Andric Module &M, LDSUsesInfoTy &LDSUsesInfo, 434bdd1243dSDimitry Andric DenseSet<GlobalVariable *> const &VariableSet) { 435bdd1243dSDimitry Andric 436bdd1243dSDimitry Andric DenseSet<Function *> KernelSet; 437bdd1243dSDimitry Andric 43806c3fb27SDimitry Andric if (VariableSet.empty()) 43906c3fb27SDimitry Andric return KernelSet; 440bdd1243dSDimitry Andric 441bdd1243dSDimitry Andric for (Function &Func : M.functions()) { 442bdd1243dSDimitry Andric if (Func.isDeclaration() || !isKernelLDS(&Func)) 443bdd1243dSDimitry Andric continue; 444bdd1243dSDimitry Andric for (GlobalVariable *GV : LDSUsesInfo.indirect_access[&Func]) { 445bdd1243dSDimitry Andric if (VariableSet.contains(GV)) { 446bdd1243dSDimitry Andric KernelSet.insert(&Func); 447bdd1243dSDimitry Andric break; 448bdd1243dSDimitry Andric } 449bdd1243dSDimitry Andric } 450bdd1243dSDimitry Andric } 451bdd1243dSDimitry Andric 452bdd1243dSDimitry Andric return KernelSet; 453bdd1243dSDimitry Andric } 454bdd1243dSDimitry Andric 455bdd1243dSDimitry Andric static GlobalVariable * 456bdd1243dSDimitry Andric chooseBestVariableForModuleStrategy(const DataLayout &DL, 457bdd1243dSDimitry Andric VariableFunctionMap &LDSVars) { 458bdd1243dSDimitry Andric // Find the global variable with the most indirect uses from kernels 459bdd1243dSDimitry Andric 460bdd1243dSDimitry Andric struct CandidateTy { 461bdd1243dSDimitry Andric GlobalVariable *GV = nullptr; 462bdd1243dSDimitry Andric size_t UserCount = 0; 463bdd1243dSDimitry Andric size_t Size = 0; 464bdd1243dSDimitry Andric 465bdd1243dSDimitry Andric CandidateTy() = default; 466bdd1243dSDimitry Andric 467bdd1243dSDimitry Andric CandidateTy(GlobalVariable *GV, uint64_t UserCount, uint64_t AllocSize) 468bdd1243dSDimitry Andric : GV(GV), UserCount(UserCount), Size(AllocSize) {} 469bdd1243dSDimitry Andric 470bdd1243dSDimitry Andric bool operator<(const CandidateTy &Other) const { 471bdd1243dSDimitry Andric // Fewer users makes module scope variable less attractive 472bdd1243dSDimitry Andric if (UserCount < Other.UserCount) { 473bdd1243dSDimitry Andric return true; 474bdd1243dSDimitry Andric } 475bdd1243dSDimitry Andric if (UserCount > Other.UserCount) { 476bdd1243dSDimitry Andric return false; 477bdd1243dSDimitry Andric } 478bdd1243dSDimitry Andric 479bdd1243dSDimitry Andric // Bigger makes module scope variable less attractive 480bdd1243dSDimitry Andric if (Size < Other.Size) { 481bdd1243dSDimitry Andric return false; 482bdd1243dSDimitry Andric } 483bdd1243dSDimitry Andric 484bdd1243dSDimitry Andric if (Size > Other.Size) { 485bdd1243dSDimitry Andric return true; 486bdd1243dSDimitry Andric } 487bdd1243dSDimitry Andric 488bdd1243dSDimitry Andric // Arbitrary but consistent 489bdd1243dSDimitry Andric return GV->getName() < Other.GV->getName(); 490bdd1243dSDimitry Andric } 491bdd1243dSDimitry Andric }; 492bdd1243dSDimitry Andric 493bdd1243dSDimitry Andric CandidateTy MostUsed; 494bdd1243dSDimitry Andric 495bdd1243dSDimitry Andric for (auto &K : LDSVars) { 496bdd1243dSDimitry Andric GlobalVariable *GV = K.first; 497bdd1243dSDimitry Andric if (K.second.size() <= 1) { 498bdd1243dSDimitry Andric // A variable reachable by only one kernel is best lowered with kernel 499bdd1243dSDimitry Andric // strategy 500bdd1243dSDimitry Andric continue; 501bdd1243dSDimitry Andric } 50206c3fb27SDimitry Andric CandidateTy Candidate( 50306c3fb27SDimitry Andric GV, K.second.size(), 504bdd1243dSDimitry Andric DL.getTypeAllocSize(GV->getValueType()).getFixedValue()); 505bdd1243dSDimitry Andric if (MostUsed < Candidate) 506bdd1243dSDimitry Andric MostUsed = Candidate; 507bdd1243dSDimitry Andric } 508bdd1243dSDimitry Andric 509bdd1243dSDimitry Andric return MostUsed.GV; 510bdd1243dSDimitry Andric } 511bdd1243dSDimitry Andric 51206c3fb27SDimitry Andric static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV, 51306c3fb27SDimitry Andric uint32_t Address) { 51406c3fb27SDimitry Andric // Write the specified address into metadata where it can be retrieved by 51506c3fb27SDimitry Andric // the assembler. Format is a half open range, [Address Address+1) 51606c3fb27SDimitry Andric LLVMContext &Ctx = M->getContext(); 51706c3fb27SDimitry Andric auto *IntTy = 51806c3fb27SDimitry Andric M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS); 51906c3fb27SDimitry Andric auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address)); 52006c3fb27SDimitry Andric auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1)); 52106c3fb27SDimitry Andric GV->setMetadata(LLVMContext::MD_absolute_symbol, 52206c3fb27SDimitry Andric MDNode::get(Ctx, {MinC, MaxC})); 52306c3fb27SDimitry Andric } 524972a253aSDimitry Andric 52506c3fb27SDimitry Andric DenseMap<Function *, Value *> tableKernelIndexCache; 52606c3fb27SDimitry Andric Value *getTableLookupKernelIndex(Module &M, Function *F) { 52706c3fb27SDimitry Andric // Accesses from a function use the amdgcn_lds_kernel_id intrinsic which 52806c3fb27SDimitry Andric // lowers to a read from a live in register. Emit it once in the entry 52906c3fb27SDimitry Andric // block to spare deduplicating it later. 53006c3fb27SDimitry Andric auto [It, Inserted] = tableKernelIndexCache.try_emplace(F); 53106c3fb27SDimitry Andric if (Inserted) { 53206c3fb27SDimitry Andric Function *Decl = 53306c3fb27SDimitry Andric Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_lds_kernel_id, {}); 534fe6060f1SDimitry Andric 53506c3fb27SDimitry Andric auto InsertAt = F->getEntryBlock().getFirstNonPHIOrDbgOrAlloca(); 53606c3fb27SDimitry Andric IRBuilder<> Builder(&*InsertAt); 537972a253aSDimitry Andric 53806c3fb27SDimitry Andric It->second = Builder.CreateCall(Decl, {}); 53906c3fb27SDimitry Andric } 540972a253aSDimitry Andric 54106c3fb27SDimitry Andric return It->second; 54206c3fb27SDimitry Andric } 54306c3fb27SDimitry Andric 54406c3fb27SDimitry Andric static std::vector<Function *> assignLDSKernelIDToEachKernel( 54506c3fb27SDimitry Andric Module *M, DenseSet<Function *> const &KernelsThatAllocateTableLDS, 54606c3fb27SDimitry Andric DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS) { 547*0fca6ea1SDimitry Andric // Associate kernels in the set with an arbitrary but reproducible order and 54806c3fb27SDimitry Andric // annotate them with that order in metadata. This metadata is recognised by 54906c3fb27SDimitry Andric // the backend and lowered to a SGPR which can be read from using 55006c3fb27SDimitry Andric // amdgcn_lds_kernel_id. 55106c3fb27SDimitry Andric 55206c3fb27SDimitry Andric std::vector<Function *> OrderedKernels; 55306c3fb27SDimitry Andric if (!KernelsThatAllocateTableLDS.empty() || 55406c3fb27SDimitry Andric !KernelsThatIndirectlyAllocateDynamicLDS.empty()) { 55506c3fb27SDimitry Andric 55606c3fb27SDimitry Andric for (Function &Func : M->functions()) { 55706c3fb27SDimitry Andric if (Func.isDeclaration()) 55806c3fb27SDimitry Andric continue; 55906c3fb27SDimitry Andric if (!isKernelLDS(&Func)) 56006c3fb27SDimitry Andric continue; 56106c3fb27SDimitry Andric 56206c3fb27SDimitry Andric if (KernelsThatAllocateTableLDS.contains(&Func) || 56306c3fb27SDimitry Andric KernelsThatIndirectlyAllocateDynamicLDS.contains(&Func)) { 56406c3fb27SDimitry Andric assert(Func.hasName()); // else fatal error earlier 56506c3fb27SDimitry Andric OrderedKernels.push_back(&Func); 566bdd1243dSDimitry Andric } 567bdd1243dSDimitry Andric } 568972a253aSDimitry Andric 56906c3fb27SDimitry Andric // Put them in an arbitrary but reproducible order 57006c3fb27SDimitry Andric OrderedKernels = sortByName(std::move(OrderedKernels)); 571972a253aSDimitry Andric 57206c3fb27SDimitry Andric // Annotate the kernels with their order in this vector 57306c3fb27SDimitry Andric LLVMContext &Ctx = M->getContext(); 57406c3fb27SDimitry Andric IRBuilder<> Builder(Ctx); 57506c3fb27SDimitry Andric 57606c3fb27SDimitry Andric if (OrderedKernels.size() > UINT32_MAX) { 57706c3fb27SDimitry Andric // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU 57806c3fb27SDimitry Andric report_fatal_error("Unimplemented LDS lowering for > 2**32 kernels"); 57906c3fb27SDimitry Andric } 58006c3fb27SDimitry Andric 58106c3fb27SDimitry Andric for (size_t i = 0; i < OrderedKernels.size(); i++) { 58206c3fb27SDimitry Andric Metadata *AttrMDArgs[1] = { 58306c3fb27SDimitry Andric ConstantAsMetadata::get(Builder.getInt32(i)), 58406c3fb27SDimitry Andric }; 58506c3fb27SDimitry Andric OrderedKernels[i]->setMetadata("llvm.amdgcn.lds.kernel.id", 58606c3fb27SDimitry Andric MDNode::get(Ctx, AttrMDArgs)); 58706c3fb27SDimitry Andric } 58806c3fb27SDimitry Andric } 58906c3fb27SDimitry Andric return OrderedKernels; 59006c3fb27SDimitry Andric } 59106c3fb27SDimitry Andric 59206c3fb27SDimitry Andric static void partitionVariablesIntoIndirectStrategies( 59306c3fb27SDimitry Andric Module &M, LDSUsesInfoTy const &LDSUsesInfo, 59406c3fb27SDimitry Andric VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly, 59506c3fb27SDimitry Andric DenseSet<GlobalVariable *> &ModuleScopeVariables, 59606c3fb27SDimitry Andric DenseSet<GlobalVariable *> &TableLookupVariables, 59706c3fb27SDimitry Andric DenseSet<GlobalVariable *> &KernelAccessVariables, 59806c3fb27SDimitry Andric DenseSet<GlobalVariable *> &DynamicVariables) { 59906c3fb27SDimitry Andric 600bdd1243dSDimitry Andric GlobalVariable *HybridModuleRoot = 601bdd1243dSDimitry Andric LoweringKindLoc != LoweringKind::hybrid 602bdd1243dSDimitry Andric ? nullptr 603bdd1243dSDimitry Andric : chooseBestVariableForModuleStrategy( 60406c3fb27SDimitry Andric M.getDataLayout(), LDSToKernelsThatNeedToAccessItIndirectly); 605972a253aSDimitry Andric 606bdd1243dSDimitry Andric DenseSet<Function *> const EmptySet; 607bdd1243dSDimitry Andric DenseSet<Function *> const &HybridModuleRootKernels = 608bdd1243dSDimitry Andric HybridModuleRoot 609bdd1243dSDimitry Andric ? LDSToKernelsThatNeedToAccessItIndirectly[HybridModuleRoot] 610bdd1243dSDimitry Andric : EmptySet; 611bdd1243dSDimitry Andric 612bdd1243dSDimitry Andric for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) { 613bdd1243dSDimitry Andric // Each iteration of this loop assigns exactly one global variable to 614bdd1243dSDimitry Andric // exactly one of the implementation strategies. 615bdd1243dSDimitry Andric 616bdd1243dSDimitry Andric GlobalVariable *GV = K.first; 617bdd1243dSDimitry Andric assert(AMDGPU::isLDSVariableToLower(*GV)); 618bdd1243dSDimitry Andric assert(K.second.size() != 0); 619bdd1243dSDimitry Andric 62006c3fb27SDimitry Andric if (AMDGPU::isDynamicLDS(*GV)) { 62106c3fb27SDimitry Andric DynamicVariables.insert(GV); 62206c3fb27SDimitry Andric continue; 62306c3fb27SDimitry Andric } 62406c3fb27SDimitry Andric 625bdd1243dSDimitry Andric switch (LoweringKindLoc) { 626bdd1243dSDimitry Andric case LoweringKind::module: 627bdd1243dSDimitry Andric ModuleScopeVariables.insert(GV); 628bdd1243dSDimitry Andric break; 629bdd1243dSDimitry Andric 630bdd1243dSDimitry Andric case LoweringKind::table: 631bdd1243dSDimitry Andric TableLookupVariables.insert(GV); 632bdd1243dSDimitry Andric break; 633bdd1243dSDimitry Andric 634bdd1243dSDimitry Andric case LoweringKind::kernel: 635bdd1243dSDimitry Andric if (K.second.size() == 1) { 636bdd1243dSDimitry Andric KernelAccessVariables.insert(GV); 637972a253aSDimitry Andric } else { 638bdd1243dSDimitry Andric report_fatal_error( 639bdd1243dSDimitry Andric "cannot lower LDS '" + GV->getName() + 640bdd1243dSDimitry Andric "' to kernel access as it is reachable from multiple kernels"); 641bdd1243dSDimitry Andric } 642bdd1243dSDimitry Andric break; 643bdd1243dSDimitry Andric 644bdd1243dSDimitry Andric case LoweringKind::hybrid: { 645bdd1243dSDimitry Andric if (GV == HybridModuleRoot) { 646bdd1243dSDimitry Andric assert(K.second.size() != 1); 647bdd1243dSDimitry Andric ModuleScopeVariables.insert(GV); 648bdd1243dSDimitry Andric } else if (K.second.size() == 1) { 649bdd1243dSDimitry Andric KernelAccessVariables.insert(GV); 650bdd1243dSDimitry Andric } else if (set_is_subset(K.second, HybridModuleRootKernels)) { 651bdd1243dSDimitry Andric ModuleScopeVariables.insert(GV); 652bdd1243dSDimitry Andric } else { 653bdd1243dSDimitry Andric TableLookupVariables.insert(GV); 654bdd1243dSDimitry Andric } 655bdd1243dSDimitry Andric break; 656bdd1243dSDimitry Andric } 657bdd1243dSDimitry Andric } 658bdd1243dSDimitry Andric } 659bdd1243dSDimitry Andric 66006c3fb27SDimitry Andric // All LDS variables accessed indirectly have now been partitioned into 66106c3fb27SDimitry Andric // the distinct lowering strategies. 662bdd1243dSDimitry Andric assert(ModuleScopeVariables.size() + TableLookupVariables.size() + 66306c3fb27SDimitry Andric KernelAccessVariables.size() + DynamicVariables.size() == 664bdd1243dSDimitry Andric LDSToKernelsThatNeedToAccessItIndirectly.size()); 66506c3fb27SDimitry Andric } 666bdd1243dSDimitry Andric 66706c3fb27SDimitry Andric static GlobalVariable *lowerModuleScopeStructVariables( 66806c3fb27SDimitry Andric Module &M, DenseSet<GlobalVariable *> const &ModuleScopeVariables, 66906c3fb27SDimitry Andric DenseSet<Function *> const &KernelsThatAllocateModuleLDS) { 67006c3fb27SDimitry Andric // Create a struct to hold the ModuleScopeVariables 67106c3fb27SDimitry Andric // Replace all uses of those variables from non-kernel functions with the 67206c3fb27SDimitry Andric // new struct instance Replace only the uses from kernel functions that will 67306c3fb27SDimitry Andric // allocate this instance. That is a space optimisation - kernels that use a 67406c3fb27SDimitry Andric // subset of the module scope struct and do not need to allocate it for 67506c3fb27SDimitry Andric // indirect calls will only allocate the subset they use (they do so as part 67606c3fb27SDimitry Andric // of the per-kernel lowering). 67706c3fb27SDimitry Andric if (ModuleScopeVariables.empty()) { 67806c3fb27SDimitry Andric return nullptr; 67906c3fb27SDimitry Andric } 680bdd1243dSDimitry Andric 68106c3fb27SDimitry Andric LLVMContext &Ctx = M.getContext(); 68206c3fb27SDimitry Andric 683bdd1243dSDimitry Andric LDSVariableReplacement ModuleScopeReplacement = 684bdd1243dSDimitry Andric createLDSVariableReplacement(M, "llvm.amdgcn.module.lds", 685bdd1243dSDimitry Andric ModuleScopeVariables); 686bdd1243dSDimitry Andric 68706c3fb27SDimitry Andric appendToCompilerUsed(M, {static_cast<GlobalValue *>( 688bdd1243dSDimitry Andric ConstantExpr::getPointerBitCastOrAddrSpaceCast( 689bdd1243dSDimitry Andric cast<Constant>(ModuleScopeReplacement.SGV), 6905f757f3fSDimitry Andric PointerType::getUnqual(Ctx)))}); 691bdd1243dSDimitry Andric 69206c3fb27SDimitry Andric // module.lds will be allocated at zero in any kernel that allocates it 69306c3fb27SDimitry Andric recordLDSAbsoluteAddress(&M, ModuleScopeReplacement.SGV, 0); 69406c3fb27SDimitry Andric 695bdd1243dSDimitry Andric // historic 696bdd1243dSDimitry Andric removeLocalVarsFromUsedLists(M, ModuleScopeVariables); 697bdd1243dSDimitry Andric 698bdd1243dSDimitry Andric // Replace all uses of module scope variable from non-kernel functions 699bdd1243dSDimitry Andric replaceLDSVariablesWithStruct( 700bdd1243dSDimitry Andric M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) { 701bdd1243dSDimitry Andric Instruction *I = dyn_cast<Instruction>(U.getUser()); 702bdd1243dSDimitry Andric if (!I) { 703bdd1243dSDimitry Andric return false; 704bdd1243dSDimitry Andric } 705bdd1243dSDimitry Andric Function *F = I->getFunction(); 706bdd1243dSDimitry Andric return !isKernelLDS(F); 707bdd1243dSDimitry Andric }); 708bdd1243dSDimitry Andric 709bdd1243dSDimitry Andric // Replace uses of module scope variable from kernel functions that 710bdd1243dSDimitry Andric // allocate the module scope variable, otherwise leave them unchanged 711bdd1243dSDimitry Andric // Record on each kernel whether the module scope global is used by it 712bdd1243dSDimitry Andric 713bdd1243dSDimitry Andric for (Function &Func : M.functions()) { 714bdd1243dSDimitry Andric if (Func.isDeclaration() || !isKernelLDS(&Func)) 715bdd1243dSDimitry Andric continue; 716bdd1243dSDimitry Andric 717bdd1243dSDimitry Andric if (KernelsThatAllocateModuleLDS.contains(&Func)) { 718bdd1243dSDimitry Andric replaceLDSVariablesWithStruct( 719bdd1243dSDimitry Andric M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) { 720bdd1243dSDimitry Andric Instruction *I = dyn_cast<Instruction>(U.getUser()); 721bdd1243dSDimitry Andric if (!I) { 722bdd1243dSDimitry Andric return false; 723bdd1243dSDimitry Andric } 724bdd1243dSDimitry Andric Function *F = I->getFunction(); 725bdd1243dSDimitry Andric return F == &Func; 726bdd1243dSDimitry Andric }); 727bdd1243dSDimitry Andric 72806c3fb27SDimitry Andric markUsedByKernel(&Func, ModuleScopeReplacement.SGV); 729972a253aSDimitry Andric } 730972a253aSDimitry Andric } 731972a253aSDimitry Andric 73206c3fb27SDimitry Andric return ModuleScopeReplacement.SGV; 73306c3fb27SDimitry Andric } 73406c3fb27SDimitry Andric 73506c3fb27SDimitry Andric static DenseMap<Function *, LDSVariableReplacement> 73606c3fb27SDimitry Andric lowerKernelScopeStructVariables( 73706c3fb27SDimitry Andric Module &M, LDSUsesInfoTy &LDSUsesInfo, 73806c3fb27SDimitry Andric DenseSet<GlobalVariable *> const &ModuleScopeVariables, 73906c3fb27SDimitry Andric DenseSet<Function *> const &KernelsThatAllocateModuleLDS, 74006c3fb27SDimitry Andric GlobalVariable *MaybeModuleScopeStruct) { 74106c3fb27SDimitry Andric 74206c3fb27SDimitry Andric // Create a struct for each kernel for the non-module-scope variables. 74306c3fb27SDimitry Andric 744bdd1243dSDimitry Andric DenseMap<Function *, LDSVariableReplacement> KernelToReplacement; 745bdd1243dSDimitry Andric for (Function &Func : M.functions()) { 746bdd1243dSDimitry Andric if (Func.isDeclaration() || !isKernelLDS(&Func)) 747349cc55cSDimitry Andric continue; 748349cc55cSDimitry Andric 749bdd1243dSDimitry Andric DenseSet<GlobalVariable *> KernelUsedVariables; 75006c3fb27SDimitry Andric // Allocating variables that are used directly in this struct to get 75106c3fb27SDimitry Andric // alignment aware allocation and predictable frame size. 752bdd1243dSDimitry Andric for (auto &v : LDSUsesInfo.direct_access[&Func]) { 75306c3fb27SDimitry Andric if (!AMDGPU::isDynamicLDS(*v)) { 754bdd1243dSDimitry Andric KernelUsedVariables.insert(v); 755bdd1243dSDimitry Andric } 75606c3fb27SDimitry Andric } 75706c3fb27SDimitry Andric 75806c3fb27SDimitry Andric // Allocating variables that are accessed indirectly so that a lookup of 75906c3fb27SDimitry Andric // this struct instance can find them from nested functions. 760bdd1243dSDimitry Andric for (auto &v : LDSUsesInfo.indirect_access[&Func]) { 76106c3fb27SDimitry Andric if (!AMDGPU::isDynamicLDS(*v)) { 762bdd1243dSDimitry Andric KernelUsedVariables.insert(v); 763bdd1243dSDimitry Andric } 76406c3fb27SDimitry Andric } 765bdd1243dSDimitry Andric 766bdd1243dSDimitry Andric // Variables allocated in module lds must all resolve to that struct, 767bdd1243dSDimitry Andric // not to the per-kernel instance. 768bdd1243dSDimitry Andric if (KernelsThatAllocateModuleLDS.contains(&Func)) { 769bdd1243dSDimitry Andric for (GlobalVariable *v : ModuleScopeVariables) { 770bdd1243dSDimitry Andric KernelUsedVariables.erase(v); 771bdd1243dSDimitry Andric } 772bdd1243dSDimitry Andric } 773bdd1243dSDimitry Andric 774bdd1243dSDimitry Andric if (KernelUsedVariables.empty()) { 77506c3fb27SDimitry Andric // Either used no LDS, or the LDS it used was all in the module struct 77606c3fb27SDimitry Andric // or dynamically sized 777fe6060f1SDimitry Andric continue; 778972a253aSDimitry Andric } 779972a253aSDimitry Andric 780bdd1243dSDimitry Andric // The association between kernel function and LDS struct is done by 781bdd1243dSDimitry Andric // symbol name, which only works if the function in question has a 782bdd1243dSDimitry Andric // name This is not expected to be a problem in practice as kernels 783bdd1243dSDimitry Andric // are called by name making anonymous ones (which are named by the 784bdd1243dSDimitry Andric // backend) difficult to use. This does mean that llvm test cases need 785bdd1243dSDimitry Andric // to name the kernels. 786bdd1243dSDimitry Andric if (!Func.hasName()) { 787bdd1243dSDimitry Andric report_fatal_error("Anonymous kernels cannot use LDS variables"); 788bdd1243dSDimitry Andric } 789bdd1243dSDimitry Andric 790972a253aSDimitry Andric std::string VarName = 791bdd1243dSDimitry Andric (Twine("llvm.amdgcn.kernel.") + Func.getName() + ".lds").str(); 792bdd1243dSDimitry Andric 793bdd1243dSDimitry Andric auto Replacement = 794972a253aSDimitry Andric createLDSVariableReplacement(M, VarName, KernelUsedVariables); 795972a253aSDimitry Andric 79606c3fb27SDimitry Andric // If any indirect uses, create a direct use to ensure allocation 79706c3fb27SDimitry Andric // TODO: Simpler to unconditionally mark used but that regresses 79806c3fb27SDimitry Andric // codegen in test/CodeGen/AMDGPU/noclobber-barrier.ll 79906c3fb27SDimitry Andric auto Accesses = LDSUsesInfo.indirect_access.find(&Func); 80006c3fb27SDimitry Andric if ((Accesses != LDSUsesInfo.indirect_access.end()) && 80106c3fb27SDimitry Andric !Accesses->second.empty()) 80206c3fb27SDimitry Andric markUsedByKernel(&Func, Replacement.SGV); 80306c3fb27SDimitry Andric 804bdd1243dSDimitry Andric // remove preserves existing codegen 805bdd1243dSDimitry Andric removeLocalVarsFromUsedLists(M, KernelUsedVariables); 806bdd1243dSDimitry Andric KernelToReplacement[&Func] = Replacement; 807bdd1243dSDimitry Andric 808bdd1243dSDimitry Andric // Rewrite uses within kernel to the new struct 809972a253aSDimitry Andric replaceLDSVariablesWithStruct( 810bdd1243dSDimitry Andric M, KernelUsedVariables, Replacement, [&Func](Use &U) { 811972a253aSDimitry Andric Instruction *I = dyn_cast<Instruction>(U.getUser()); 812bdd1243dSDimitry Andric return I && I->getFunction() == &Func; 813972a253aSDimitry Andric }); 814972a253aSDimitry Andric } 81506c3fb27SDimitry Andric return KernelToReplacement; 81606c3fb27SDimitry Andric } 81706c3fb27SDimitry Andric 81806c3fb27SDimitry Andric static GlobalVariable * 81906c3fb27SDimitry Andric buildRepresentativeDynamicLDSInstance(Module &M, LDSUsesInfoTy &LDSUsesInfo, 82006c3fb27SDimitry Andric Function *func) { 82106c3fb27SDimitry Andric // Create a dynamic lds variable with a name associated with the passed 82206c3fb27SDimitry Andric // function that has the maximum alignment of any dynamic lds variable 82306c3fb27SDimitry Andric // reachable from this kernel. Dynamic LDS is allocated after the static LDS 82406c3fb27SDimitry Andric // allocation, possibly after alignment padding. The representative variable 82506c3fb27SDimitry Andric // created here has the maximum alignment of any other dynamic variable 82606c3fb27SDimitry Andric // reachable by that kernel. All dynamic LDS variables are allocated at the 82706c3fb27SDimitry Andric // same address in each kernel in order to provide the documented aliasing 82806c3fb27SDimitry Andric // semantics. Setting the alignment here allows this IR pass to accurately 82906c3fb27SDimitry Andric // predict the exact constant at which it will be allocated. 83006c3fb27SDimitry Andric 83106c3fb27SDimitry Andric assert(isKernelLDS(func)); 83206c3fb27SDimitry Andric 83306c3fb27SDimitry Andric LLVMContext &Ctx = M.getContext(); 83406c3fb27SDimitry Andric const DataLayout &DL = M.getDataLayout(); 83506c3fb27SDimitry Andric Align MaxDynamicAlignment(1); 83606c3fb27SDimitry Andric 83706c3fb27SDimitry Andric auto UpdateMaxAlignment = [&MaxDynamicAlignment, &DL](GlobalVariable *GV) { 83806c3fb27SDimitry Andric if (AMDGPU::isDynamicLDS(*GV)) { 83906c3fb27SDimitry Andric MaxDynamicAlignment = 84006c3fb27SDimitry Andric std::max(MaxDynamicAlignment, AMDGPU::getAlign(DL, GV)); 84106c3fb27SDimitry Andric } 84206c3fb27SDimitry Andric }; 84306c3fb27SDimitry Andric 84406c3fb27SDimitry Andric for (GlobalVariable *GV : LDSUsesInfo.indirect_access[func]) { 84506c3fb27SDimitry Andric UpdateMaxAlignment(GV); 84606c3fb27SDimitry Andric } 84706c3fb27SDimitry Andric 84806c3fb27SDimitry Andric for (GlobalVariable *GV : LDSUsesInfo.direct_access[func]) { 84906c3fb27SDimitry Andric UpdateMaxAlignment(GV); 85006c3fb27SDimitry Andric } 85106c3fb27SDimitry Andric 85206c3fb27SDimitry Andric assert(func->hasName()); // Checked by caller 85306c3fb27SDimitry Andric auto emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0); 85406c3fb27SDimitry Andric GlobalVariable *N = new GlobalVariable( 85506c3fb27SDimitry Andric M, emptyCharArray, false, GlobalValue::ExternalLinkage, nullptr, 85606c3fb27SDimitry Andric Twine("llvm.amdgcn." + func->getName() + ".dynlds"), nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, 85706c3fb27SDimitry Andric false); 85806c3fb27SDimitry Andric N->setAlignment(MaxDynamicAlignment); 85906c3fb27SDimitry Andric 86006c3fb27SDimitry Andric assert(AMDGPU::isDynamicLDS(*N)); 86106c3fb27SDimitry Andric return N; 86206c3fb27SDimitry Andric } 86306c3fb27SDimitry Andric 86406c3fb27SDimitry Andric DenseMap<Function *, GlobalVariable *> lowerDynamicLDSVariables( 86506c3fb27SDimitry Andric Module &M, LDSUsesInfoTy &LDSUsesInfo, 86606c3fb27SDimitry Andric DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS, 86706c3fb27SDimitry Andric DenseSet<GlobalVariable *> const &DynamicVariables, 86806c3fb27SDimitry Andric std::vector<Function *> const &OrderedKernels) { 86906c3fb27SDimitry Andric DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS; 87006c3fb27SDimitry Andric if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) { 87106c3fb27SDimitry Andric LLVMContext &Ctx = M.getContext(); 87206c3fb27SDimitry Andric IRBuilder<> Builder(Ctx); 87306c3fb27SDimitry Andric Type *I32 = Type::getInt32Ty(Ctx); 87406c3fb27SDimitry Andric 87506c3fb27SDimitry Andric std::vector<Constant *> newDynamicLDS; 87606c3fb27SDimitry Andric 87706c3fb27SDimitry Andric // Table is built in the same order as OrderedKernels 87806c3fb27SDimitry Andric for (auto &func : OrderedKernels) { 87906c3fb27SDimitry Andric 88006c3fb27SDimitry Andric if (KernelsThatIndirectlyAllocateDynamicLDS.contains(func)) { 88106c3fb27SDimitry Andric assert(isKernelLDS(func)); 88206c3fb27SDimitry Andric if (!func->hasName()) { 88306c3fb27SDimitry Andric report_fatal_error("Anonymous kernels cannot use LDS variables"); 88406c3fb27SDimitry Andric } 88506c3fb27SDimitry Andric 88606c3fb27SDimitry Andric GlobalVariable *N = 88706c3fb27SDimitry Andric buildRepresentativeDynamicLDSInstance(M, LDSUsesInfo, func); 88806c3fb27SDimitry Andric 88906c3fb27SDimitry Andric KernelToCreatedDynamicLDS[func] = N; 89006c3fb27SDimitry Andric 89106c3fb27SDimitry Andric markUsedByKernel(func, N); 89206c3fb27SDimitry Andric 89306c3fb27SDimitry Andric auto emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0); 89406c3fb27SDimitry Andric auto GEP = ConstantExpr::getGetElementPtr( 89506c3fb27SDimitry Andric emptyCharArray, N, ConstantInt::get(I32, 0), true); 89606c3fb27SDimitry Andric newDynamicLDS.push_back(ConstantExpr::getPtrToInt(GEP, I32)); 89706c3fb27SDimitry Andric } else { 89806c3fb27SDimitry Andric newDynamicLDS.push_back(PoisonValue::get(I32)); 89906c3fb27SDimitry Andric } 90006c3fb27SDimitry Andric } 90106c3fb27SDimitry Andric assert(OrderedKernels.size() == newDynamicLDS.size()); 90206c3fb27SDimitry Andric 90306c3fb27SDimitry Andric ArrayType *t = ArrayType::get(I32, newDynamicLDS.size()); 90406c3fb27SDimitry Andric Constant *init = ConstantArray::get(t, newDynamicLDS); 90506c3fb27SDimitry Andric GlobalVariable *table = new GlobalVariable( 90606c3fb27SDimitry Andric M, t, true, GlobalValue::InternalLinkage, init, 90706c3fb27SDimitry Andric "llvm.amdgcn.dynlds.offset.table", nullptr, 90806c3fb27SDimitry Andric GlobalValue::NotThreadLocal, AMDGPUAS::CONSTANT_ADDRESS); 90906c3fb27SDimitry Andric 91006c3fb27SDimitry Andric for (GlobalVariable *GV : DynamicVariables) { 91106c3fb27SDimitry Andric for (Use &U : make_early_inc_range(GV->uses())) { 91206c3fb27SDimitry Andric auto *I = dyn_cast<Instruction>(U.getUser()); 91306c3fb27SDimitry Andric if (!I) 91406c3fb27SDimitry Andric continue; 91506c3fb27SDimitry Andric if (isKernelLDS(I->getFunction())) 91606c3fb27SDimitry Andric continue; 91706c3fb27SDimitry Andric 91806c3fb27SDimitry Andric replaceUseWithTableLookup(M, Builder, table, GV, U, nullptr); 91906c3fb27SDimitry Andric } 92006c3fb27SDimitry Andric } 92106c3fb27SDimitry Andric } 92206c3fb27SDimitry Andric return KernelToCreatedDynamicLDS; 92306c3fb27SDimitry Andric } 92406c3fb27SDimitry Andric 9255f757f3fSDimitry Andric bool runOnModule(Module &M) { 92606c3fb27SDimitry Andric CallGraph CG = CallGraph(M); 92706c3fb27SDimitry Andric bool Changed = superAlignLDSGlobals(M); 92806c3fb27SDimitry Andric 92906c3fb27SDimitry Andric Changed |= eliminateConstantExprUsesOfLDSFromAllInstructions(M); 93006c3fb27SDimitry Andric 93106c3fb27SDimitry Andric Changed = true; // todo: narrow this down 93206c3fb27SDimitry Andric 93306c3fb27SDimitry Andric // For each kernel, what variables does it access directly or through 93406c3fb27SDimitry Andric // callees 93506c3fb27SDimitry Andric LDSUsesInfoTy LDSUsesInfo = getTransitiveUsesOfLDS(CG, M); 93606c3fb27SDimitry Andric 93706c3fb27SDimitry Andric // For each variable accessed through callees, which kernels access it 93806c3fb27SDimitry Andric VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly; 93906c3fb27SDimitry Andric for (auto &K : LDSUsesInfo.indirect_access) { 94006c3fb27SDimitry Andric Function *F = K.first; 94106c3fb27SDimitry Andric assert(isKernelLDS(F)); 94206c3fb27SDimitry Andric for (GlobalVariable *GV : K.second) { 94306c3fb27SDimitry Andric LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(F); 94406c3fb27SDimitry Andric } 94506c3fb27SDimitry Andric } 94606c3fb27SDimitry Andric 94706c3fb27SDimitry Andric // Partition variables accessed indirectly into the different strategies 94806c3fb27SDimitry Andric DenseSet<GlobalVariable *> ModuleScopeVariables; 94906c3fb27SDimitry Andric DenseSet<GlobalVariable *> TableLookupVariables; 95006c3fb27SDimitry Andric DenseSet<GlobalVariable *> KernelAccessVariables; 95106c3fb27SDimitry Andric DenseSet<GlobalVariable *> DynamicVariables; 95206c3fb27SDimitry Andric partitionVariablesIntoIndirectStrategies( 95306c3fb27SDimitry Andric M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly, 95406c3fb27SDimitry Andric ModuleScopeVariables, TableLookupVariables, KernelAccessVariables, 95506c3fb27SDimitry Andric DynamicVariables); 95606c3fb27SDimitry Andric 95706c3fb27SDimitry Andric // If the kernel accesses a variable that is going to be stored in the 95806c3fb27SDimitry Andric // module instance through a call then that kernel needs to allocate the 95906c3fb27SDimitry Andric // module instance 96006c3fb27SDimitry Andric const DenseSet<Function *> KernelsThatAllocateModuleLDS = 96106c3fb27SDimitry Andric kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo, 96206c3fb27SDimitry Andric ModuleScopeVariables); 96306c3fb27SDimitry Andric const DenseSet<Function *> KernelsThatAllocateTableLDS = 96406c3fb27SDimitry Andric kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo, 96506c3fb27SDimitry Andric TableLookupVariables); 96606c3fb27SDimitry Andric 96706c3fb27SDimitry Andric const DenseSet<Function *> KernelsThatIndirectlyAllocateDynamicLDS = 96806c3fb27SDimitry Andric kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo, 96906c3fb27SDimitry Andric DynamicVariables); 97006c3fb27SDimitry Andric 97106c3fb27SDimitry Andric GlobalVariable *MaybeModuleScopeStruct = lowerModuleScopeStructVariables( 97206c3fb27SDimitry Andric M, ModuleScopeVariables, KernelsThatAllocateModuleLDS); 97306c3fb27SDimitry Andric 97406c3fb27SDimitry Andric DenseMap<Function *, LDSVariableReplacement> KernelToReplacement = 97506c3fb27SDimitry Andric lowerKernelScopeStructVariables(M, LDSUsesInfo, ModuleScopeVariables, 97606c3fb27SDimitry Andric KernelsThatAllocateModuleLDS, 97706c3fb27SDimitry Andric MaybeModuleScopeStruct); 978bdd1243dSDimitry Andric 979bdd1243dSDimitry Andric // Lower zero cost accesses to the kernel instances just created 980bdd1243dSDimitry Andric for (auto &GV : KernelAccessVariables) { 981bdd1243dSDimitry Andric auto &funcs = LDSToKernelsThatNeedToAccessItIndirectly[GV]; 982bdd1243dSDimitry Andric assert(funcs.size() == 1); // Only one kernel can access it 983bdd1243dSDimitry Andric LDSVariableReplacement Replacement = 984bdd1243dSDimitry Andric KernelToReplacement[*(funcs.begin())]; 985bdd1243dSDimitry Andric 986bdd1243dSDimitry Andric DenseSet<GlobalVariable *> Vec; 987bdd1243dSDimitry Andric Vec.insert(GV); 988bdd1243dSDimitry Andric 989bdd1243dSDimitry Andric replaceLDSVariablesWithStruct(M, Vec, Replacement, [](Use &U) { 990bdd1243dSDimitry Andric return isa<Instruction>(U.getUser()); 991bdd1243dSDimitry Andric }); 992bdd1243dSDimitry Andric } 993bdd1243dSDimitry Andric 99406c3fb27SDimitry Andric // The ith element of this vector is kernel id i 99506c3fb27SDimitry Andric std::vector<Function *> OrderedKernels = 99606c3fb27SDimitry Andric assignLDSKernelIDToEachKernel(&M, KernelsThatAllocateTableLDS, 99706c3fb27SDimitry Andric KernelsThatIndirectlyAllocateDynamicLDS); 99806c3fb27SDimitry Andric 999bdd1243dSDimitry Andric if (!KernelsThatAllocateTableLDS.empty()) { 1000bdd1243dSDimitry Andric LLVMContext &Ctx = M.getContext(); 1001bdd1243dSDimitry Andric IRBuilder<> Builder(Ctx); 1002bdd1243dSDimitry Andric 1003bdd1243dSDimitry Andric // The order must be consistent between lookup table and accesses to 1004bdd1243dSDimitry Andric // lookup table 100506c3fb27SDimitry Andric auto TableLookupVariablesOrdered = 100606c3fb27SDimitry Andric sortByName(std::vector<GlobalVariable *>(TableLookupVariables.begin(), 100706c3fb27SDimitry Andric TableLookupVariables.end())); 1008bdd1243dSDimitry Andric 1009bdd1243dSDimitry Andric GlobalVariable *LookupTable = buildLookupTable( 1010bdd1243dSDimitry Andric M, TableLookupVariablesOrdered, OrderedKernels, KernelToReplacement); 1011bdd1243dSDimitry Andric replaceUsesInInstructionsWithTableLookup(M, TableLookupVariablesOrdered, 1012bdd1243dSDimitry Andric LookupTable); 1013297eecfbSDimitry Andric 1014297eecfbSDimitry Andric // Strip amdgpu-no-lds-kernel-id from all functions reachable from the 1015297eecfbSDimitry Andric // kernel. We may have inferred this wasn't used prior to the pass. 1016297eecfbSDimitry Andric // 1017297eecfbSDimitry Andric // TODO: We could filter out subgraphs that do not access LDS globals. 1018297eecfbSDimitry Andric for (Function *F : KernelsThatAllocateTableLDS) 1019*0fca6ea1SDimitry Andric removeFnAttrFromReachable(CG, F, {"amdgpu-no-lds-kernel-id"}); 1020bdd1243dSDimitry Andric } 1021bdd1243dSDimitry Andric 102206c3fb27SDimitry Andric DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS = 102306c3fb27SDimitry Andric lowerDynamicLDSVariables(M, LDSUsesInfo, 102406c3fb27SDimitry Andric KernelsThatIndirectlyAllocateDynamicLDS, 102506c3fb27SDimitry Andric DynamicVariables, OrderedKernels); 102606c3fb27SDimitry Andric 102706c3fb27SDimitry Andric // All kernel frames have been allocated. Calculate and record the 102806c3fb27SDimitry Andric // addresses. 102906c3fb27SDimitry Andric { 103006c3fb27SDimitry Andric const DataLayout &DL = M.getDataLayout(); 103106c3fb27SDimitry Andric 103206c3fb27SDimitry Andric for (Function &Func : M.functions()) { 103306c3fb27SDimitry Andric if (Func.isDeclaration() || !isKernelLDS(&Func)) 103406c3fb27SDimitry Andric continue; 103506c3fb27SDimitry Andric 103606c3fb27SDimitry Andric // All three of these are optional. The first variable is allocated at 103706c3fb27SDimitry Andric // zero. They are allocated by AMDGPUMachineFunction as one block. 103806c3fb27SDimitry Andric // Layout: 103906c3fb27SDimitry Andric //{ 104006c3fb27SDimitry Andric // module.lds 104106c3fb27SDimitry Andric // alignment padding 104206c3fb27SDimitry Andric // kernel instance 104306c3fb27SDimitry Andric // alignment padding 104406c3fb27SDimitry Andric // dynamic lds variables 104506c3fb27SDimitry Andric //} 104606c3fb27SDimitry Andric 104706c3fb27SDimitry Andric const bool AllocateModuleScopeStruct = 104806c3fb27SDimitry Andric MaybeModuleScopeStruct && 104906c3fb27SDimitry Andric KernelsThatAllocateModuleLDS.contains(&Func); 105006c3fb27SDimitry Andric 105106c3fb27SDimitry Andric auto Replacement = KernelToReplacement.find(&Func); 105206c3fb27SDimitry Andric const bool AllocateKernelScopeStruct = 105306c3fb27SDimitry Andric Replacement != KernelToReplacement.end(); 105406c3fb27SDimitry Andric 105506c3fb27SDimitry Andric const bool AllocateDynamicVariable = 105606c3fb27SDimitry Andric KernelToCreatedDynamicLDS.contains(&Func); 105706c3fb27SDimitry Andric 105806c3fb27SDimitry Andric uint32_t Offset = 0; 105906c3fb27SDimitry Andric 106006c3fb27SDimitry Andric if (AllocateModuleScopeStruct) { 106106c3fb27SDimitry Andric // Allocated at zero, recorded once on construction, not once per 106206c3fb27SDimitry Andric // kernel 106306c3fb27SDimitry Andric Offset += DL.getTypeAllocSize(MaybeModuleScopeStruct->getValueType()); 106406c3fb27SDimitry Andric } 106506c3fb27SDimitry Andric 106606c3fb27SDimitry Andric if (AllocateKernelScopeStruct) { 106706c3fb27SDimitry Andric GlobalVariable *KernelStruct = Replacement->second.SGV; 106806c3fb27SDimitry Andric Offset = alignTo(Offset, AMDGPU::getAlign(DL, KernelStruct)); 106906c3fb27SDimitry Andric recordLDSAbsoluteAddress(&M, KernelStruct, Offset); 107006c3fb27SDimitry Andric Offset += DL.getTypeAllocSize(KernelStruct->getValueType()); 107106c3fb27SDimitry Andric } 107206c3fb27SDimitry Andric 107306c3fb27SDimitry Andric // If there is dynamic allocation, the alignment needed is included in 107406c3fb27SDimitry Andric // the static frame size. There may be no reference to the dynamic 107506c3fb27SDimitry Andric // variable in the kernel itself, so without including it here, that 107606c3fb27SDimitry Andric // alignment padding could be missed. 107706c3fb27SDimitry Andric if (AllocateDynamicVariable) { 107806c3fb27SDimitry Andric GlobalVariable *DynamicVariable = KernelToCreatedDynamicLDS[&Func]; 107906c3fb27SDimitry Andric Offset = alignTo(Offset, AMDGPU::getAlign(DL, DynamicVariable)); 108006c3fb27SDimitry Andric recordLDSAbsoluteAddress(&M, DynamicVariable, Offset); 108106c3fb27SDimitry Andric } 108206c3fb27SDimitry Andric 108306c3fb27SDimitry Andric if (Offset != 0) { 10845f757f3fSDimitry Andric (void)TM; // TODO: Account for target maximum LDS 108506c3fb27SDimitry Andric std::string Buffer; 108606c3fb27SDimitry Andric raw_string_ostream SS{Buffer}; 108706c3fb27SDimitry Andric SS << format("%u", Offset); 108806c3fb27SDimitry Andric 1089*0fca6ea1SDimitry Andric // Instead of explicitly marking kernels that access dynamic variables 109006c3fb27SDimitry Andric // using special case metadata, annotate with min-lds == max-lds, i.e. 109106c3fb27SDimitry Andric // that there is no more space available for allocating more static 109206c3fb27SDimitry Andric // LDS variables. That is the right condition to prevent allocating 109306c3fb27SDimitry Andric // more variables which would collide with the addresses assigned to 109406c3fb27SDimitry Andric // dynamic variables. 109506c3fb27SDimitry Andric if (AllocateDynamicVariable) 109606c3fb27SDimitry Andric SS << format(",%u", Offset); 109706c3fb27SDimitry Andric 109806c3fb27SDimitry Andric Func.addFnAttr("amdgpu-lds-size", Buffer); 109906c3fb27SDimitry Andric } 110006c3fb27SDimitry Andric } 110106c3fb27SDimitry Andric } 110206c3fb27SDimitry Andric 1103bdd1243dSDimitry Andric for (auto &GV : make_early_inc_range(M.globals())) 1104bdd1243dSDimitry Andric if (AMDGPU::isLDSVariableToLower(GV)) { 1105bdd1243dSDimitry Andric // probably want to remove from used lists 1106bdd1243dSDimitry Andric GV.removeDeadConstantUsers(); 1107bdd1243dSDimitry Andric if (GV.use_empty()) 1108bdd1243dSDimitry Andric GV.eraseFromParent(); 1109fe6060f1SDimitry Andric } 1110fe6060f1SDimitry Andric 1111fe6060f1SDimitry Andric return Changed; 1112fe6060f1SDimitry Andric } 1113fe6060f1SDimitry Andric 1114fe6060f1SDimitry Andric private: 1115fe6060f1SDimitry Andric // Increase the alignment of LDS globals if necessary to maximise the chance 1116fe6060f1SDimitry Andric // that we can use aligned LDS instructions to access them. 11170eae32dcSDimitry Andric static bool superAlignLDSGlobals(Module &M) { 11180eae32dcSDimitry Andric const DataLayout &DL = M.getDataLayout(); 11190eae32dcSDimitry Andric bool Changed = false; 11200eae32dcSDimitry Andric if (!SuperAlignLDSGlobals) { 11210eae32dcSDimitry Andric return Changed; 11220eae32dcSDimitry Andric } 11230eae32dcSDimitry Andric 11240eae32dcSDimitry Andric for (auto &GV : M.globals()) { 11250eae32dcSDimitry Andric if (GV.getType()->getPointerAddressSpace() != AMDGPUAS::LOCAL_ADDRESS) { 11260eae32dcSDimitry Andric // Only changing alignment of LDS variables 11270eae32dcSDimitry Andric continue; 11280eae32dcSDimitry Andric } 11290eae32dcSDimitry Andric if (!GV.hasInitializer()) { 11300eae32dcSDimitry Andric // cuda/hip extern __shared__ variable, leave alignment alone 11310eae32dcSDimitry Andric continue; 11320eae32dcSDimitry Andric } 11330eae32dcSDimitry Andric 11340eae32dcSDimitry Andric Align Alignment = AMDGPU::getAlign(DL, &GV); 11350eae32dcSDimitry Andric TypeSize GVSize = DL.getTypeAllocSize(GV.getValueType()); 1136fe6060f1SDimitry Andric 1137fe6060f1SDimitry Andric if (GVSize > 8) { 1138fe6060f1SDimitry Andric // We might want to use a b96 or b128 load/store 1139fe6060f1SDimitry Andric Alignment = std::max(Alignment, Align(16)); 1140fe6060f1SDimitry Andric } else if (GVSize > 4) { 1141fe6060f1SDimitry Andric // We might want to use a b64 load/store 1142fe6060f1SDimitry Andric Alignment = std::max(Alignment, Align(8)); 1143fe6060f1SDimitry Andric } else if (GVSize > 2) { 1144fe6060f1SDimitry Andric // We might want to use a b32 load/store 1145fe6060f1SDimitry Andric Alignment = std::max(Alignment, Align(4)); 1146fe6060f1SDimitry Andric } else if (GVSize > 1) { 1147fe6060f1SDimitry Andric // We might want to use a b16 load/store 1148fe6060f1SDimitry Andric Alignment = std::max(Alignment, Align(2)); 1149fe6060f1SDimitry Andric } 1150fe6060f1SDimitry Andric 11510eae32dcSDimitry Andric if (Alignment != AMDGPU::getAlign(DL, &GV)) { 11520eae32dcSDimitry Andric Changed = true; 11530eae32dcSDimitry Andric GV.setAlignment(Alignment); 1154fe6060f1SDimitry Andric } 1155fe6060f1SDimitry Andric } 11560eae32dcSDimitry Andric return Changed; 11570eae32dcSDimitry Andric } 11580eae32dcSDimitry Andric 1159bdd1243dSDimitry Andric static LDSVariableReplacement createLDSVariableReplacement( 1160972a253aSDimitry Andric Module &M, std::string VarName, 1161bdd1243dSDimitry Andric DenseSet<GlobalVariable *> const &LDSVarsToTransform) { 1162972a253aSDimitry Andric // Create a struct instance containing LDSVarsToTransform and map from those 1163972a253aSDimitry Andric // variables to ConstantExprGEP 1164972a253aSDimitry Andric // Variables may be introduced to meet alignment requirements. No aliasing 1165972a253aSDimitry Andric // metadata is useful for these as they have no uses. Erased before return. 1166972a253aSDimitry Andric 11670eae32dcSDimitry Andric LLVMContext &Ctx = M.getContext(); 11680eae32dcSDimitry Andric const DataLayout &DL = M.getDataLayout(); 1169972a253aSDimitry Andric assert(!LDSVarsToTransform.empty()); 1170fe6060f1SDimitry Andric 1171fe6060f1SDimitry Andric SmallVector<OptimizedStructLayoutField, 8> LayoutFields; 1172fcaf7f86SDimitry Andric LayoutFields.reserve(LDSVarsToTransform.size()); 1173bdd1243dSDimitry Andric { 1174bdd1243dSDimitry Andric // The order of fields in this struct depends on the order of 1175*0fca6ea1SDimitry Andric // variables in the argument which varies when changing how they 1176bdd1243dSDimitry Andric // are identified, leading to spurious test breakage. 117706c3fb27SDimitry Andric auto Sorted = sortByName(std::vector<GlobalVariable *>( 117806c3fb27SDimitry Andric LDSVarsToTransform.begin(), LDSVarsToTransform.end())); 117906c3fb27SDimitry Andric 1180bdd1243dSDimitry Andric for (GlobalVariable *GV : Sorted) { 1181bdd1243dSDimitry Andric OptimizedStructLayoutField F(GV, 1182bdd1243dSDimitry Andric DL.getTypeAllocSize(GV->getValueType()), 1183fe6060f1SDimitry Andric AMDGPU::getAlign(DL, GV)); 1184fe6060f1SDimitry Andric LayoutFields.emplace_back(F); 1185fe6060f1SDimitry Andric } 1186bdd1243dSDimitry Andric } 1187fe6060f1SDimitry Andric 1188fe6060f1SDimitry Andric performOptimizedStructLayout(LayoutFields); 1189fe6060f1SDimitry Andric 1190fe6060f1SDimitry Andric std::vector<GlobalVariable *> LocalVars; 1191972a253aSDimitry Andric BitVector IsPaddingField; 1192fcaf7f86SDimitry Andric LocalVars.reserve(LDSVarsToTransform.size()); // will be at least this large 1193972a253aSDimitry Andric IsPaddingField.reserve(LDSVarsToTransform.size()); 1194fe6060f1SDimitry Andric { 1195fe6060f1SDimitry Andric uint64_t CurrentOffset = 0; 1196*0fca6ea1SDimitry Andric for (auto &F : LayoutFields) { 1197*0fca6ea1SDimitry Andric GlobalVariable *FGV = 1198*0fca6ea1SDimitry Andric static_cast<GlobalVariable *>(const_cast<void *>(F.Id)); 1199*0fca6ea1SDimitry Andric Align DataAlign = F.Alignment; 1200fe6060f1SDimitry Andric 1201fe6060f1SDimitry Andric uint64_t DataAlignV = DataAlign.value(); 1202fe6060f1SDimitry Andric if (uint64_t Rem = CurrentOffset % DataAlignV) { 1203fe6060f1SDimitry Andric uint64_t Padding = DataAlignV - Rem; 1204fe6060f1SDimitry Andric 1205fe6060f1SDimitry Andric // Append an array of padding bytes to meet alignment requested 1206fe6060f1SDimitry Andric // Note (o + (a - (o % a)) ) % a == 0 1207fe6060f1SDimitry Andric // (offset + Padding ) % align == 0 1208fe6060f1SDimitry Andric 1209fe6060f1SDimitry Andric Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding); 1210fe6060f1SDimitry Andric LocalVars.push_back(new GlobalVariable( 12115f757f3fSDimitry Andric M, ATy, false, GlobalValue::InternalLinkage, 12125f757f3fSDimitry Andric PoisonValue::get(ATy), "", nullptr, GlobalValue::NotThreadLocal, 12135f757f3fSDimitry Andric AMDGPUAS::LOCAL_ADDRESS, false)); 1214972a253aSDimitry Andric IsPaddingField.push_back(true); 1215fe6060f1SDimitry Andric CurrentOffset += Padding; 1216fe6060f1SDimitry Andric } 1217fe6060f1SDimitry Andric 1218fe6060f1SDimitry Andric LocalVars.push_back(FGV); 1219972a253aSDimitry Andric IsPaddingField.push_back(false); 1220*0fca6ea1SDimitry Andric CurrentOffset += F.Size; 1221fe6060f1SDimitry Andric } 1222fe6060f1SDimitry Andric } 1223fe6060f1SDimitry Andric 1224fe6060f1SDimitry Andric std::vector<Type *> LocalVarTypes; 1225fe6060f1SDimitry Andric LocalVarTypes.reserve(LocalVars.size()); 1226fe6060f1SDimitry Andric std::transform( 1227fe6060f1SDimitry Andric LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes), 1228fe6060f1SDimitry Andric [](const GlobalVariable *V) -> Type * { return V->getValueType(); }); 1229fe6060f1SDimitry Andric 1230fe6060f1SDimitry Andric StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t"); 1231fe6060f1SDimitry Andric 1232bdd1243dSDimitry Andric Align StructAlign = AMDGPU::getAlign(DL, LocalVars[0]); 1233fe6060f1SDimitry Andric 1234fe6060f1SDimitry Andric GlobalVariable *SGV = new GlobalVariable( 12355f757f3fSDimitry Andric M, LDSTy, false, GlobalValue::InternalLinkage, PoisonValue::get(LDSTy), 1236fe6060f1SDimitry Andric VarName, nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, 1237fe6060f1SDimitry Andric false); 1238fe6060f1SDimitry Andric SGV->setAlignment(StructAlign); 1239972a253aSDimitry Andric 1240972a253aSDimitry Andric DenseMap<GlobalVariable *, Constant *> Map; 1241972a253aSDimitry Andric Type *I32 = Type::getInt32Ty(Ctx); 1242972a253aSDimitry Andric for (size_t I = 0; I < LocalVars.size(); I++) { 1243972a253aSDimitry Andric GlobalVariable *GV = LocalVars[I]; 1244972a253aSDimitry Andric Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)}; 1245972a253aSDimitry Andric Constant *GEP = ConstantExpr::getGetElementPtr(LDSTy, SGV, GEPIdx, true); 1246972a253aSDimitry Andric if (IsPaddingField[I]) { 1247972a253aSDimitry Andric assert(GV->use_empty()); 1248972a253aSDimitry Andric GV->eraseFromParent(); 1249972a253aSDimitry Andric } else { 1250972a253aSDimitry Andric Map[GV] = GEP; 1251972a253aSDimitry Andric } 1252972a253aSDimitry Andric } 1253972a253aSDimitry Andric assert(Map.size() == LDSVarsToTransform.size()); 1254972a253aSDimitry Andric return {SGV, std::move(Map)}; 1255fe6060f1SDimitry Andric } 1256fe6060f1SDimitry Andric 1257972a253aSDimitry Andric template <typename PredicateTy> 125806c3fb27SDimitry Andric static void replaceLDSVariablesWithStruct( 1259bdd1243dSDimitry Andric Module &M, DenseSet<GlobalVariable *> const &LDSVarsToTransformArg, 126006c3fb27SDimitry Andric const LDSVariableReplacement &Replacement, PredicateTy Predicate) { 1261972a253aSDimitry Andric LLVMContext &Ctx = M.getContext(); 1262972a253aSDimitry Andric const DataLayout &DL = M.getDataLayout(); 1263fe6060f1SDimitry Andric 1264bdd1243dSDimitry Andric // A hack... we need to insert the aliasing info in a predictable order for 1265bdd1243dSDimitry Andric // lit tests. Would like to have them in a stable order already, ideally the 1266bdd1243dSDimitry Andric // same order they get allocated, which might mean an ordered set container 126706c3fb27SDimitry Andric auto LDSVarsToTransform = sortByName(std::vector<GlobalVariable *>( 126806c3fb27SDimitry Andric LDSVarsToTransformArg.begin(), LDSVarsToTransformArg.end())); 1269bdd1243dSDimitry Andric 1270349cc55cSDimitry Andric // Create alias.scope and their lists. Each field in the new structure 1271349cc55cSDimitry Andric // does not alias with all other fields. 1272349cc55cSDimitry Andric SmallVector<MDNode *> AliasScopes; 1273349cc55cSDimitry Andric SmallVector<Metadata *> NoAliasList; 1274972a253aSDimitry Andric const size_t NumberVars = LDSVarsToTransform.size(); 1275972a253aSDimitry Andric if (NumberVars > 1) { 1276349cc55cSDimitry Andric MDBuilder MDB(Ctx); 1277972a253aSDimitry Andric AliasScopes.reserve(NumberVars); 1278349cc55cSDimitry Andric MDNode *Domain = MDB.createAnonymousAliasScopeDomain(); 1279972a253aSDimitry Andric for (size_t I = 0; I < NumberVars; I++) { 1280349cc55cSDimitry Andric MDNode *Scope = MDB.createAnonymousAliasScope(Domain); 1281349cc55cSDimitry Andric AliasScopes.push_back(Scope); 1282349cc55cSDimitry Andric } 1283349cc55cSDimitry Andric NoAliasList.append(&AliasScopes[1], AliasScopes.end()); 1284349cc55cSDimitry Andric } 1285349cc55cSDimitry Andric 1286972a253aSDimitry Andric // Replace uses of ith variable with a constantexpr to the corresponding 1287972a253aSDimitry Andric // field of the instance that will be allocated by AMDGPUMachineFunction 1288972a253aSDimitry Andric for (size_t I = 0; I < NumberVars; I++) { 1289972a253aSDimitry Andric GlobalVariable *GV = LDSVarsToTransform[I]; 129006c3fb27SDimitry Andric Constant *GEP = Replacement.LDSVarsToConstantGEP.at(GV); 1291fe6060f1SDimitry Andric 1292972a253aSDimitry Andric GV->replaceUsesWithIf(GEP, Predicate); 1293fe6060f1SDimitry Andric 1294972a253aSDimitry Andric APInt APOff(DL.getIndexTypeSizeInBits(GEP->getType()), 0); 1295972a253aSDimitry Andric GEP->stripAndAccumulateInBoundsConstantOffsets(DL, APOff); 1296972a253aSDimitry Andric uint64_t Offset = APOff.getZExtValue(); 1297972a253aSDimitry Andric 1298bdd1243dSDimitry Andric Align A = 1299bdd1243dSDimitry Andric commonAlignment(Replacement.SGV->getAlign().valueOrOne(), Offset); 1300349cc55cSDimitry Andric 1301349cc55cSDimitry Andric if (I) 1302349cc55cSDimitry Andric NoAliasList[I - 1] = AliasScopes[I - 1]; 1303349cc55cSDimitry Andric MDNode *NoAlias = 1304349cc55cSDimitry Andric NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList); 1305349cc55cSDimitry Andric MDNode *AliasScope = 1306349cc55cSDimitry Andric AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]}); 1307349cc55cSDimitry Andric 1308349cc55cSDimitry Andric refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias); 1309fe6060f1SDimitry Andric } 1310fe6060f1SDimitry Andric } 1311fe6060f1SDimitry Andric 131206c3fb27SDimitry Andric static void refineUsesAlignmentAndAA(Value *Ptr, Align A, 131306c3fb27SDimitry Andric const DataLayout &DL, MDNode *AliasScope, 131406c3fb27SDimitry Andric MDNode *NoAlias, unsigned MaxDepth = 5) { 1315349cc55cSDimitry Andric if (!MaxDepth || (A == 1 && !AliasScope)) 1316fe6060f1SDimitry Andric return; 1317fe6060f1SDimitry Andric 1318fe6060f1SDimitry Andric for (User *U : Ptr->users()) { 1319349cc55cSDimitry Andric if (auto *I = dyn_cast<Instruction>(U)) { 1320349cc55cSDimitry Andric if (AliasScope && I->mayReadOrWriteMemory()) { 1321349cc55cSDimitry Andric MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope); 1322349cc55cSDimitry Andric AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope) 1323349cc55cSDimitry Andric : AliasScope); 1324349cc55cSDimitry Andric I->setMetadata(LLVMContext::MD_alias_scope, AS); 1325349cc55cSDimitry Andric 1326349cc55cSDimitry Andric MDNode *NA = I->getMetadata(LLVMContext::MD_noalias); 1327349cc55cSDimitry Andric NA = (NA ? MDNode::intersect(NA, NoAlias) : NoAlias); 1328349cc55cSDimitry Andric I->setMetadata(LLVMContext::MD_noalias, NA); 1329349cc55cSDimitry Andric } 1330349cc55cSDimitry Andric } 1331349cc55cSDimitry Andric 1332fe6060f1SDimitry Andric if (auto *LI = dyn_cast<LoadInst>(U)) { 1333fe6060f1SDimitry Andric LI->setAlignment(std::max(A, LI->getAlign())); 1334fe6060f1SDimitry Andric continue; 1335fe6060f1SDimitry Andric } 1336fe6060f1SDimitry Andric if (auto *SI = dyn_cast<StoreInst>(U)) { 1337fe6060f1SDimitry Andric if (SI->getPointerOperand() == Ptr) 1338fe6060f1SDimitry Andric SI->setAlignment(std::max(A, SI->getAlign())); 1339fe6060f1SDimitry Andric continue; 1340fe6060f1SDimitry Andric } 1341fe6060f1SDimitry Andric if (auto *AI = dyn_cast<AtomicRMWInst>(U)) { 1342fe6060f1SDimitry Andric // None of atomicrmw operations can work on pointers, but let's 1343fe6060f1SDimitry Andric // check it anyway in case it will or we will process ConstantExpr. 1344fe6060f1SDimitry Andric if (AI->getPointerOperand() == Ptr) 1345fe6060f1SDimitry Andric AI->setAlignment(std::max(A, AI->getAlign())); 1346fe6060f1SDimitry Andric continue; 1347fe6060f1SDimitry Andric } 1348fe6060f1SDimitry Andric if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) { 1349fe6060f1SDimitry Andric if (AI->getPointerOperand() == Ptr) 1350fe6060f1SDimitry Andric AI->setAlignment(std::max(A, AI->getAlign())); 1351fe6060f1SDimitry Andric continue; 1352fe6060f1SDimitry Andric } 1353fe6060f1SDimitry Andric if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { 1354fe6060f1SDimitry Andric unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType()); 1355fe6060f1SDimitry Andric APInt Off(BitWidth, 0); 1356349cc55cSDimitry Andric if (GEP->getPointerOperand() == Ptr) { 1357349cc55cSDimitry Andric Align GA; 1358349cc55cSDimitry Andric if (GEP->accumulateConstantOffset(DL, Off)) 1359349cc55cSDimitry Andric GA = commonAlignment(A, Off.getLimitedValue()); 1360349cc55cSDimitry Andric refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias, 1361349cc55cSDimitry Andric MaxDepth - 1); 1362fe6060f1SDimitry Andric } 1363fe6060f1SDimitry Andric continue; 1364fe6060f1SDimitry Andric } 1365fe6060f1SDimitry Andric if (auto *I = dyn_cast<Instruction>(U)) { 1366fe6060f1SDimitry Andric if (I->getOpcode() == Instruction::BitCast || 1367fe6060f1SDimitry Andric I->getOpcode() == Instruction::AddrSpaceCast) 1368349cc55cSDimitry Andric refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1); 1369fe6060f1SDimitry Andric } 1370fe6060f1SDimitry Andric } 1371fe6060f1SDimitry Andric } 1372fe6060f1SDimitry Andric }; 1373fe6060f1SDimitry Andric 13745f757f3fSDimitry Andric class AMDGPULowerModuleLDSLegacy : public ModulePass { 13755f757f3fSDimitry Andric public: 13765f757f3fSDimitry Andric const AMDGPUTargetMachine *TM; 13775f757f3fSDimitry Andric static char ID; 13785f757f3fSDimitry Andric 13795f757f3fSDimitry Andric AMDGPULowerModuleLDSLegacy(const AMDGPUTargetMachine *TM_ = nullptr) 13805f757f3fSDimitry Andric : ModulePass(ID), TM(TM_) { 13815f757f3fSDimitry Andric initializeAMDGPULowerModuleLDSLegacyPass(*PassRegistry::getPassRegistry()); 13825f757f3fSDimitry Andric } 13835f757f3fSDimitry Andric 13845f757f3fSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 13855f757f3fSDimitry Andric if (!TM) 13865f757f3fSDimitry Andric AU.addRequired<TargetPassConfig>(); 13875f757f3fSDimitry Andric } 13885f757f3fSDimitry Andric 13895f757f3fSDimitry Andric bool runOnModule(Module &M) override { 13905f757f3fSDimitry Andric if (!TM) { 13915f757f3fSDimitry Andric auto &TPC = getAnalysis<TargetPassConfig>(); 13925f757f3fSDimitry Andric TM = &TPC.getTM<AMDGPUTargetMachine>(); 13935f757f3fSDimitry Andric } 13945f757f3fSDimitry Andric 13955f757f3fSDimitry Andric return AMDGPULowerModuleLDS(*TM).runOnModule(M); 13965f757f3fSDimitry Andric } 13975f757f3fSDimitry Andric }; 13985f757f3fSDimitry Andric 1399fe6060f1SDimitry Andric } // namespace 14005f757f3fSDimitry Andric char AMDGPULowerModuleLDSLegacy::ID = 0; 1401fe6060f1SDimitry Andric 14025f757f3fSDimitry Andric char &llvm::AMDGPULowerModuleLDSLegacyPassID = AMDGPULowerModuleLDSLegacy::ID; 1403fe6060f1SDimitry Andric 14045f757f3fSDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE, 14055f757f3fSDimitry Andric "Lower uses of LDS variables from non-kernel functions", 14065f757f3fSDimitry Andric false, false) 14075f757f3fSDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 14085f757f3fSDimitry Andric INITIALIZE_PASS_END(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE, 14095f757f3fSDimitry Andric "Lower uses of LDS variables from non-kernel functions", 14105f757f3fSDimitry Andric false, false) 1411fe6060f1SDimitry Andric 14125f757f3fSDimitry Andric ModulePass * 14135f757f3fSDimitry Andric llvm::createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM) { 14145f757f3fSDimitry Andric return new AMDGPULowerModuleLDSLegacy(TM); 1415fe6060f1SDimitry Andric } 1416fe6060f1SDimitry Andric 1417fe6060f1SDimitry Andric PreservedAnalyses AMDGPULowerModuleLDSPass::run(Module &M, 1418fe6060f1SDimitry Andric ModuleAnalysisManager &) { 14195f757f3fSDimitry Andric return AMDGPULowerModuleLDS(TM).runOnModule(M) ? PreservedAnalyses::none() 1420fe6060f1SDimitry Andric : PreservedAnalyses::all(); 1421fe6060f1SDimitry Andric } 1422