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 LDS uses from non-kernel functions. 10 // 11 // The strategy is to create a new struct with a field for each LDS variable 12 // and allocate that struct at the same address for every kernel. Uses of the 13 // original LDS variables are then replaced with compile time offsets from that 14 // known address. AMDGPUMachineFunction allocates the LDS global. 15 // 16 // Local variables with constant annotation or non-undef initializer are passed 17 // through unchanged for simplication or error diagnostics in later passes. 18 // 19 // To reduce the memory overhead variables that are only used by kernels are 20 // excluded from this transform. The analysis to determine whether a variable 21 // is only used by a kernel is cheap and conservative so this may allocate 22 // a variable in every kernel when it was not strictly necessary to do so. 23 // 24 // A possible future refinement is to specialise the structure per-kernel, so 25 // that fields can be elided based on more expensive analysis. 26 // 27 //===----------------------------------------------------------------------===// 28 29 #include "AMDGPU.h" 30 #include "Utils/AMDGPUBaseInfo.h" 31 #include "Utils/AMDGPULDSUtils.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DerivedTypes.h" 35 #include "llvm/IR/IRBuilder.h" 36 #include "llvm/IR/InlineAsm.h" 37 #include "llvm/IR/Instructions.h" 38 #include "llvm/IR/MDBuilder.h" 39 #include "llvm/InitializePasses.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/CommandLine.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/OptimizedStructLayout.h" 44 #include "llvm/Transforms/Utils/ModuleUtils.h" 45 #include <vector> 46 47 #define DEBUG_TYPE "amdgpu-lower-module-lds" 48 49 using namespace llvm; 50 51 static cl::opt<bool> SuperAlignLDSGlobals( 52 "amdgpu-super-align-lds-globals", 53 cl::desc("Increase alignment of LDS if it is not on align boundary"), 54 cl::init(true), cl::Hidden); 55 56 namespace { 57 58 class AMDGPULowerModuleLDS : public ModulePass { 59 60 static void removeFromUsedList(Module &M, StringRef Name, 61 SmallPtrSetImpl<Constant *> &ToRemove) { 62 GlobalVariable *GV = M.getNamedGlobal(Name); 63 if (!GV || ToRemove.empty()) { 64 return; 65 } 66 67 SmallVector<Constant *, 16> Init; 68 auto *CA = cast<ConstantArray>(GV->getInitializer()); 69 for (auto &Op : CA->operands()) { 70 // ModuleUtils::appendToUsed only inserts Constants 71 Constant *C = cast<Constant>(Op); 72 if (!ToRemove.contains(C->stripPointerCasts())) { 73 Init.push_back(C); 74 } 75 } 76 77 if (Init.size() == CA->getNumOperands()) { 78 return; // none to remove 79 } 80 81 GV->eraseFromParent(); 82 83 for (Constant *C : ToRemove) { 84 C->removeDeadConstantUsers(); 85 } 86 87 if (!Init.empty()) { 88 ArrayType *ATy = 89 ArrayType::get(Type::getInt8PtrTy(M.getContext()), Init.size()); 90 GV = 91 new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage, 92 ConstantArray::get(ATy, Init), Name); 93 GV->setSection("llvm.metadata"); 94 } 95 } 96 97 static void 98 removeFromUsedLists(Module &M, 99 const std::vector<GlobalVariable *> &LocalVars) { 100 SmallPtrSet<Constant *, 32> LocalVarsSet; 101 for (size_t I = 0; I < LocalVars.size(); I++) { 102 if (Constant *C = dyn_cast<Constant>(LocalVars[I]->stripPointerCasts())) { 103 LocalVarsSet.insert(C); 104 } 105 } 106 removeFromUsedList(M, "llvm.used", LocalVarsSet); 107 removeFromUsedList(M, "llvm.compiler.used", LocalVarsSet); 108 } 109 110 static void markUsedByKernel(IRBuilder<> &Builder, Function *Func, 111 GlobalVariable *SGV) { 112 // The llvm.amdgcn.module.lds instance is implicitly used by all kernels 113 // that might call a function which accesses a field within it. This is 114 // presently approximated to 'all kernels' if there are any such functions 115 // in the module. This implicit use is redefined as an explicit use here so 116 // that later passes, specifically PromoteAlloca, account for the required 117 // memory without any knowledge of this transform. 118 119 // An operand bundle on llvm.donothing works because the call instruction 120 // survives until after the last pass that needs to account for LDS. It is 121 // better than inline asm as the latter survives until the end of codegen. A 122 // totally robust solution would be a function with the same semantics as 123 // llvm.donothing that takes a pointer to the instance and is lowered to a 124 // no-op after LDS is allocated, but that is not presently necessary. 125 126 LLVMContext &Ctx = Func->getContext(); 127 128 Builder.SetInsertPoint(Func->getEntryBlock().getFirstNonPHI()); 129 130 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), {}); 131 132 Function *Decl = 133 Intrinsic::getDeclaration(Func->getParent(), Intrinsic::donothing, {}); 134 135 Value *UseInstance[1] = {Builder.CreateInBoundsGEP( 136 SGV->getValueType(), SGV, ConstantInt::get(Type::getInt32Ty(Ctx), 0))}; 137 138 Builder.CreateCall(FTy, Decl, {}, 139 {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)}, 140 ""); 141 } 142 143 private: 144 SmallPtrSet<GlobalValue *, 32> UsedList; 145 146 public: 147 static char ID; 148 149 AMDGPULowerModuleLDS() : ModulePass(ID) { 150 initializeAMDGPULowerModuleLDSPass(*PassRegistry::getPassRegistry()); 151 } 152 153 bool runOnModule(Module &M) override { 154 bool Changed = processUsedLDS(M); 155 156 for (Function &F : M.functions()) { 157 if (F.isDeclaration()) 158 continue; 159 160 // Only lower compute kernels' LDS. 161 if (!AMDGPU::isKernel(F.getCallingConv())) 162 continue; 163 Changed |= processUsedLDS(M, &F); 164 } 165 166 return Changed; 167 } 168 169 private: 170 bool processUsedLDS(Module &M, Function *F = nullptr) { 171 LLVMContext &Ctx = M.getContext(); 172 const DataLayout &DL = M.getDataLayout(); 173 174 // Find variables to move into new struct instance 175 std::vector<GlobalVariable *> FoundLocalVars = 176 AMDGPU::findVariablesToLower(M, F); 177 178 if (FoundLocalVars.empty()) { 179 // No variables to rewrite, no changes made. 180 return false; 181 } 182 183 // Increase the alignment of LDS globals if necessary to maximise the chance 184 // that we can use aligned LDS instructions to access them. 185 if (SuperAlignLDSGlobals) { 186 for (auto *GV : FoundLocalVars) { 187 Align Alignment = AMDGPU::getAlign(DL, GV); 188 TypeSize GVSize = DL.getTypeAllocSize(GV->getValueType()); 189 190 if (GVSize > 8) { 191 // We might want to use a b96 or b128 load/store 192 Alignment = std::max(Alignment, Align(16)); 193 } else if (GVSize > 4) { 194 // We might want to use a b64 load/store 195 Alignment = std::max(Alignment, Align(8)); 196 } else if (GVSize > 2) { 197 // We might want to use a b32 load/store 198 Alignment = std::max(Alignment, Align(4)); 199 } else if (GVSize > 1) { 200 // We might want to use a b16 load/store 201 Alignment = std::max(Alignment, Align(2)); 202 } 203 204 GV->setAlignment(Alignment); 205 } 206 } 207 208 SmallVector<OptimizedStructLayoutField, 8> LayoutFields; 209 LayoutFields.reserve(FoundLocalVars.size()); 210 for (GlobalVariable *GV : FoundLocalVars) { 211 OptimizedStructLayoutField F(GV, DL.getTypeAllocSize(GV->getValueType()), 212 AMDGPU::getAlign(DL, GV)); 213 LayoutFields.emplace_back(F); 214 } 215 216 performOptimizedStructLayout(LayoutFields); 217 218 std::vector<GlobalVariable *> LocalVars; 219 LocalVars.reserve(FoundLocalVars.size()); // will be at least this large 220 { 221 // This usually won't need to insert any padding, perhaps avoid the alloc 222 uint64_t CurrentOffset = 0; 223 for (size_t I = 0; I < LayoutFields.size(); I++) { 224 GlobalVariable *FGV = static_cast<GlobalVariable *>( 225 const_cast<void *>(LayoutFields[I].Id)); 226 Align DataAlign = LayoutFields[I].Alignment; 227 228 uint64_t DataAlignV = DataAlign.value(); 229 if (uint64_t Rem = CurrentOffset % DataAlignV) { 230 uint64_t Padding = DataAlignV - Rem; 231 232 // Append an array of padding bytes to meet alignment requested 233 // Note (o + (a - (o % a)) ) % a == 0 234 // (offset + Padding ) % align == 0 235 236 Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding); 237 LocalVars.push_back(new GlobalVariable( 238 M, ATy, false, GlobalValue::InternalLinkage, UndefValue::get(ATy), 239 "", nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, 240 false)); 241 CurrentOffset += Padding; 242 } 243 244 LocalVars.push_back(FGV); 245 CurrentOffset += LayoutFields[I].Size; 246 } 247 } 248 249 std::vector<Type *> LocalVarTypes; 250 LocalVarTypes.reserve(LocalVars.size()); 251 std::transform( 252 LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes), 253 [](const GlobalVariable *V) -> Type * { return V->getValueType(); }); 254 255 std::string VarName( 256 F ? (Twine("llvm.amdgcn.kernel.") + F->getName() + ".lds").str() 257 : "llvm.amdgcn.module.lds"); 258 StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t"); 259 260 Align StructAlign = 261 AMDGPU::getAlign(DL, LocalVars[0]); 262 263 GlobalVariable *SGV = new GlobalVariable( 264 M, LDSTy, false, GlobalValue::InternalLinkage, UndefValue::get(LDSTy), 265 VarName, nullptr, GlobalValue::NotThreadLocal, AMDGPUAS::LOCAL_ADDRESS, 266 false); 267 SGV->setAlignment(StructAlign); 268 if (!F) { 269 appendToCompilerUsed( 270 M, {static_cast<GlobalValue *>( 271 ConstantExpr::getPointerBitCastOrAddrSpaceCast( 272 cast<Constant>(SGV), Type::getInt8PtrTy(Ctx)))}); 273 } 274 275 // The verifier rejects used lists containing an inttoptr of a constant 276 // so remove the variables from these lists before replaceAllUsesWith 277 removeFromUsedLists(M, LocalVars); 278 279 // Create alias.scope and their lists. Each field in the new structure 280 // does not alias with all other fields. 281 SmallVector<MDNode *> AliasScopes; 282 SmallVector<Metadata *> NoAliasList; 283 if (LocalVars.size() > 1) { 284 MDBuilder MDB(Ctx); 285 AliasScopes.reserve(LocalVars.size()); 286 MDNode *Domain = MDB.createAnonymousAliasScopeDomain(); 287 for (size_t I = 0; I < LocalVars.size(); I++) { 288 MDNode *Scope = MDB.createAnonymousAliasScope(Domain); 289 AliasScopes.push_back(Scope); 290 } 291 NoAliasList.append(&AliasScopes[1], AliasScopes.end()); 292 } 293 294 // Replace uses of ith variable with a constantexpr to the ith field of the 295 // instance that will be allocated by AMDGPUMachineFunction 296 Type *I32 = Type::getInt32Ty(Ctx); 297 for (size_t I = 0; I < LocalVars.size(); I++) { 298 GlobalVariable *GV = LocalVars[I]; 299 Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)}; 300 Constant *GEP = ConstantExpr::getGetElementPtr(LDSTy, SGV, GEPIdx); 301 if (F) { 302 // Replace all constant uses with instructions if they belong to the 303 // current kernel. 304 for (User *U : make_early_inc_range(GV->users())) { 305 if (ConstantExpr *C = dyn_cast<ConstantExpr>(U)) 306 AMDGPU::replaceConstantUsesInFunction(C, F); 307 } 308 309 GV->removeDeadConstantUsers(); 310 311 GV->replaceUsesWithIf(GEP, [F](Use &U) { 312 Instruction *I = dyn_cast<Instruction>(U.getUser()); 313 return I && I->getFunction() == F; 314 }); 315 } else { 316 GV->replaceAllUsesWith(GEP); 317 } 318 if (GV->use_empty()) { 319 UsedList.erase(GV); 320 GV->eraseFromParent(); 321 } 322 323 uint64_t Off = DL.getStructLayout(LDSTy)->getElementOffset(I); 324 Align A = commonAlignment(StructAlign, Off); 325 326 if (I) 327 NoAliasList[I - 1] = AliasScopes[I - 1]; 328 MDNode *NoAlias = 329 NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList); 330 MDNode *AliasScope = 331 AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]}); 332 333 refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias); 334 } 335 336 // This ensures the variable is allocated when called functions access it. 337 // It also lets other passes, specifically PromoteAlloca, accurately 338 // calculate how much LDS will be used by the kernel after lowering. 339 if (!F) { 340 IRBuilder<> Builder(Ctx); 341 for (Function &Func : M.functions()) { 342 if (!Func.isDeclaration() && AMDGPU::isKernelCC(&Func)) { 343 markUsedByKernel(Builder, &Func, SGV); 344 } 345 } 346 } 347 return true; 348 } 349 350 void refineUsesAlignmentAndAA(Value *Ptr, Align A, const DataLayout &DL, 351 MDNode *AliasScope, MDNode *NoAlias, 352 unsigned MaxDepth = 5) { 353 if (!MaxDepth || (A == 1 && !AliasScope)) 354 return; 355 356 for (User *U : Ptr->users()) { 357 if (auto *I = dyn_cast<Instruction>(U)) { 358 if (AliasScope && I->mayReadOrWriteMemory()) { 359 MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope); 360 AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope) 361 : AliasScope); 362 I->setMetadata(LLVMContext::MD_alias_scope, AS); 363 364 MDNode *NA = I->getMetadata(LLVMContext::MD_noalias); 365 NA = (NA ? MDNode::intersect(NA, NoAlias) : NoAlias); 366 I->setMetadata(LLVMContext::MD_noalias, NA); 367 } 368 } 369 370 if (auto *LI = dyn_cast<LoadInst>(U)) { 371 LI->setAlignment(std::max(A, LI->getAlign())); 372 continue; 373 } 374 if (auto *SI = dyn_cast<StoreInst>(U)) { 375 if (SI->getPointerOperand() == Ptr) 376 SI->setAlignment(std::max(A, SI->getAlign())); 377 continue; 378 } 379 if (auto *AI = dyn_cast<AtomicRMWInst>(U)) { 380 // None of atomicrmw operations can work on pointers, but let's 381 // check it anyway in case it will or we will process ConstantExpr. 382 if (AI->getPointerOperand() == Ptr) 383 AI->setAlignment(std::max(A, AI->getAlign())); 384 continue; 385 } 386 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) { 387 if (AI->getPointerOperand() == Ptr) 388 AI->setAlignment(std::max(A, AI->getAlign())); 389 continue; 390 } 391 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { 392 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType()); 393 APInt Off(BitWidth, 0); 394 if (GEP->getPointerOperand() == Ptr) { 395 Align GA; 396 if (GEP->accumulateConstantOffset(DL, Off)) 397 GA = commonAlignment(A, Off.getLimitedValue()); 398 refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias, 399 MaxDepth - 1); 400 } 401 continue; 402 } 403 if (auto *I = dyn_cast<Instruction>(U)) { 404 if (I->getOpcode() == Instruction::BitCast || 405 I->getOpcode() == Instruction::AddrSpaceCast) 406 refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1); 407 } 408 } 409 } 410 }; 411 412 } // namespace 413 char AMDGPULowerModuleLDS::ID = 0; 414 415 char &llvm::AMDGPULowerModuleLDSID = AMDGPULowerModuleLDS::ID; 416 417 INITIALIZE_PASS(AMDGPULowerModuleLDS, DEBUG_TYPE, 418 "Lower uses of LDS variables from non-kernel functions", false, 419 false) 420 421 ModulePass *llvm::createAMDGPULowerModuleLDSPass() { 422 return new AMDGPULowerModuleLDS(); 423 } 424 425 PreservedAnalyses AMDGPULowerModuleLDSPass::run(Module &M, 426 ModuleAnalysisManager &) { 427 return AMDGPULowerModuleLDS().runOnModule(M) ? PreservedAnalyses::none() 428 : PreservedAnalyses::all(); 429 } 430