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