LLVM 24.0.0git
AMDGPULowerModuleLDSPass.cpp
Go to the documentation of this file.
1//===-- AMDGPULowerModuleLDSPass.cpp ------------------------------*- C++ -*-=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass eliminates local data store, LDS, uses from non-kernel functions.
10// LDS is contiguous memory allocated per kernel execution.
11//
12// Background.
13//
14// The programming model is global variables, or equivalently function local
15// static variables, accessible from kernels or other functions. For uses from
16// kernels this is straightforward - assign an integer to the kernel for the
17// memory required by all the variables combined, allocate them within that.
18// For uses from functions there are performance tradeoffs to choose between.
19//
20// This model means the GPU runtime can specify the amount of memory allocated.
21// If this is more than the kernel assumed, the excess can be made available
22// using a language specific feature, which IR represents as a variable with
23// no initializer. This feature is referred to here as "Dynamic LDS" and is
24// lowered slightly differently to the normal case.
25//
26// Consequences of this GPU feature:
27// - memory is limited and exceeding it halts compilation
28// - a global accessed by one kernel exists independent of other kernels
29// - a global exists independent of simultaneous execution of the same kernel
30// - the address of the global may be different from different kernels as they
31// do not alias, which permits only allocating variables they use
32// - if the address is allowed to differ, functions need help to find it
33//
34// Uses from kernels are implemented here by grouping them in a per-kernel
35// struct instance. This duplicates the variables, accurately modelling their
36// aliasing properties relative to a single global representation. It also
37// permits control over alignment via padding.
38//
39// Uses from functions are more complicated and the primary purpose of this
40// IR pass. Several different lowering are chosen between to meet requirements
41// to avoid allocating any LDS where it is not necessary, as that impacts
42// occupancy and may fail the compilation, while not imposing overhead on a
43// feature whose primary advantage over global memory is performance. The basic
44// design goal is to avoid one kernel imposing overhead on another.
45//
46// Implementation.
47//
48// LDS variables with constant annotation or non-undef initializer are passed
49// through unchanged for simplification or error diagnostics in later passes.
50// Non-undef initializers are not yet implemented for LDS.
51//
52// LDS variables that are always allocated at the same address can be found
53// by lookup at that address. Otherwise runtime information/cost is required.
54//
55// The simplest strategy possible is to group all LDS variables in a single
56// struct and allocate that struct in every kernel such that the original
57// variables are always at the same address. LDS is however a limited resource
58// so this strategy is unusable in practice. It is not implemented here.
59//
60// Strategy | Precise allocation | Zero runtime cost | General purpose |
61// --------+--------------------+-------------------+-----------------+
62// Module | No | Yes | Yes |
63// Table | Yes | No | Yes |
64// Kernel | Yes | Yes | No |
65// Hybrid | Yes | Partial | Yes |
66//
67// "Module" spends LDS memory to save cycles. "Table" spends cycles and global
68// memory to save LDS. "Kernel" is as fast as kernel allocation but only works
69// for variables that are known reachable from a single kernel. "Hybrid" picks
70// between all three. When forced to choose between LDS and cycles we minimise
71// LDS use.
72
73// The "module" lowering implemented here finds LDS variables which are used by
74// non-kernel functions and creates a new struct with a field for each of those
75// LDS variables. Variables that are only used from kernels are excluded.
76//
77// The "table" lowering implemented here has three components.
78// First kernels are assigned a unique integer identifier which is available in
79// functions it calls through the intrinsic amdgcn_lds_kernel_id. The integer
80// is passed through a specific SGPR, thus works with indirect calls.
81// Second, each kernel allocates LDS variables independent of other kernels and
82// writes the addresses it chose for each variable into an array in consistent
83// order. If the kernel does not allocate a given variable, it writes undef to
84// the corresponding array location. These arrays are written to a constant
85// table in the order matching the kernel unique integer identifier.
86// Third, uses from non-kernel functions are replaced with a table lookup using
87// the intrinsic function to find the address of the variable.
88//
89// "Kernel" lowering is only applicable for variables that are unambiguously
90// reachable from exactly one kernel. For those cases, accesses to the variable
91// can be lowered to ConstantExpr address of a struct instance specific to that
92// one kernel. This is zero cost in space and in compute. It will raise a fatal
93// error on any variable that might be reachable from multiple kernels and is
94// thus most easily used as part of the hybrid lowering strategy.
95//
96// Hybrid lowering is a mixture of the above. It uses the zero cost kernel
97// lowering where it can. It lowers the variable accessed by the greatest
98// number of kernels using the module strategy as that is free for the first
99// variable. Any futher variables that can be lowered with the module strategy
100// without incurring LDS memory overhead are. The remaining ones are lowered
101// via table.
102//
103// Consequences
104// - No heuristics or user controlled magic numbers, hybrid is the right choice
105// - Kernels that don't use functions (or have had them all inlined) are not
106// affected by any lowering for kernels that do.
107// - Kernels that don't make indirect function calls are not affected by those
108// that do.
109// - Variables which are used by lots of kernels, e.g. those injected by a
110// language runtime in most kernels, are expected to have no overhead
111// - Implementations that instantiate templates per-kernel where those templates
112// use LDS are expected to hit the "Kernel" lowering strategy
113// - The runtime properties impose a cost in compiler implementation complexity
114//
115// Dynamic LDS implementation
116// Dynamic LDS is lowered similarly to the "table" strategy above and uses the
117// same intrinsic to identify which kernel is at the root of the dynamic call
118// graph. This relies on the specified behaviour that all dynamic LDS variables
119// alias one another, i.e. are at the same address, with respect to a given
120// kernel. Therefore this pass creates new dynamic LDS variables for each kernel
121// that allocates any dynamic LDS and builds a table of addresses out of those.
122// The AMDGPUPromoteAlloca pass skips kernels that use dynamic LDS.
123// The corresponding optimisation for "kernel" lowering where the table lookup
124// is elided is not implemented.
125//
126//
127// Implementation notes / limitations
128// A single LDS global variable represents an instance per kernel that can reach
129// said variables. This pass essentially specialises said variables per kernel.
130// Handling ConstantExpr during the pass complicated this significantly so now
131// all ConstantExpr uses of LDS variables are expanded to instructions. This
132// may need amending when implementing non-undef initialisers.
133//
134// Lowering is split between this IR pass and the back end. This pass chooses
135// where given variables should be allocated and marks them with metadata,
136// MD_absolute_symbol. The backend places the variables in coincidentally the
137// same location and raises a fatal error if something has gone awry. This works
138// in practice because the only pass between this one and the backend that
139// changes LDS is PromoteAlloca and the changes it makes do not conflict.
140//
141// Addresses are written to constant global arrays based on the same metadata.
142//
143// The backend lowers LDS variables in the order of traversal of the function.
144// This is at odds with the deterministic layout required. The workaround is to
145// allocate the fixed-address variables immediately upon starting the function
146// where they can be placed as intended. This requires a means of mapping from
147// the function to the variables that it allocates. For the module scope lds,
148// this is via metadata indicating whether the variable is not required. If a
149// pass deletes that metadata, a fatal error on disagreement with the absolute
150// symbol metadata will occur. For kernel scope and dynamic, this is by _name_
151// correspondence between the function and the variable. It requires the
152// kernel to have a name (which is only a limitation for tests in practice) and
153// for nothing to rename the corresponding symbols. This is a hazard if the pass
154// is run multiple times during debugging. Alternative schemes considered all
155// involve bespoke metadata.
156//
157// If the name correspondence can be replaced, multiple distinct kernels that
158// have the same memory layout can map to the same kernel id (as the address
159// itself is handled by the absolute symbol metadata) and that will allow more
160// uses of the "kernel" style faster lowering and reduce the size of the lookup
161// tables.
162//
163// There is a test that checks this does not fire for a graphics shader. This
164// lowering is expected to work for graphics if the isKernel test is changed.
165//
166// The current markUsedByKernel is sufficient for PromoteAlloca but is elided
167// before codegen. Replacing this with an equivalent intrinsic which lasts until
168// shortly after the machine function lowering of LDS would help break the name
169// mapping. The other part needed is probably to amend PromoteAlloca to embed
170// the LDS variables it creates in the same struct created here. That avoids the
171// current hazard where a PromoteAlloca LDS variable might be allocated before
172// the kernel scope (and thus error on the address check). Given a new invariant
173// that no LDS variables exist outside of the structs managed here, and an
174// intrinsic that lasts until after the LDS frame lowering, it should be
175// possible to drop the name mapping and fold equivalent memory layouts.
176//
177//===----------------------------------------------------------------------===//
178
179#include "AMDGPU.h"
180#include "AMDGPUMemoryUtils.h"
181#include "AMDGPUTargetMachine.h"
182#include "Utils/AMDGPUBaseInfo.h"
183#include "llvm/ADT/BitVector.h"
184#include "llvm/ADT/STLExtras.h"
189#include "llvm/IR/Constants.h"
190#include "llvm/IR/DerivedTypes.h"
191#include "llvm/IR/Dominators.h"
192#include "llvm/IR/IRBuilder.h"
193#include "llvm/IR/InlineAsm.h"
194#include "llvm/IR/Instructions.h"
195#include "llvm/IR/IntrinsicsAMDGPU.h"
196#include "llvm/IR/MDBuilder.h"
199#include "llvm/Pass.h"
201#include "llvm/Support/Format.h"
206
207#include <cstdio>
208
209#define DEBUG_TYPE "amdgpu-lower-module-lds"
210
211using namespace llvm;
212using namespace AMDGPU;
213
214namespace {
215
216cl::opt<bool> SuperAlignLDSGlobals(
217 "amdgpu-super-align-lds-globals",
218 cl::desc("Increase alignment of LDS if it is not on align boundary"),
219 cl::init(true), cl::Hidden);
220
221enum class LoweringKind { module, table, kernel, hybrid };
222cl::opt<LoweringKind> LoweringKindLoc(
223 "amdgpu-lower-module-lds-strategy",
224 cl::desc("Specify lowering strategy for function LDS access:"), cl::Hidden,
225 cl::init(LoweringKind::hybrid),
227 clEnumValN(LoweringKind::table, "table", "Lower via table lookup"),
228 clEnumValN(LoweringKind::module, "module", "Lower via module struct"),
230 LoweringKind::kernel, "kernel",
231 "Lower variables reachable from one kernel, otherwise abort"),
232 clEnumValN(LoweringKind::hybrid, "hybrid",
233 "Lower via mixture of above strategies")));
234
235template <typename T> std::vector<T> sortByName(std::vector<T> &&V) {
236 llvm::sort(V, [](const auto *L, const auto *R) {
237 return L->getName() < R->getName();
238 });
239 return {std::move(V)};
240}
241
242class AMDGPULowerModuleLDS {
243 const AMDGPUTargetMachine &TM;
244
245 static void
246 removeLocalVarsFromUsedLists(Module &M,
247 const DenseSet<GlobalVariable *> &LocalVars) {
248 // The verifier rejects used lists containing an inttoptr of a constant
249 // so remove the variables from these lists before replaceAllUsesWith
250 SmallPtrSet<Constant *, 8> LocalVarsSet;
251 for (GlobalVariable *LocalVar : LocalVars)
252 LocalVarsSet.insert(cast<Constant>(LocalVar->stripPointerCasts()));
253
255 M, [&LocalVarsSet](Constant *C) { return LocalVarsSet.count(C); });
256
257 for (GlobalVariable *LocalVar : LocalVars)
258 LocalVar->removeDeadConstantUsers();
259 }
260
261 static void markUsedByKernel(Function *Func, GlobalVariable *SGV) {
262 // The llvm.amdgcn.module.lds instance is implicitly used by all kernels
263 // that might call a function which accesses a field within it. This is
264 // presently approximated to 'all kernels' if there are any such functions
265 // in the module. This implicit use is redefined as an explicit use here so
266 // that later passes, specifically PromoteAlloca, account for the required
267 // memory without any knowledge of this transform.
268
269 // An operand bundle on llvm.donothing works because the call instruction
270 // survives until after the last pass that needs to account for LDS. It is
271 // better than inline asm as the latter survives until the end of codegen. A
272 // totally robust solution would be a function with the same semantics as
273 // llvm.donothing that takes a pointer to the instance and is lowered to a
274 // no-op after LDS is allocated, but that is not presently necessary.
275
276 // This intrinsic is eliminated shortly before instruction selection. It
277 // does not suffice to indicate to ISel that a given global which is not
278 // immediately used by the kernel must still be allocated by it. An
279 // equivalent target specific intrinsic which lasts until immediately after
280 // codegen would suffice for that, but one would still need to ensure that
281 // the variables are allocated in the anticipated order.
282 BasicBlock *Entry = &Func->getEntryBlock();
283 IRBuilder<> Builder(Entry, Entry->getFirstNonPHIIt());
284
286 Func->getParent(), Intrinsic::donothing, {});
287
288 Value *UseInstance[1] = {
289 Builder.CreateConstInBoundsGEP1_32(SGV->getValueType(), SGV, 0)};
290
291 Builder.CreateCall(
292 Decl, {}, {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)});
293 }
294
295public:
296 AMDGPULowerModuleLDS(const AMDGPUTargetMachine &TM_) : TM(TM_) {}
297
298 struct LDSVariableReplacement {
299 GlobalVariable *SGV = nullptr;
300 DenseMap<GlobalVariable *, Constant *> LDSVarsToConstantGEP;
301 };
302
303 // remap from lds global to a constantexpr gep to where it has been moved to
304 // for each kernel
305 // an array with an element for each kernel containing where the corresponding
306 // variable was remapped to
307
308 static Constant *getAddressesOfVariablesInKernel(
310 const DenseMap<GlobalVariable *, Constant *> &LDSVarsToConstantGEP) {
311 // Create a ConstantArray containing the address of each Variable within the
312 // kernel corresponding to LDSVarsToConstantGEP, or poison if that kernel
313 // does not allocate it
314
316 ArrayType *KernelOffsetsType = ArrayType::get(LocalPtrTy, Variables.size());
317
319 for (GlobalVariable *GV : Variables) {
320 auto ConstantGepIt = LDSVarsToConstantGEP.find(GV);
321 if (ConstantGepIt != LDSVarsToConstantGEP.end()) {
322 Elements.push_back(ConstantGepIt->second);
323 } else {
324 Elements.push_back(PoisonValue::get(LocalPtrTy));
325 }
326 }
327 return ConstantArray::get(KernelOffsetsType, Elements);
328 }
329
330 static GlobalVariable *buildLookupTable(
332 ArrayRef<Function *> kernels,
334 if (Variables.empty()) {
335 return nullptr;
336 }
337 LLVMContext &Ctx = M.getContext();
338
339 const size_t NumberVariables = Variables.size();
340 const size_t NumberKernels = kernels.size();
341
343 ArrayType *KernelOffsetsType = ArrayType::get(LocalPtrTy, NumberVariables);
344
345 ArrayType *AllKernelsOffsetsType =
346 ArrayType::get(KernelOffsetsType, NumberKernels);
347
348 Constant *Missing = PoisonValue::get(KernelOffsetsType);
349 std::vector<Constant *> overallConstantExprElts(NumberKernels);
350 for (size_t i = 0; i < NumberKernels; i++) {
351 auto Replacement = KernelToReplacement.find(kernels[i]);
352 overallConstantExprElts[i] =
353 (Replacement == KernelToReplacement.end())
354 ? Missing
355 : getAddressesOfVariablesInKernel(
356 Ctx, Variables, Replacement->second.LDSVarsToConstantGEP);
357 }
358
359 Constant *init =
360 ConstantArray::get(AllKernelsOffsetsType, overallConstantExprElts);
361
362 return new GlobalVariable(
363 M, AllKernelsOffsetsType, true, GlobalValue::InternalLinkage, init,
364 "llvm.amdgcn.lds.offset.table", nullptr, GlobalValue::NotThreadLocal,
366 }
367
368 void replaceUseWithTableLookup(Module &M, IRBuilder<> &Builder,
369 GlobalVariable *LookupTable,
370 GlobalVariable *GV, Use &U,
371 Value *OptionalIndex) {
372 // Table is a constant array of the same length as OrderedKernels
373 LLVMContext &Ctx = M.getContext();
374 Type *I32 = Type::getInt32Ty(Ctx);
375 auto *I = cast<Instruction>(U.getUser());
376
377 Value *tableKernelIndex = getTableLookupKernelIndex(M, I->getFunction());
378
379 if (auto *Phi = dyn_cast<PHINode>(I)) {
380 BasicBlock *BB = Phi->getIncomingBlock(U);
381 Builder.SetInsertPoint(&(*(BB->getFirstInsertionPt())));
382 } else {
383 Builder.SetInsertPoint(I);
384 }
385
386 SmallVector<Value *, 3> GEPIdx = {
387 ConstantInt::get(I32, 0),
388 tableKernelIndex,
389 };
390 if (OptionalIndex)
391 GEPIdx.push_back(OptionalIndex);
392
393 Value *Address = Builder.CreateInBoundsGEP(
394 LookupTable->getValueType(), LookupTable, GEPIdx, GV->getName());
395
396 Value *Loaded = Builder.CreateLoad(GV->getType(), Address);
397 U.set(Loaded);
398 }
399
400 void replaceUsesInInstructionsWithTableLookup(
401 Module &M, ArrayRef<GlobalVariable *> ModuleScopeVariables,
402 GlobalVariable *LookupTable) {
403
404 LLVMContext &Ctx = M.getContext();
405 IRBuilder<> Builder(Ctx);
406 Type *I32 = Type::getInt32Ty(Ctx);
407
408 for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) {
409 auto *GV = ModuleScopeVariables[Index];
410
411 for (Use &U : make_early_inc_range(GV->uses())) {
412 auto *I = dyn_cast<Instruction>(U.getUser());
413 if (!I)
414 continue;
415
416 replaceUseWithTableLookup(M, Builder, LookupTable, GV, U,
417 ConstantInt::get(I32, Index));
418 }
419 }
420 }
421
422 static DenseSet<Function *> kernelsThatIndirectlyAccessAnyOfPassedVariables(
423 Module &M, GVUsesInfoTy &LDSUsesInfo,
424 DenseSet<GlobalVariable *> const &VariableSet) {
425
426 DenseSet<Function *> KernelSet;
427
428 if (VariableSet.empty())
429 return KernelSet;
430
431 for (Function &Func : M.functions()) {
432 if (Func.isDeclaration() || !isKernel(Func))
433 continue;
434 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[&Func]) {
435 if (VariableSet.contains(GV)) {
436 KernelSet.insert(&Func);
437 break;
438 }
439 }
440 }
441
442 return KernelSet;
443 }
444
445 static GlobalVariable *
446 chooseBestVariableForModuleStrategy(const DataLayout &DL,
447 VariableFunctionMap &LDSVars) {
448 // Find the global variable with the most indirect uses from kernels
449
450 struct CandidateTy {
451 GlobalVariable *GV = nullptr;
452 size_t UserCount = 0;
453 size_t Size = 0;
454
455 CandidateTy() = default;
456
457 CandidateTy(GlobalVariable *GV, uint64_t UserCount, uint64_t AllocSize)
458 : GV(GV), UserCount(UserCount), Size(AllocSize) {}
459
460 bool operator<(const CandidateTy &Other) const {
461 // Fewer users makes module scope variable less attractive
462 if (UserCount < Other.UserCount) {
463 return true;
464 }
465 if (UserCount > Other.UserCount) {
466 return false;
467 }
468
469 // Bigger makes module scope variable less attractive
470 if (Size < Other.Size) {
471 return false;
472 }
473
474 if (Size > Other.Size) {
475 return true;
476 }
477
478 // Arbitrary but consistent
479 return GV->getName() < Other.GV->getName();
480 }
481 };
482
483 CandidateTy MostUsed;
484
485 for (auto &K : LDSVars) {
486 GlobalVariable *GV = K.first;
487 if (K.second.size() <= 1) {
488 // A variable reachable by only one kernel is best lowered with kernel
489 // strategy
490 continue;
491 }
492 CandidateTy Candidate(GV, K.second.size(), GV->getGlobalSize(DL));
493 if (MostUsed < Candidate)
494 MostUsed = Candidate;
495 }
496
497 return MostUsed.GV;
498 }
499
500 static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV,
501 uint32_t Address) {
502 // Write the specified address into metadata where it can be retrieved by
503 // the assembler. Format is a half open range, [Address Address+1)
504 LLVMContext &Ctx = M->getContext();
505 auto *IntTy =
506 M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS);
507 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address));
508 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1));
509 GV->setMetadata(LLVMContext::MD_absolute_symbol,
510 MDNode::get(Ctx, {MinC, MaxC}));
511 }
512
513 DenseMap<Function *, Value *> tableKernelIndexCache;
514 Value *getTableLookupKernelIndex(Module &M, Function *F) {
515 // Accesses from a function use the amdgcn_lds_kernel_id intrinsic which
516 // lowers to a read from a live in register. Emit it once in the entry
517 // block to spare deduplicating it later.
518 auto [It, Inserted] = tableKernelIndexCache.try_emplace(F);
519 if (Inserted) {
520 auto InsertAt = F->getEntryBlock().getFirstNonPHIOrDbgOrAlloca();
521 IRBuilder<> Builder(&*InsertAt);
522
523 It->second = Builder.CreateIntrinsic(Intrinsic::amdgcn_lds_kernel_id, {});
524 }
525
526 return It->second;
527 }
528
529 static std::vector<Function *> assignLDSKernelIDToEachKernel(
530 Module *M, DenseSet<Function *> const &KernelsThatAllocateTableLDS,
531 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS) {
532 // Associate kernels in the set with an arbitrary but reproducible order and
533 // annotate them with that order in metadata. This metadata is recognised by
534 // the backend and lowered to a SGPR which can be read from using
535 // amdgcn_lds_kernel_id.
536
537 std::vector<Function *> OrderedKernels;
538 if (!KernelsThatAllocateTableLDS.empty() ||
539 !KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
540
541 for (Function &Func : M->functions()) {
542 if (Func.isDeclaration())
543 continue;
544 if (!isKernel(Func))
545 continue;
546
547 if (KernelsThatAllocateTableLDS.contains(&Func) ||
548 KernelsThatIndirectlyAllocateDynamicLDS.contains(&Func)) {
549 assert(Func.hasName()); // else fatal error earlier
550 OrderedKernels.push_back(&Func);
551 }
552 }
553
554 // Put them in an arbitrary but reproducible order
555 OrderedKernels = sortByName(std::move(OrderedKernels));
556
557 // Annotate the kernels with their order in this vector
558 LLVMContext &Ctx = M->getContext();
559 IRBuilder<> Builder(Ctx);
560
561 if (OrderedKernels.size() > UINT32_MAX) {
562 // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU
563 reportFatalUsageError("unimplemented LDS lowering for > 2**32 kernels");
564 }
565
566 for (size_t i = 0; i < OrderedKernels.size(); i++) {
567 Metadata *AttrMDArgs[1] = {
568 ConstantAsMetadata::get(Builder.getInt32(i)),
569 };
570 OrderedKernels[i]->setMetadata("llvm.amdgcn.lds.kernel.id",
571 MDNode::get(Ctx, AttrMDArgs));
572 }
573 }
574 return OrderedKernels;
575 }
576
577 static void partitionVariablesIntoIndirectStrategies(
578 Module &M, GVUsesInfoTy const &LDSUsesInfo,
579 VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly,
580 DenseSet<GlobalVariable *> &ModuleScopeVariables,
581 DenseSet<GlobalVariable *> &TableLookupVariables,
582 DenseSet<GlobalVariable *> &KernelAccessVariables,
583 DenseSet<GlobalVariable *> &DynamicVariables) {
584
585 GlobalVariable *HybridModuleRoot =
586 LoweringKindLoc != LoweringKind::hybrid
587 ? nullptr
588 : chooseBestVariableForModuleStrategy(
589 M.getDataLayout(), LDSToKernelsThatNeedToAccessItIndirectly);
590
591 DenseSet<Function *> const EmptySet;
592 DenseSet<Function *> const &HybridModuleRootKernels =
593 HybridModuleRoot
594 ? LDSToKernelsThatNeedToAccessItIndirectly[HybridModuleRoot]
595 : EmptySet;
596
597 for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) {
598 // Each iteration of this loop assigns exactly one global variable to
599 // exactly one of the implementation strategies.
600
601 GlobalVariable *GV = K.first;
603 assert(!K.second.empty());
604
605 if (AMDGPU::isDynamicLDS(*GV)) {
606 DynamicVariables.insert(GV);
607 continue;
608 }
609
610 switch (LoweringKindLoc) {
611 case LoweringKind::module:
612 ModuleScopeVariables.insert(GV);
613 break;
614
615 case LoweringKind::table:
616 TableLookupVariables.insert(GV);
617 break;
618
619 case LoweringKind::kernel:
620 if (K.second.size() == 1) {
621 KernelAccessVariables.insert(GV);
622 } else {
623 // FIXME: This should use DiagnosticInfo
625 "cannot lower LDS '" + GV->getName() +
626 "' to kernel access as it is reachable from multiple kernels");
627 }
628 break;
629
630 case LoweringKind::hybrid: {
631 if (GV == HybridModuleRoot) {
632 assert(K.second.size() != 1);
633 ModuleScopeVariables.insert(GV);
634 } else if (K.second.size() == 1) {
635 KernelAccessVariables.insert(GV);
636 } else if (K.second == HybridModuleRootKernels) {
637 ModuleScopeVariables.insert(GV);
638 } else {
639 TableLookupVariables.insert(GV);
640 }
641 break;
642 }
643 }
644 }
645
646 // All LDS variables accessed indirectly have now been partitioned into
647 // the distinct lowering strategies.
648 assert(ModuleScopeVariables.size() + TableLookupVariables.size() +
649 KernelAccessVariables.size() + DynamicVariables.size() ==
650 LDSToKernelsThatNeedToAccessItIndirectly.size());
651 }
652
653 static GlobalVariable *lowerModuleScopeStructVariables(
654 Module &M, DenseSet<GlobalVariable *> const &ModuleScopeVariables,
655 DenseSet<Function *> const &KernelsThatAllocateModuleLDS) {
656 // Create a struct to hold the ModuleScopeVariables
657 // Replace all uses of those variables from non-kernel functions with the
658 // new struct instance Replace only the uses from kernel functions that will
659 // allocate this instance. That is a space optimisation - kernels that use a
660 // subset of the module scope struct and do not need to allocate it for
661 // indirect calls will only allocate the subset they use (they do so as part
662 // of the per-kernel lowering).
663 if (ModuleScopeVariables.empty()) {
664 return nullptr;
665 }
666
667 LLVMContext &Ctx = M.getContext();
668
669 LDSVariableReplacement ModuleScopeReplacement =
670 createLDSVariableReplacement(M, "llvm.amdgcn.module.lds",
671 ModuleScopeVariables);
672
673 appendToCompilerUsed(M, {static_cast<GlobalValue *>(
675 cast<Constant>(ModuleScopeReplacement.SGV),
676 PointerType::getUnqual(Ctx)))});
677
678 // module.lds will be allocated at zero in any kernel that allocates it
679 recordLDSAbsoluteAddress(&M, ModuleScopeReplacement.SGV, 0);
680
681 // historic
682 removeLocalVarsFromUsedLists(M, ModuleScopeVariables);
683
684 // Replace all uses of module scope variable from non-kernel functions
685 replaceLDSVariablesWithStruct(
686 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
687 Instruction *I = dyn_cast<Instruction>(U.getUser());
688 if (!I) {
689 return false;
690 }
691 Function *F = I->getFunction();
692 return !isKernel(*F);
693 });
694
695 // Replace uses of module scope variable from kernel functions that
696 // allocate the module scope variable, otherwise leave them unchanged
697 // Record on each kernel whether the module scope global is used by it
698
699 for (Function &Func : M.functions()) {
700 if (Func.isDeclaration() || !isKernel(Func))
701 continue;
702
703 if (KernelsThatAllocateModuleLDS.contains(&Func)) {
704 replaceLDSVariablesWithStruct(
705 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
706 Instruction *I = dyn_cast<Instruction>(U.getUser());
707 if (!I) {
708 return false;
709 }
710 Function *F = I->getFunction();
711 return F == &Func;
712 });
713
714 markUsedByKernel(&Func, ModuleScopeReplacement.SGV);
715 }
716 }
717
718 return ModuleScopeReplacement.SGV;
719 }
720
722 lowerKernelScopeStructVariables(
723 Module &M, GVUsesInfoTy &LDSUsesInfo,
724 DenseSet<GlobalVariable *> const &ModuleScopeVariables,
725 DenseSet<Function *> const &KernelsThatAllocateModuleLDS,
726 GlobalVariable *MaybeModuleScopeStruct) {
727
728 // Create a struct for each kernel for the non-module-scope variables.
729
731 for (Function &Func : M.functions()) {
732 if (Func.isDeclaration() || !isKernel(Func))
733 continue;
734
735 DenseSet<GlobalVariable *> KernelUsedVariables;
736 // Allocating variables that are used directly in this struct to get
737 // alignment aware allocation and predictable frame size.
738 for (auto &v : LDSUsesInfo.DirectAccess[&Func]) {
739 if (!AMDGPU::isDynamicLDS(*v)) {
740 KernelUsedVariables.insert(v);
741 }
742 }
743
744 // Allocating variables that are accessed indirectly so that a lookup of
745 // this struct instance can find them from nested functions.
746 for (auto &v : LDSUsesInfo.IndirectAccess[&Func]) {
747 if (!AMDGPU::isDynamicLDS(*v)) {
748 KernelUsedVariables.insert(v);
749 }
750 }
751
752 // Variables allocated in module lds must all resolve to that struct,
753 // not to the per-kernel instance.
754 if (KernelsThatAllocateModuleLDS.contains(&Func)) {
755 for (GlobalVariable *v : ModuleScopeVariables) {
756 KernelUsedVariables.erase(v);
757 }
758 }
759
760 if (KernelUsedVariables.empty()) {
761 // Either used no LDS, or the LDS it used was all in the module struct
762 // or dynamically sized
763 continue;
764 }
765
766 // The association between kernel function and LDS struct is done by
767 // symbol name, which only works if the function in question has a
768 // name This is not expected to be a problem in practice as kernels
769 // are called by name making anonymous ones (which are named by the
770 // backend) difficult to use. This does mean that llvm test cases need
771 // to name the kernels.
772 if (!Func.hasName()) {
773 reportFatalUsageError("anonymous kernels cannot use LDS variables");
774 }
775
776 std::string VarName =
777 (Twine("llvm.amdgcn.kernel.") + Func.getName() + ".lds").str();
778
779 auto Replacement =
780 createLDSVariableReplacement(M, VarName, KernelUsedVariables);
781
782 // If any indirect uses, create a direct use to ensure allocation
783 // TODO: Simpler to unconditionally mark used but that regresses
784 // codegen in test/CodeGen/AMDGPU/noclobber-barrier.ll
785 auto Accesses = LDSUsesInfo.IndirectAccess.find(&Func);
786 if ((Accesses != LDSUsesInfo.IndirectAccess.end()) &&
787 !Accesses->second.empty())
788 markUsedByKernel(&Func, Replacement.SGV);
789
790 // remove preserves existing codegen
791 removeLocalVarsFromUsedLists(M, KernelUsedVariables);
792 KernelToReplacement[&Func] = Replacement;
793
794 // Rewrite uses within kernel to the new struct
795 replaceLDSVariablesWithStruct(
796 M, KernelUsedVariables, Replacement, [&Func](Use &U) {
797 Instruction *I = dyn_cast<Instruction>(U.getUser());
798 return I && I->getFunction() == &Func;
799 });
800 }
801 return KernelToReplacement;
802 }
803
804 static GlobalVariable *
805 buildRepresentativeDynamicLDSInstance(Module &M, GVUsesInfoTy &LDSUsesInfo,
806 Function *func) {
807 // Create a dynamic lds variable with a name associated with the passed
808 // function that has the maximum alignment of any dynamic lds variable
809 // reachable from this kernel. Dynamic LDS is allocated after the static LDS
810 // allocation, possibly after alignment padding. The representative variable
811 // created here has the maximum alignment of any other dynamic variable
812 // reachable by that kernel. All dynamic LDS variables are allocated at the
813 // same address in each kernel in order to provide the documented aliasing
814 // semantics. Setting the alignment here allows this IR pass to accurately
815 // predict the exact constant at which it will be allocated.
816
817 assert(isKernel(*func));
818
819 LLVMContext &Ctx = M.getContext();
820 const DataLayout &DL = M.getDataLayout();
821 Align MaxDynamicAlignment(1);
822
823 auto UpdateMaxAlignment = [&MaxDynamicAlignment, &DL](GlobalVariable *GV) {
824 if (AMDGPU::isDynamicLDS(*GV)) {
825 MaxDynamicAlignment =
826 std::max(MaxDynamicAlignment, AMDGPU::getAlign(DL, GV));
827 }
828 };
829
830 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[func]) {
831 UpdateMaxAlignment(GV);
832 }
833
834 for (GlobalVariable *GV : LDSUsesInfo.DirectAccess[func]) {
835 UpdateMaxAlignment(GV);
836 }
837
838 assert(func->hasName()); // Checked by caller
839 auto *emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0);
841 M, emptyCharArray, false, GlobalValue::ExternalLinkage, nullptr,
842 Twine("llvm.amdgcn." + func->getName() + ".dynlds"), nullptr,
844 N->setAlignment(MaxDynamicAlignment);
845
847 return N;
848 }
849
850 DenseMap<Function *, GlobalVariable *> lowerDynamicLDSVariables(
851 Module &M, GVUsesInfoTy &LDSUsesInfo,
852 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS,
853 DenseSet<GlobalVariable *> const &DynamicVariables,
854 std::vector<Function *> const &OrderedKernels) {
855 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS;
856 if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
857 LLVMContext &Ctx = M.getContext();
858 IRBuilder<> Builder(Ctx);
860
861 std::vector<Constant *> newDynamicLDS;
862
863 // Table is built in the same order as OrderedKernels
864 for (auto &func : OrderedKernels) {
865
866 if (KernelsThatIndirectlyAllocateDynamicLDS.contains(func)) {
867 assert(isKernel(*func));
868 if (!func->hasName()) {
869 reportFatalUsageError("anonymous kernels cannot use LDS variables");
870 }
871
873 buildRepresentativeDynamicLDSInstance(M, LDSUsesInfo, func);
874
875 KernelToCreatedDynamicLDS[func] = N;
876
877 markUsedByKernel(func, N);
878
879 newDynamicLDS.push_back(N);
880 } else {
881 newDynamicLDS.push_back(PoisonValue::get(LocalPtrTy));
882 }
883 }
884 assert(OrderedKernels.size() == newDynamicLDS.size());
885
886 ArrayType *t = ArrayType::get(LocalPtrTy, newDynamicLDS.size());
887 Constant *init = ConstantArray::get(t, newDynamicLDS);
888 GlobalVariable *table = new GlobalVariable(
889 M, t, true, GlobalValue::InternalLinkage, init,
890 "llvm.amdgcn.dynlds.offset.table", nullptr,
892
893 for (GlobalVariable *GV : DynamicVariables) {
894 for (Use &U : make_early_inc_range(GV->uses())) {
895 auto *I = dyn_cast<Instruction>(U.getUser());
896 if (!I)
897 continue;
898 if (isKernel(*I->getFunction()))
899 continue;
900
901 replaceUseWithTableLookup(M, Builder, table, GV, U, nullptr);
902 }
903 }
904 }
905 return KernelToCreatedDynamicLDS;
906 }
907
908 // Per-TU mode for link-time LDS resolution. Instead of computing a global
909 // layout, create per-function LDS struct declarations so the linker can
910 // assign offsets across TUs.
911 bool runOnModuleLinkTime(Module &M) {
912 bool Changed = superAlignLDSGlobals(M);
913 Changed |=
915
916 CallGraph CG(M);
917 FunctionVariableMap KernelLDSUses, FunctionLDSUses;
918 getUsesOfGVByFunction(CG, M, isLDSVariableToLower, KernelLDSUses,
919 FunctionLDSUses);
920
921 if (KernelLDSUses.empty() && FunctionLDSUses.empty())
922 return Changed;
923
924 std::string ModuleId = getUniqueModuleId(&M);
925 assert(!ModuleId.empty() &&
926 "modules with LDS variables should have a unique ID");
927
928 FunctionVariableMap AllLDSUses;
929 for (auto &[F, Vars] : KernelLDSUses)
930 AllLDSUses[F].insert(Vars.begin(), Vars.end());
931 for (auto &[F, Vars] : FunctionLDSUses)
932 AllLDSUses[F].insert(Vars.begin(), Vars.end());
933
934 // Named barriers are handled by AMDGPULowerExecSync; filter them out.
935 for (auto &[F, Vars] : AllLDSUses) {
937 for (GlobalVariable *V : Vars)
939 Barriers.push_back(V);
940 for (GlobalVariable *V : Barriers)
941 Vars.erase(V);
942 }
943
944 // Build reverse map: LDS variable -> functions that use it.
946 for (auto &[F, Vars] : AllLDSUses) {
947 for (GlobalVariable *V : Vars)
948 VarToFuncs[V].push_back(F);
949 }
950
951 // A variable is function-scope iff it has local linkage and exactly one
952 // user function. Everything else is global-scope and must remain as a
953 // standalone external declaration so the linker can assign a single shared
954 // offset.
955 DenseSet<GlobalVariable *> GlobalScopeVars;
956 DenseSet<GlobalVariable *> InternalMultiUserVars;
957 for (auto &[V, Funcs] : VarToFuncs) {
958 if (!V->hasLocalLinkage() || Funcs.size() > 1) {
959 GlobalScopeVars.insert(V);
960 if (V->hasLocalLinkage())
961 InternalMultiUserVars.insert(V);
962 }
963 }
964
965 // Wrap function-scope LDS into per-function structs (unchanged logic,
966 // but global-scope variables are excluded from the set).
968 DenseSet<GlobalVariable *> AllReplacedVars;
969 for (auto &KV : AllLDSUses) {
970 Function *F = KV.first;
971 DenseSet<GlobalVariable *> FuncScopeVars;
972 for (GlobalVariable *V : KV.second) {
973 if (!GlobalScopeVars.count(V))
974 FuncScopeVars.insert(V);
975 }
976
977 if (FuncScopeVars.empty())
978 continue;
979
980 std::string StructName =
981 F->hasLocalLinkage()
982 ? ("__amdgpu_lds." + F->getName() + ModuleId).str()
983 : ("__amdgpu_lds." + F->getName()).str();
984 LDSVariableReplacement Replacement =
985 createLDSVariableReplacement(M, StructName, FuncScopeVars);
986
987 GlobalVariable *SGV = Replacement.SGV;
989 SGV->setInitializer(nullptr);
990 FuncToLdsStruct.push_back({F, SGV});
991
992 replaceLDSVariablesWithStruct(
993 M, FuncScopeVars, Replacement, [F](const Use &U) {
994 auto *I = dyn_cast<Instruction>(U.getUser());
995 return I && I->getFunction() == F;
996 });
997
998 AllReplacedVars.insert(FuncScopeVars.begin(), FuncScopeVars.end());
999 }
1000
1001 // Internal-linkage LDS variables used by multiple functions would collide
1002 // across TUs if promoted individually to external linkage (same name in
1003 // different TUs). Pack them into a single per-module struct with a
1004 // module-unique name so the linker treats them as one allocation unit.
1005 if (!InternalMultiUserVars.empty()) {
1006 std::string StructName = "__amdgpu_lds.__internal" + ModuleId;
1007 LDSVariableReplacement Replacement =
1008 createLDSVariableReplacement(M, StructName, InternalMultiUserVars);
1009
1010 GlobalVariable *SGV = Replacement.SGV;
1012 SGV->setInitializer(nullptr);
1013
1014 replaceLDSVariablesWithStruct(
1015 M, InternalMultiUserVars, Replacement,
1016 [](const Use &U) { return isa<Instruction>(U.getUser()); });
1017
1018 DenseSet<Function *> FuncsUsingInternalVars;
1019 for (GlobalVariable *V : InternalMultiUserVars) {
1020 for (Function *F : VarToFuncs[V])
1021 FuncsUsingInternalVars.insert(F);
1022 }
1023 for (Function *F : FuncsUsingInternalVars)
1024 FuncToLdsStruct.push_back({F, SGV});
1025
1026 AllReplacedVars.insert(InternalMultiUserVars.begin(),
1027 InternalMultiUserVars.end());
1028 }
1029
1030 // Convert global-scope LDS to external declarations. Their uses remain
1031 // intact and ISel generates R_AMDGPU_ABS32_LO relocations for them.
1032 for (GlobalVariable *V : GlobalScopeVars) {
1033 V->setInitializer(nullptr);
1034 V->setLinkage(GlobalValue::ExternalLinkage);
1035 }
1036
1037 // Emit amdgpu.lds.uses metadata for struct and global-scope LDS.
1038 {
1039 LLVMContext &Ctx = M.getContext();
1040 NamedMDNode *LdsMD = M.getOrInsertNamedMetadata("amdgpu.lds.uses");
1041
1042 for (auto &[F, SGV] : FuncToLdsStruct)
1043 LdsMD->addOperand(MDNode::get(
1045
1046 for (auto &[V, Funcs] : VarToFuncs) {
1047 if (GlobalScopeVars.count(V) && !InternalMultiUserVars.count(V)) {
1048 for (Function *F : Funcs) {
1049 LdsMD->addOperand(MDNode::get(
1051 }
1052 }
1053 }
1054 }
1055
1056 DenseSet<GlobalVariable *> AllLDSVarsForCleanup = AllReplacedVars;
1057 AllLDSVarsForCleanup.insert(GlobalScopeVars.begin(), GlobalScopeVars.end());
1058 removeLocalVarsFromUsedLists(M, AllLDSVarsForCleanup);
1059 for (GlobalVariable *GV : AllReplacedVars) {
1061 if (GV->use_empty())
1062 GV->eraseFromParent();
1063 }
1064
1065 return true;
1066 }
1067
1068 bool runOnModule(Module &M) {
1070 return runOnModuleLinkTime(M);
1071 return runOnModuleNormal(M);
1072 }
1073
1074 bool runOnModuleNormal(Module &M) {
1075 bool Changed = superAlignLDSGlobals(M);
1076
1077 Changed |= any_of(M.globals(), isNotYetLoweredLDSVariable);
1078
1079 CallGraph CG(M);
1080
1082 isNotYetLoweredLDSVariable);
1083
1084 // For each kernel, what variables does it access directly or through
1085 // callees
1087
1088 // For each variable accessed through callees, which kernels access it
1089 VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly;
1090 for (auto &K : LDSUsesInfo.IndirectAccess) {
1091 Function *F = K.first;
1092 assert(isKernel(*F));
1093 for (GlobalVariable *GV : K.second) {
1094 LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(F);
1095 }
1096 }
1097
1098 // Partition variables accessed indirectly into the different strategies
1099 DenseSet<GlobalVariable *> ModuleScopeVariables;
1100 DenseSet<GlobalVariable *> TableLookupVariables;
1101 DenseSet<GlobalVariable *> KernelAccessVariables;
1102 DenseSet<GlobalVariable *> DynamicVariables;
1103 partitionVariablesIntoIndirectStrategies(
1104 M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly,
1105 ModuleScopeVariables, TableLookupVariables, KernelAccessVariables,
1106 DynamicVariables);
1107
1108 // If the kernel accesses a variable that is going to be stored in the
1109 // module instance through a call then that kernel needs to allocate the
1110 // module instance
1111 const DenseSet<Function *> KernelsThatAllocateModuleLDS =
1112 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1113 ModuleScopeVariables);
1114 const DenseSet<Function *> KernelsThatAllocateTableLDS =
1115 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1116 TableLookupVariables);
1117
1118 const DenseSet<Function *> KernelsThatIndirectlyAllocateDynamicLDS =
1119 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1120 DynamicVariables);
1121
1122 GlobalVariable *MaybeModuleScopeStruct = lowerModuleScopeStructVariables(
1123 M, ModuleScopeVariables, KernelsThatAllocateModuleLDS);
1124
1126 lowerKernelScopeStructVariables(M, LDSUsesInfo, ModuleScopeVariables,
1127 KernelsThatAllocateModuleLDS,
1128 MaybeModuleScopeStruct);
1129
1130 // Lower zero cost accesses to the kernel instances just created
1131 for (auto &GV : KernelAccessVariables) {
1132 auto &funcs = LDSToKernelsThatNeedToAccessItIndirectly[GV];
1133 assert(funcs.size() == 1); // Only one kernel can access it
1134 LDSVariableReplacement Replacement =
1135 KernelToReplacement[*(funcs.begin())];
1136
1138 Vec.insert(GV);
1139
1140 replaceLDSVariablesWithStruct(M, Vec, Replacement, [](Use &U) {
1141 return isa<Instruction>(U.getUser());
1142 });
1143 }
1144
1145 // The ith element of this vector is kernel id i
1146 std::vector<Function *> OrderedKernels =
1147 assignLDSKernelIDToEachKernel(&M, KernelsThatAllocateTableLDS,
1148 KernelsThatIndirectlyAllocateDynamicLDS);
1149
1150 if (!KernelsThatAllocateTableLDS.empty()) {
1151 LLVMContext &Ctx = M.getContext();
1152 IRBuilder<> Builder(Ctx);
1153
1154 // The order must be consistent between lookup table and accesses to
1155 // lookup table
1156 auto TableLookupVariablesOrdered =
1157 sortByName(std::vector<GlobalVariable *>(TableLookupVariables.begin(),
1158 TableLookupVariables.end()));
1159
1160 GlobalVariable *LookupTable = buildLookupTable(
1161 M, TableLookupVariablesOrdered, OrderedKernels, KernelToReplacement);
1162 replaceUsesInInstructionsWithTableLookup(M, TableLookupVariablesOrdered,
1163 LookupTable);
1164 }
1165
1166 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS =
1167 lowerDynamicLDSVariables(M, LDSUsesInfo,
1168 KernelsThatIndirectlyAllocateDynamicLDS,
1169 DynamicVariables, OrderedKernels);
1170
1171 // Strip amdgpu-no-lds-kernel-id from all functions reachable from the
1172 // kernel. We may have inferred this wasn't used prior to the pass.
1173 // TODO: We could filter out subgraphs that do not access LDS globals.
1174 for (auto *KernelSet : {&KernelsThatIndirectlyAllocateDynamicLDS,
1175 &KernelsThatAllocateTableLDS})
1176 for (Function *F : *KernelSet)
1177 removeFnAttrFromReachable(CG, F, {"amdgpu-no-lds-kernel-id"});
1178
1179 // All kernel frames have been allocated. Calculate and record the
1180 // addresses.
1181 {
1182 const DataLayout &DL = M.getDataLayout();
1183
1184 for (Function &Func : M.functions()) {
1185 if (Func.isDeclaration() || !isKernel(Func))
1186 continue;
1187
1188 // All three of these are optional. The first variable is allocated at
1189 // zero. They are allocated by AMDGPUMachineFunctionInfo as one block.
1190 // Layout:
1191 //{
1192 // module.lds
1193 // alignment padding
1194 // kernel instance
1195 // alignment padding
1196 // dynamic lds variables
1197 //}
1198
1199 const bool AllocateModuleScopeStruct =
1200 MaybeModuleScopeStruct &&
1201 KernelsThatAllocateModuleLDS.contains(&Func);
1202
1203 auto Replacement = KernelToReplacement.find(&Func);
1204 const bool AllocateKernelScopeStruct =
1205 Replacement != KernelToReplacement.end();
1206
1207 const bool AllocateDynamicVariable =
1208 KernelToCreatedDynamicLDS.contains(&Func);
1209
1210 uint32_t Offset = 0;
1211
1212 if (AllocateModuleScopeStruct) {
1213 // Allocated at zero, recorded once on construction, not once per
1214 // kernel
1215 Offset += MaybeModuleScopeStruct->getGlobalSize(DL);
1216 }
1217
1218 if (AllocateKernelScopeStruct) {
1219 GlobalVariable *KernelStruct = Replacement->second.SGV;
1220 Offset = alignTo(Offset, AMDGPU::getAlign(DL, KernelStruct));
1221 recordLDSAbsoluteAddress(&M, KernelStruct, Offset);
1222 Offset += KernelStruct->getGlobalSize(DL);
1223 }
1224
1225 // If there is dynamic allocation, the alignment needed is included in
1226 // the static frame size. There may be no reference to the dynamic
1227 // variable in the kernel itself, so without including it here, that
1228 // alignment padding could be missed.
1229 if (AllocateDynamicVariable) {
1230 GlobalVariable *DynamicVariable = KernelToCreatedDynamicLDS[&Func];
1231 Offset = alignTo(Offset, AMDGPU::getAlign(DL, DynamicVariable));
1232 recordLDSAbsoluteAddress(&M, DynamicVariable, Offset);
1233 }
1234
1235 if (Offset != 0) {
1236 (void)TM; // TODO: Account for target maximum LDS
1237 std::string Buffer;
1238 raw_string_ostream SS{Buffer};
1239 SS << format("%u", Offset);
1240
1241 // Instead of explicitly marking kernels that access dynamic variables
1242 // using special case metadata, annotate with min-lds == max-lds, i.e.
1243 // that there is no more space available for allocating more static
1244 // LDS variables. That is the right condition to prevent allocating
1245 // more variables which would collide with the addresses assigned to
1246 // dynamic variables.
1247 if (AllocateDynamicVariable)
1248 SS << format(",%u", Offset);
1249
1250 Func.addFnAttr("amdgpu-lds-size", Buffer);
1251 }
1252 }
1253 }
1254
1255 for (auto &GV : make_early_inc_range(M.globals()))
1256 if (isNotYetLoweredLDSVariable(GV)) {
1257 // probably want to remove from used lists
1259 if (GV.use_empty())
1260 GV.eraseFromParent();
1261 }
1262
1263 return Changed;
1264 }
1265
1266private:
1267 // An absolute address means a previous run already placed the variable.
1268 static bool isNotYetLoweredLDSVariable(const GlobalVariable &GV) {
1269 return isLDSVariableToLower(GV) && !GV.isAbsoluteSymbolRef();
1270 }
1271
1272 // Increase the alignment of LDS globals if necessary to maximise the chance
1273 // that we can use aligned LDS instructions to access them.
1274 static bool superAlignLDSGlobals(Module &M) {
1275 const DataLayout &DL = M.getDataLayout();
1276 bool Changed = false;
1277 if (!SuperAlignLDSGlobals) {
1278 return Changed;
1279 }
1280
1281 for (auto &GV : M.globals()) {
1283 // Only changing alignment of LDS variables
1284 continue;
1285 }
1286 if (!GV.hasInitializer()) {
1287 // cuda/hip extern __shared__ variable, leave alignment alone
1288 continue;
1289 }
1290
1291 if (GV.isAbsoluteSymbolRef()) {
1292 // If the variable is already allocated, don't change the alignment
1293 continue;
1294 }
1295
1296 Align Alignment = AMDGPU::getAlign(DL, &GV);
1297 uint64_t GVSize = GV.getGlobalSize(DL);
1298
1299 if (GVSize > 8) {
1300 // We might want to use a b96 or b128 load/store
1301 Alignment = std::max(Alignment, Align(16));
1302 } else if (GVSize > 4) {
1303 // We might want to use a b64 load/store
1304 Alignment = std::max(Alignment, Align(8));
1305 } else if (GVSize > 2) {
1306 // We might want to use a b32 load/store
1307 Alignment = std::max(Alignment, Align(4));
1308 } else if (GVSize > 1) {
1309 // We might want to use a b16 load/store
1310 Alignment = std::max(Alignment, Align(2));
1311 }
1312
1313 if (Alignment != AMDGPU::getAlign(DL, &GV)) {
1314 Changed = true;
1315 GV.setAlignment(Alignment);
1316 }
1317 }
1318 return Changed;
1319 }
1320
1321 static LDSVariableReplacement createLDSVariableReplacement(
1322 Module &M, std::string VarName,
1323 DenseSet<GlobalVariable *> const &LDSVarsToTransform) {
1324 // Create a struct instance containing LDSVarsToTransform and map from those
1325 // variables to ConstantExprGEP
1326 // Variables may be introduced to meet alignment requirements. No aliasing
1327 // metadata is useful for these as they have no uses. Erased before return.
1328
1329 LLVMContext &Ctx = M.getContext();
1330 const DataLayout &DL = M.getDataLayout();
1331 assert(!LDSVarsToTransform.empty());
1332
1334 LayoutFields.reserve(LDSVarsToTransform.size());
1335 {
1336 // The order of fields in this struct depends on the order of
1337 // variables in the argument which varies when changing how they
1338 // are identified, leading to spurious test breakage.
1339 auto Sorted = sortByName(std::vector<GlobalVariable *>(
1340 LDSVarsToTransform.begin(), LDSVarsToTransform.end()));
1341
1342 for (GlobalVariable *GV : Sorted) {
1344 AMDGPU::getAlign(DL, GV));
1345 LayoutFields.emplace_back(F);
1346 }
1347 }
1348
1349 performOptimizedStructLayout(LayoutFields);
1350
1351 std::vector<GlobalVariable *> LocalVars;
1352 BitVector IsPaddingField;
1353 LocalVars.reserve(LDSVarsToTransform.size()); // will be at least this large
1354 IsPaddingField.reserve(LDSVarsToTransform.size());
1355 {
1356 uint64_t CurrentOffset = 0;
1357 for (auto &F : LayoutFields) {
1358 GlobalVariable *FGV =
1359 static_cast<GlobalVariable *>(const_cast<void *>(F.Id));
1360 Align DataAlign = F.Alignment;
1361
1362 uint64_t DataAlignV = DataAlign.value();
1363 if (uint64_t Rem = CurrentOffset % DataAlignV) {
1364 uint64_t Padding = DataAlignV - Rem;
1365
1366 // Append an array of padding bytes to meet alignment requested
1367 // Note (o + (a - (o % a)) ) % a == 0
1368 // (offset + Padding ) % align == 0
1369
1370 Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding);
1371 LocalVars.push_back(new GlobalVariable(
1372 M, ATy, false, GlobalValue::InternalLinkage,
1374 AMDGPUAS::LOCAL_ADDRESS, false));
1375 IsPaddingField.push_back(true);
1376 CurrentOffset += Padding;
1377 }
1378
1379 LocalVars.push_back(FGV);
1380 IsPaddingField.push_back(false);
1381 CurrentOffset += F.Size;
1382 }
1383 }
1384
1385 std::vector<Type *> LocalVarTypes;
1386 LocalVarTypes.reserve(LocalVars.size());
1387 std::transform(
1388 LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes),
1389 [](const GlobalVariable *V) -> Type * { return V->getValueType(); });
1390
1391 StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t");
1392
1393 Align StructAlign = AMDGPU::getAlign(DL, LocalVars[0]);
1394
1395 GlobalVariable *SGV = new GlobalVariable(
1396 M, LDSTy, false, GlobalValue::InternalLinkage, PoisonValue::get(LDSTy),
1398 false);
1399 SGV->setAlignment(StructAlign);
1400
1402 Type *I32 = Type::getInt32Ty(Ctx);
1403 for (size_t I = 0; I < LocalVars.size(); I++) {
1404 GlobalVariable *GV = LocalVars[I];
1405 Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)};
1406 Constant *GEP = ConstantExpr::getGetElementPtr(LDSTy, SGV, GEPIdx, true);
1407 if (IsPaddingField[I]) {
1408 assert(GV->use_empty());
1409 GV->eraseFromParent();
1410 } else {
1411 Map[GV] = GEP;
1412 }
1413 }
1414 assert(Map.size() == LDSVarsToTransform.size());
1415 return {SGV, std::move(Map)};
1416 }
1417
1418 template <typename PredicateTy>
1419 static void replaceLDSVariablesWithStruct(
1420 Module &M, DenseSet<GlobalVariable *> const &LDSVarsToTransformArg,
1421 const LDSVariableReplacement &Replacement, PredicateTy Predicate) {
1422 LLVMContext &Ctx = M.getContext();
1423 const DataLayout &DL = M.getDataLayout();
1424
1425 // A hack... we need to insert the aliasing info in a predictable order for
1426 // lit tests. Would like to have them in a stable order already, ideally the
1427 // same order they get allocated, which might mean an ordered set container
1428 auto LDSVarsToTransform = sortByName(std::vector<GlobalVariable *>(
1429 LDSVarsToTransformArg.begin(), LDSVarsToTransformArg.end()));
1430
1431 // Create alias.scope and their lists. Each field in the new structure
1432 // does not alias with all other fields.
1433 SmallVector<MDNode *> AliasScopes;
1434 SmallVector<Metadata *> NoAliasList;
1435 const size_t NumberVars = LDSVarsToTransform.size();
1436 if (NumberVars > 1) {
1437 MDBuilder MDB(Ctx);
1438 AliasScopes.reserve(NumberVars);
1440 for (size_t I = 0; I < NumberVars; I++) {
1442 AliasScopes.push_back(Scope);
1443 }
1444 NoAliasList.append(&AliasScopes[1], AliasScopes.end());
1445 }
1446
1447 // Replace uses of ith variable with a constantexpr to the corresponding
1448 // field of the instance that will be allocated by AMDGPUMachineFunctionInfo
1449 for (size_t I = 0; I < NumberVars; I++) {
1450 GlobalVariable *GV = LDSVarsToTransform[I];
1451 Constant *GEP = Replacement.LDSVarsToConstantGEP.at(GV);
1452
1454
1455 APInt APOff(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1456 GEP->stripAndAccumulateInBoundsConstantOffsets(DL, APOff);
1457 uint64_t Offset = APOff.getZExtValue();
1458
1459 Align A =
1460 commonAlignment(Replacement.SGV->getAlign().valueOrOne(), Offset);
1461
1462 if (I)
1463 NoAliasList[I - 1] = AliasScopes[I - 1];
1464 MDNode *NoAlias =
1465 NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList);
1466 MDNode *AliasScope =
1467 AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]});
1468
1469 refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias);
1470 }
1471 }
1472
1473 static void refineUsesAlignmentAndAA(Value *Ptr, Align A,
1474 const DataLayout &DL, MDNode *AliasScope,
1475 MDNode *NoAlias, unsigned MaxDepth = 5) {
1476 if (!MaxDepth || (A == 1 && !AliasScope))
1477 return;
1478
1479 ScopedNoAliasAAResult ScopedNoAlias;
1480
1481 for (User *U : Ptr->users()) {
1482 if (auto *I = dyn_cast<Instruction>(U)) {
1483 if (AliasScope && I->mayReadOrWriteMemory()) {
1484 MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope);
1485 AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope)
1486 : AliasScope);
1487 I->setMetadata(LLVMContext::MD_alias_scope, AS);
1488
1489 MDNode *NA = I->getMetadata(LLVMContext::MD_noalias);
1490
1491 // Scoped aliases can originate from two different domains.
1492 // First domain would be from LDS domain (created by this pass).
1493 // All entries (LDS vars) into LDS struct will have same domain.
1494
1495 // Second domain could be existing scoped aliases that are the
1496 // results of noalias params and subsequent optimizations that
1497 // may alter thesse sets.
1498
1499 // We need to be careful how we create new alias sets, and
1500 // have right scopes and domains for loads/stores of these new
1501 // LDS variables. We intersect NoAlias set if alias sets belong
1502 // to the same domain. This is the case if we have memcpy using
1503 // LDS variables. Both src and dst of memcpy would belong to
1504 // LDS struct, they donot alias.
1505 // On the other hand, if one of the domains is LDS and other is
1506 // existing domain prior to LDS, we need to have a union of all
1507 // these aliases set to preserve existing aliasing information.
1508
1509 SmallPtrSet<const MDNode *, 16> ExistingDomains, LDSDomains;
1510 ScopedNoAlias.collectScopedDomains(NA, ExistingDomains);
1511 ScopedNoAlias.collectScopedDomains(NoAlias, LDSDomains);
1512 auto Intersection = set_intersection(ExistingDomains, LDSDomains);
1513 if (Intersection.empty()) {
1514 NA = NA ? MDNode::concatenate(NA, NoAlias) : NoAlias;
1515 } else {
1516 NA = NA ? MDNode::intersect(NA, NoAlias) : NoAlias;
1517 }
1518 I->setMetadata(LLVMContext::MD_noalias, NA);
1519 }
1520 }
1521
1522 if (auto *LI = dyn_cast<LoadInst>(U)) {
1523 LI->setAlignment(std::max(A, LI->getAlign()));
1524 continue;
1525 }
1526 if (auto *SI = dyn_cast<StoreInst>(U)) {
1527 if (SI->getPointerOperand() == Ptr)
1528 SI->setAlignment(std::max(A, SI->getAlign()));
1529 continue;
1530 }
1531 if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
1532 // None of atomicrmw operations can work on pointers, but let's
1533 // check it anyway in case it will or we will process ConstantExpr.
1534 if (AI->getPointerOperand() == Ptr)
1535 AI->setAlignment(std::max(A, AI->getAlign()));
1536 continue;
1537 }
1538 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) {
1539 if (AI->getPointerOperand() == Ptr)
1540 AI->setAlignment(std::max(A, AI->getAlign()));
1541 continue;
1542 }
1543 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
1544 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1545 APInt Off(BitWidth, 0);
1546 if (GEP->getPointerOperand() == Ptr) {
1547 Align GA;
1548 if (GEP->accumulateConstantOffset(DL, Off))
1549 GA = commonAlignment(A, Off.getLimitedValue());
1550 refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias,
1551 MaxDepth - 1);
1552 }
1553 continue;
1554 }
1555 if (auto *I = dyn_cast<Instruction>(U)) {
1556 if (I->getOpcode() == Instruction::BitCast ||
1557 I->getOpcode() == Instruction::AddrSpaceCast)
1558 refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1);
1559 }
1560 }
1561 }
1562};
1563
1564class AMDGPULowerModuleLDSLegacy : public ModulePass {
1565public:
1566 const AMDGPUTargetMachine *TM;
1567 static char ID;
1568
1569 AMDGPULowerModuleLDSLegacy(const AMDGPUTargetMachine *TM = nullptr)
1570 : ModulePass(ID), TM(TM) {}
1571
1572 void getAnalysisUsage(AnalysisUsage &AU) const override {
1573 if (!TM)
1575 }
1576
1577 bool runOnModule(Module &M) override {
1578 if (!TM) {
1579 auto &TPC = getAnalysis<TargetPassConfig>();
1580 TM = &TPC.getTM<AMDGPUTargetMachine>();
1581 }
1582
1583 return AMDGPULowerModuleLDS(*TM).runOnModule(M);
1584 }
1585};
1586
1587} // namespace
1588char AMDGPULowerModuleLDSLegacy::ID = 0;
1589
1590char &llvm::AMDGPULowerModuleLDSLegacyPassID = AMDGPULowerModuleLDSLegacy::ID;
1591
1592INITIALIZE_PASS_BEGIN(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1593 "Lower uses of LDS variables from non-kernel functions",
1594 false, false)
1596INITIALIZE_PASS_END(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1597 "Lower uses of LDS variables from non-kernel functions",
1599
1600ModulePass *
1602 return new AMDGPULowerModuleLDSLegacy(TM);
1603}
1604
1607 return AMDGPULowerModuleLDS(TM).runOnModule(M) ? PreservedAnalyses::none()
1609}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
#define DEBUG_TYPE
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
const std::string FatArchTraits< MachO::fat_arch >::StructName
This file provides an interface for laying out a sequence of fields as a struct in a way that attempt...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains some templates that are useful if you are working with the STL at all.
This is the interface for a metadata-based scoped no-alias analysis.
This file defines generic set operations that may be used on set's of different types,...
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void reserve(unsigned N)
Reserve space for atleast N bits in the bitvector.
Definition BitVector.h:363
void push_back(bool Val)
Definition BitVector.h:505
The basic data container for the call graph of a Module of IR.
Definition CallGraph.h:72
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1470
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI bool isAbsoluteSymbolRef() const
Returns whether this is a reference to an absolute symbol.
Definition Globals.cpp:526
void setLinkage(LinkageTypes LT)
PointerType * getType() const
Global values are always pointers.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Type * getValueType() const
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:613
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
bool runOnModule(Module &) override
ImmutablePasses are never run.
Definition Pass.h:302
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition MDBuilder.h:195
MDNode * createAnonymousAliasScopeDomain(StringRef Name=StringRef())
Return metadata appropriate for an alias scope domain node.
Definition MDBuilder.h:188
Metadata node.
Definition Metadata.h:1069
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
Root of the metadata hierarchy.
Definition Metadata.h:64
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1755
LLVM_ABI void addOperand(MDNode *M)
A container for an operand bundle being viewed as a set of values rather than a set of uses.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
A simple AA result which uses scoped-noalias metadata to answer queries.
static LLVM_ABI void collectScopedDomains(const MDNode *NoAlias, SmallPtrSetImpl< const MDNode * > &Domains)
Collect the set of scoped domains relevant to the noalias scopes.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:683
Target-Independent Code Generator Pass Configuration Options.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:510
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:561
iterator_range< use_iterator > uses()
Definition Value.h:380
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
bool erase(const ValueT &V)
Definition DenseSet.h:97
size_type size() const
Definition DenseSet.h:84
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
A raw_ostream that writes to an std::string.
Changed
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
GVUsesInfoTy getTransitiveUsesOfLDSForLowering(const CallGraph &CG, Module &M)
Collects all uses of LDS Global Variables in M using getUsesOfGVByFunction, with isLDSVariableToLower...
bool isDynamicLDS(const GlobalVariable &GV)
void removeFnAttrFromReachable(CallGraph &CG, Function *KernelRoot, ArrayRef< StringRef > FnAttrs)
Strip FnAttr attribute from any functions where we may have introduced its use.
bool eliminateGVConstantExprUsesFromAllInstructions(Module &M, function_ref< bool(const GlobalVariable &)> Filter)
Iterates over all GlobalVariables in M, and whenever Filter returns true, replace all constant users ...
LLVM_READNONE constexpr bool isKernel(CallingConv::ID CC)
void getUsesOfGVByFunction(const CallGraph &CG, Module &M, function_ref< bool(const GlobalVariable &)> Filter, FunctionVariableMap &Kernels, FunctionVariableMap &Functions)
Finds uses of Global Variables on a per-function basis.
DenseMap< Function *, DenseSet< GlobalVariable * > > FunctionVariableMap
TargetExtType * isNamedBarrier(const GlobalVariable &GV)
bool isLDSVariableToLower(const GlobalVariable &GV)
Align getAlign(const DataLayout &DL, const GlobalVariable *GV)
DenseMap< GlobalVariable *, DenseSet< Function * > > VariableFunctionMap
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
char & AMDGPULowerModuleLDSLegacyPassID
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
S1Ty set_intersection(const S1Ty &S1, const S2Ty &S2)
set_intersection(A, B) - Return A ^ B
LLVM_ABI void removeFromUsedLists(Module &M, function_ref< bool(Constant *)> ShouldRemove)
Removes global values from the llvm.used and llvm.compiler.used arrays.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
ModulePass * createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM=nullptr)
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
LLVM_ABI std::pair< uint64_t, Align > performOptimizedStructLayout(MutableArrayRef< OptimizedStructLayoutField > Fields)
Compute a layout for a struct containing the given fields, making a best-effort attempt to minimize t...
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const AMDGPUTargetMachine & TM
Definition AMDGPU.h:152
FunctionVariableMap DirectAccess
FunctionVariableMap IndirectAccess
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77