1*da58b97aSjoerg //===-- AMDGPULowerModuleLDSPass.cpp ------------------------------*- C++ -*-=//
2*da58b97aSjoerg //
3*da58b97aSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*da58b97aSjoerg // See https://llvm.org/LICENSE.txt for license information.
5*da58b97aSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*da58b97aSjoerg //
7*da58b97aSjoerg //===----------------------------------------------------------------------===//
8*da58b97aSjoerg //
9*da58b97aSjoerg // This pass eliminates LDS uses from non-kernel functions.
10*da58b97aSjoerg //
11*da58b97aSjoerg // The strategy is to create a new struct with a field for each LDS variable
12*da58b97aSjoerg // and allocate that struct at the same address for every kernel. Uses of the
13*da58b97aSjoerg // original LDS variables are then replaced with compile time offsets from that
14*da58b97aSjoerg // known address. AMDGPUMachineFunction allocates the LDS global.
15*da58b97aSjoerg //
16*da58b97aSjoerg // Local variables with constant annotation or non-undef initializer are passed
17*da58b97aSjoerg // through unchanged for simplication or error diagnostics in later passes.
18*da58b97aSjoerg //
19*da58b97aSjoerg // To reduce the memory overhead variables that are only used by kernels are
20*da58b97aSjoerg // excluded from this transform. The analysis to determine whether a variable
21*da58b97aSjoerg // is only used by a kernel is cheap and conservative so this may allocate
22*da58b97aSjoerg // a variable in every kernel when it was not strictly necessary to do so.
23*da58b97aSjoerg //
24*da58b97aSjoerg // A possible future refinement is to specialise the structure per-kernel, so
25*da58b97aSjoerg // that fields can be elided based on more expensive analysis.
26*da58b97aSjoerg //
27*da58b97aSjoerg //===----------------------------------------------------------------------===//
28*da58b97aSjoerg 
29*da58b97aSjoerg #include "AMDGPU.h"
30*da58b97aSjoerg #include "Utils/AMDGPUBaseInfo.h"
31*da58b97aSjoerg #include "Utils/AMDGPULDSUtils.h"
32*da58b97aSjoerg #include "llvm/ADT/STLExtras.h"
33*da58b97aSjoerg #include "llvm/IR/Constants.h"
34*da58b97aSjoerg #include "llvm/IR/DerivedTypes.h"
35*da58b97aSjoerg #include "llvm/IR/IRBuilder.h"
36*da58b97aSjoerg #include "llvm/IR/InlineAsm.h"
37*da58b97aSjoerg #include "llvm/IR/Instructions.h"
38*da58b97aSjoerg #include "llvm/InitializePasses.h"
39*da58b97aSjoerg #include "llvm/Pass.h"
40*da58b97aSjoerg #include "llvm/Support/Debug.h"
41*da58b97aSjoerg #include "llvm/Transforms/Utils/ModuleUtils.h"
42*da58b97aSjoerg #include <algorithm>
43*da58b97aSjoerg #include <vector>
44*da58b97aSjoerg 
45*da58b97aSjoerg #define DEBUG_TYPE "amdgpu-lower-module-lds"
46*da58b97aSjoerg 
47*da58b97aSjoerg using namespace llvm;
48*da58b97aSjoerg 
49*da58b97aSjoerg namespace {
50*da58b97aSjoerg 
51*da58b97aSjoerg class AMDGPULowerModuleLDS : public ModulePass {
52*da58b97aSjoerg 
removeFromUsedList(Module & M,StringRef Name,SmallPtrSetImpl<Constant * > & ToRemove)53*da58b97aSjoerg   static void removeFromUsedList(Module &M, StringRef Name,
54*da58b97aSjoerg                                  SmallPtrSetImpl<Constant *> &ToRemove) {
55*da58b97aSjoerg     GlobalVariable *GV = M.getNamedGlobal(Name);
56*da58b97aSjoerg     if (!GV || ToRemove.empty()) {
57*da58b97aSjoerg       return;
58*da58b97aSjoerg     }
59*da58b97aSjoerg 
60*da58b97aSjoerg     SmallVector<Constant *, 16> Init;
61*da58b97aSjoerg     auto *CA = cast<ConstantArray>(GV->getInitializer());
62*da58b97aSjoerg     for (auto &Op : CA->operands()) {
63*da58b97aSjoerg       // ModuleUtils::appendToUsed only inserts Constants
64*da58b97aSjoerg       Constant *C = cast<Constant>(Op);
65*da58b97aSjoerg       if (!ToRemove.contains(C->stripPointerCasts())) {
66*da58b97aSjoerg         Init.push_back(C);
67*da58b97aSjoerg       }
68*da58b97aSjoerg     }
69*da58b97aSjoerg 
70*da58b97aSjoerg     if (Init.size() == CA->getNumOperands()) {
71*da58b97aSjoerg       return; // none to remove
72*da58b97aSjoerg     }
73*da58b97aSjoerg 
74*da58b97aSjoerg     GV->eraseFromParent();
75*da58b97aSjoerg 
76*da58b97aSjoerg     if (!Init.empty()) {
77*da58b97aSjoerg       ArrayType *ATy =
78*da58b97aSjoerg           ArrayType::get(Type::getInt8PtrTy(M.getContext()), Init.size());
79*da58b97aSjoerg       GV =
80*da58b97aSjoerg           new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
81*da58b97aSjoerg                                    ConstantArray::get(ATy, Init), Name);
82*da58b97aSjoerg       GV->setSection("llvm.metadata");
83*da58b97aSjoerg     }
84*da58b97aSjoerg   }
85*da58b97aSjoerg 
86*da58b97aSjoerg   static void
removeFromUsedLists(Module & M,const std::vector<GlobalVariable * > & LocalVars)87*da58b97aSjoerg   removeFromUsedLists(Module &M,
88*da58b97aSjoerg                       const std::vector<GlobalVariable *> &LocalVars) {
89*da58b97aSjoerg     SmallPtrSet<Constant *, 32> LocalVarsSet;
90*da58b97aSjoerg     for (size_t I = 0; I < LocalVars.size(); I++) {
91*da58b97aSjoerg       if (Constant *C = dyn_cast<Constant>(LocalVars[I]->stripPointerCasts())) {
92*da58b97aSjoerg         LocalVarsSet.insert(C);
93*da58b97aSjoerg       }
94*da58b97aSjoerg     }
95*da58b97aSjoerg     removeFromUsedList(M, "llvm.used", LocalVarsSet);
96*da58b97aSjoerg     removeFromUsedList(M, "llvm.compiler.used", LocalVarsSet);
97*da58b97aSjoerg   }
98*da58b97aSjoerg 
markUsedByKernel(IRBuilder<> & Builder,Function * Func,GlobalVariable * SGV)99*da58b97aSjoerg   static void markUsedByKernel(IRBuilder<> &Builder, Function *Func,
100*da58b97aSjoerg                                GlobalVariable *SGV) {
101*da58b97aSjoerg     // The llvm.amdgcn.module.lds instance is implicitly used by all kernels
102*da58b97aSjoerg     // that might call a function which accesses a field within it. This is
103*da58b97aSjoerg     // presently approximated to 'all kernels' if there are any such functions
104*da58b97aSjoerg     // in the module. This implicit use is reified as an explicit use here so
105*da58b97aSjoerg     // that later passes, specifically PromoteAlloca, account for the required
106*da58b97aSjoerg     // memory without any knowledge of this transform.
107*da58b97aSjoerg 
108*da58b97aSjoerg     // An operand bundle on llvm.donothing works because the call instruction
109*da58b97aSjoerg     // survives until after the last pass that needs to account for LDS. It is
110*da58b97aSjoerg     // better than inline asm as the latter survives until the end of codegen. A
111*da58b97aSjoerg     // totally robust solution would be a function with the same semantics as
112*da58b97aSjoerg     // llvm.donothing that takes a pointer to the instance and is lowered to a
113*da58b97aSjoerg     // no-op after LDS is allocated, but that is not presently necessary.
114*da58b97aSjoerg 
115*da58b97aSjoerg     LLVMContext &Ctx = Func->getContext();
116*da58b97aSjoerg 
117*da58b97aSjoerg     Builder.SetInsertPoint(Func->getEntryBlock().getFirstNonPHI());
118*da58b97aSjoerg 
119*da58b97aSjoerg     FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), {});
120*da58b97aSjoerg 
121*da58b97aSjoerg     Function *Decl =
122*da58b97aSjoerg         Intrinsic::getDeclaration(Func->getParent(), Intrinsic::donothing, {});
123*da58b97aSjoerg 
124*da58b97aSjoerg     Value *UseInstance[1] = {Builder.CreateInBoundsGEP(
125*da58b97aSjoerg         SGV->getValueType(), SGV, ConstantInt::get(Type::getInt32Ty(Ctx), 0))};
126*da58b97aSjoerg 
127*da58b97aSjoerg     Builder.CreateCall(FTy, Decl, {},
128*da58b97aSjoerg                        {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)},
129*da58b97aSjoerg                        "");
130*da58b97aSjoerg   }
131*da58b97aSjoerg 
132*da58b97aSjoerg public:
133*da58b97aSjoerg   static char ID;
134*da58b97aSjoerg 
AMDGPULowerModuleLDS()135*da58b97aSjoerg   AMDGPULowerModuleLDS() : ModulePass(ID) {
136*da58b97aSjoerg     initializeAMDGPULowerModuleLDSPass(*PassRegistry::getPassRegistry());
137*da58b97aSjoerg   }
138*da58b97aSjoerg 
runOnModule(Module & M)139*da58b97aSjoerg   bool runOnModule(Module &M) override {
140*da58b97aSjoerg     LLVMContext &Ctx = M.getContext();
141*da58b97aSjoerg     const DataLayout &DL = M.getDataLayout();
142*da58b97aSjoerg     SmallPtrSet<GlobalValue *, 32> UsedList = AMDGPU::getUsedList(M);
143*da58b97aSjoerg 
144*da58b97aSjoerg     // Find variables to move into new struct instance
145*da58b97aSjoerg     std::vector<GlobalVariable *> FoundLocalVars =
146*da58b97aSjoerg         AMDGPU::findVariablesToLower(M, UsedList);
147*da58b97aSjoerg 
148*da58b97aSjoerg     if (FoundLocalVars.empty()) {
149*da58b97aSjoerg       // No variables to rewrite, no changes made.
150*da58b97aSjoerg       return false;
151*da58b97aSjoerg     }
152*da58b97aSjoerg 
153*da58b97aSjoerg     // Sort by alignment, descending, to minimise padding.
154*da58b97aSjoerg     // On ties, sort by size, descending, then by name, lexicographical.
155*da58b97aSjoerg     llvm::stable_sort(
156*da58b97aSjoerg         FoundLocalVars,
157*da58b97aSjoerg         [&](const GlobalVariable *LHS, const GlobalVariable *RHS) -> bool {
158*da58b97aSjoerg           Align ALHS = AMDGPU::getAlign(DL, LHS);
159*da58b97aSjoerg           Align ARHS = AMDGPU::getAlign(DL, RHS);
160*da58b97aSjoerg           if (ALHS != ARHS) {
161*da58b97aSjoerg             return ALHS > ARHS;
162*da58b97aSjoerg           }
163*da58b97aSjoerg 
164*da58b97aSjoerg           TypeSize SLHS = DL.getTypeAllocSize(LHS->getValueType());
165*da58b97aSjoerg           TypeSize SRHS = DL.getTypeAllocSize(RHS->getValueType());
166*da58b97aSjoerg           if (SLHS != SRHS) {
167*da58b97aSjoerg             return SLHS > SRHS;
168*da58b97aSjoerg           }
169*da58b97aSjoerg 
170*da58b97aSjoerg           // By variable name on tie for predictable order in test cases.
171*da58b97aSjoerg           return LHS->getName() < RHS->getName();
172*da58b97aSjoerg         });
173*da58b97aSjoerg 
174*da58b97aSjoerg     std::vector<GlobalVariable *> LocalVars;
175*da58b97aSjoerg     LocalVars.reserve(FoundLocalVars.size()); // will be at least this large
176*da58b97aSjoerg     {
177*da58b97aSjoerg       // This usually won't need to insert any padding, perhaps avoid the alloc
178*da58b97aSjoerg       uint64_t CurrentOffset = 0;
179*da58b97aSjoerg       for (size_t I = 0; I < FoundLocalVars.size(); I++) {
180*da58b97aSjoerg         GlobalVariable *FGV = FoundLocalVars[I];
181*da58b97aSjoerg         Align DataAlign = AMDGPU::getAlign(DL, FGV);
182*da58b97aSjoerg 
183*da58b97aSjoerg         uint64_t DataAlignV = DataAlign.value();
184*da58b97aSjoerg         if (uint64_t Rem = CurrentOffset % DataAlignV) {
185*da58b97aSjoerg           uint64_t Padding = DataAlignV - Rem;
186*da58b97aSjoerg 
187*da58b97aSjoerg           // Append an array of padding bytes to meet alignment requested
188*da58b97aSjoerg           // Note (o +      (a - (o % a)) ) % a == 0
189*da58b97aSjoerg           //      (offset + Padding       ) % align == 0
190*da58b97aSjoerg 
191*da58b97aSjoerg           Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding);
192*da58b97aSjoerg           LocalVars.push_back(new GlobalVariable(
193*da58b97aSjoerg               M, ATy, false, GlobalValue::InternalLinkage, UndefValue::get(ATy),
194*da58b97aSjoerg               "", nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS,
195*da58b97aSjoerg               false));
196*da58b97aSjoerg           CurrentOffset += Padding;
197*da58b97aSjoerg         }
198*da58b97aSjoerg 
199*da58b97aSjoerg         LocalVars.push_back(FGV);
200*da58b97aSjoerg         CurrentOffset += DL.getTypeAllocSize(FGV->getValueType());
201*da58b97aSjoerg       }
202*da58b97aSjoerg     }
203*da58b97aSjoerg 
204*da58b97aSjoerg     std::vector<Type *> LocalVarTypes;
205*da58b97aSjoerg     LocalVarTypes.reserve(LocalVars.size());
206*da58b97aSjoerg     std::transform(
207*da58b97aSjoerg         LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes),
208*da58b97aSjoerg         [](const GlobalVariable *V) -> Type * { return V->getValueType(); });
209*da58b97aSjoerg 
210*da58b97aSjoerg     StructType *LDSTy = StructType::create(
211*da58b97aSjoerg         Ctx, LocalVarTypes, llvm::StringRef("llvm.amdgcn.module.lds.t"));
212*da58b97aSjoerg 
213*da58b97aSjoerg     Align MaxAlign =
214*da58b97aSjoerg         AMDGPU::getAlign(DL, LocalVars[0]); // was sorted on alignment
215*da58b97aSjoerg 
216*da58b97aSjoerg     GlobalVariable *SGV = new GlobalVariable(
217*da58b97aSjoerg         M, LDSTy, false, GlobalValue::InternalLinkage, UndefValue::get(LDSTy),
218*da58b97aSjoerg         "llvm.amdgcn.module.lds", nullptr, GlobalValue::NotThreadLocal,
219*da58b97aSjoerg         AMDGPUAS::LOCAL_ADDRESS, false);
220*da58b97aSjoerg     SGV->setAlignment(MaxAlign);
221*da58b97aSjoerg     appendToCompilerUsed(
222*da58b97aSjoerg         M, {static_cast<GlobalValue *>(
223*da58b97aSjoerg                ConstantExpr::getPointerBitCastOrAddrSpaceCast(
224*da58b97aSjoerg                    cast<Constant>(SGV), Type::getInt8PtrTy(Ctx)))});
225*da58b97aSjoerg 
226*da58b97aSjoerg     // The verifier rejects used lists containing an inttoptr of a constant
227*da58b97aSjoerg     // so remove the variables from these lists before replaceAllUsesWith
228*da58b97aSjoerg     removeFromUsedLists(M, LocalVars);
229*da58b97aSjoerg 
230*da58b97aSjoerg     // Replace uses of ith variable with a constantexpr to the ith field of the
231*da58b97aSjoerg     // instance that will be allocated by AMDGPUMachineFunction
232*da58b97aSjoerg     Type *I32 = Type::getInt32Ty(Ctx);
233*da58b97aSjoerg     for (size_t I = 0; I < LocalVars.size(); I++) {
234*da58b97aSjoerg       GlobalVariable *GV = LocalVars[I];
235*da58b97aSjoerg       Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)};
236*da58b97aSjoerg       GV->replaceAllUsesWith(
237*da58b97aSjoerg           ConstantExpr::getGetElementPtr(LDSTy, SGV, GEPIdx));
238*da58b97aSjoerg       GV->eraseFromParent();
239*da58b97aSjoerg     }
240*da58b97aSjoerg 
241*da58b97aSjoerg     // Mark kernels with asm that reads the address of the allocated structure
242*da58b97aSjoerg     // This is not necessary for lowering. This lets other passes, specifically
243*da58b97aSjoerg     // PromoteAlloca, accurately calculate how much LDS will be used by the
244*da58b97aSjoerg     // kernel after lowering.
245*da58b97aSjoerg     {
246*da58b97aSjoerg       IRBuilder<> Builder(Ctx);
247*da58b97aSjoerg       SmallPtrSet<Function *, 32> Kernels;
248*da58b97aSjoerg       for (auto &I : M.functions()) {
249*da58b97aSjoerg         Function *Func = &I;
250*da58b97aSjoerg         if (AMDGPU::isKernelCC(Func) && !Kernels.contains(Func)) {
251*da58b97aSjoerg           markUsedByKernel(Builder, Func, SGV);
252*da58b97aSjoerg           Kernels.insert(Func);
253*da58b97aSjoerg         }
254*da58b97aSjoerg       }
255*da58b97aSjoerg     }
256*da58b97aSjoerg     return true;
257*da58b97aSjoerg   }
258*da58b97aSjoerg };
259*da58b97aSjoerg 
260*da58b97aSjoerg } // namespace
261*da58b97aSjoerg char AMDGPULowerModuleLDS::ID = 0;
262*da58b97aSjoerg 
263*da58b97aSjoerg char &llvm::AMDGPULowerModuleLDSID = AMDGPULowerModuleLDS::ID;
264*da58b97aSjoerg 
265*da58b97aSjoerg INITIALIZE_PASS(AMDGPULowerModuleLDS, DEBUG_TYPE,
266*da58b97aSjoerg                 "Lower uses of LDS variables from non-kernel functions", false,
267*da58b97aSjoerg                 false)
268*da58b97aSjoerg 
createAMDGPULowerModuleLDSPass()269*da58b97aSjoerg ModulePass *llvm::createAMDGPULowerModuleLDSPass() {
270*da58b97aSjoerg   return new AMDGPULowerModuleLDS();
271*da58b97aSjoerg }
272*da58b97aSjoerg 
run(Module & M,ModuleAnalysisManager &)273*da58b97aSjoerg PreservedAnalyses AMDGPULowerModuleLDSPass::run(Module &M,
274*da58b97aSjoerg                                                 ModuleAnalysisManager &) {
275*da58b97aSjoerg   return AMDGPULowerModuleLDS().runOnModule(M) ? PreservedAnalyses::none()
276*da58b97aSjoerg                                                : PreservedAnalyses::all();
277*da58b97aSjoerg }
278