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"
200#include "llvm/Support/Format.h"
205
206#include <cstdio>
207
208#define DEBUG_TYPE "amdgpu-lower-module-lds"
209
210using namespace llvm;
211using namespace AMDGPU;
212
213namespace {
214
215template <typename T> std::vector<T> sortByName(std::vector<T> &&V) {
216 llvm::sort(V, [](const auto *L, const auto *R) {
217 return L->getName() < R->getName();
218 });
219 return {std::move(V)};
220}
221
222class AMDGPULowerModuleLDS {
223 const AMDGPUTargetMachine &TM;
224
225 static void
226 removeLocalVarsFromUsedLists(Module &M,
227 const DenseSet<GlobalVariable *> &LocalVars) {
228 // The verifier rejects used lists containing an inttoptr of a constant
229 // so remove the variables from these lists before replaceAllUsesWith
230 SmallPtrSet<Constant *, 8> LocalVarsSet;
231 for (GlobalVariable *LocalVar : LocalVars)
232 LocalVarsSet.insert(cast<Constant>(LocalVar->stripPointerCasts()));
233
235 M, [&LocalVarsSet](Constant *C) { return LocalVarsSet.count(C); });
236
237 for (GlobalVariable *LocalVar : LocalVars)
238 LocalVar->removeDeadConstantUsers();
239 }
240
241 static void markUsedByKernel(Function *Func, GlobalVariable *SGV) {
242 // The llvm.amdgcn.module.lds instance is implicitly used by all kernels
243 // that might call a function which accesses a field within it. This is
244 // presently approximated to 'all kernels' if there are any such functions
245 // in the module. This implicit use is redefined as an explicit use here so
246 // that later passes, specifically PromoteAlloca, account for the required
247 // memory without any knowledge of this transform.
248
249 // An operand bundle on llvm.donothing works because the call instruction
250 // survives until after the last pass that needs to account for LDS. It is
251 // better than inline asm as the latter survives until the end of codegen. A
252 // totally robust solution would be a function with the same semantics as
253 // llvm.donothing that takes a pointer to the instance and is lowered to a
254 // no-op after LDS is allocated, but that is not presently necessary.
255
256 // This intrinsic is eliminated shortly before instruction selection. It
257 // does not suffice to indicate to ISel that a given global which is not
258 // immediately used by the kernel must still be allocated by it. An
259 // equivalent target specific intrinsic which lasts until immediately after
260 // codegen would suffice for that, but one would still need to ensure that
261 // the variables are allocated in the anticipated order.
262 BasicBlock *Entry = &Func->getEntryBlock();
263 IRBuilder<> Builder(Entry->getFirstNonPHIIt());
264
266 Func->getParent(), Intrinsic::donothing, {});
267
268 Value *UseInstance[1] = {
269 Builder.CreateConstInBoundsGEP1_32(SGV->getValueType(), SGV, 0)};
270
271 Builder.CreateCall(
272 Decl, {}, {OperandBundleDefT<Value *>("ExplicitUse", UseInstance)});
273 }
274
275public:
276 AMDGPULowerModuleLDS(const AMDGPUTargetMachine &TM_) : TM(TM_) {}
277
278 struct LDSVariableReplacement {
279 GlobalVariable *SGV = nullptr;
280 DenseMap<GlobalVariable *, Constant *> LDSVarsToConstantGEP;
281 };
282
283 // remap from lds global to a constantexpr gep to where it has been moved to
284 // for each kernel
285 // an array with an element for each kernel containing where the corresponding
286 // variable was remapped to
287
288 static Constant *getAddressesOfVariablesInKernel(
290 const DenseMap<GlobalVariable *, Constant *> &LDSVarsToConstantGEP) {
291 // Create a ConstantArray containing the address of each Variable within the
292 // kernel corresponding to LDSVarsToConstantGEP, or poison if that kernel
293 // does not allocate it
294
296 ArrayType *KernelOffsetsType = ArrayType::get(LocalPtrTy, Variables.size());
297
299 for (GlobalVariable *GV : Variables) {
300 auto ConstantGepIt = LDSVarsToConstantGEP.find(GV);
301 if (ConstantGepIt != LDSVarsToConstantGEP.end()) {
302 Elements.push_back(ConstantGepIt->second);
303 } else {
304 Elements.push_back(PoisonValue::get(LocalPtrTy));
305 }
306 }
307 return ConstantArray::get(KernelOffsetsType, Elements);
308 }
309
310 static GlobalVariable *buildLookupTable(
312 ArrayRef<Function *> kernels,
314 if (Variables.empty()) {
315 return nullptr;
316 }
317 LLVMContext &Ctx = M.getContext();
318
319 const size_t NumberVariables = Variables.size();
320 const size_t NumberKernels = kernels.size();
321
323 ArrayType *KernelOffsetsType = ArrayType::get(LocalPtrTy, NumberVariables);
324
325 ArrayType *AllKernelsOffsetsType =
326 ArrayType::get(KernelOffsetsType, NumberKernels);
327
328 Constant *Missing = PoisonValue::get(KernelOffsetsType);
329 std::vector<Constant *> overallConstantExprElts(NumberKernels);
330 for (size_t i = 0; i < NumberKernels; i++) {
331 auto Replacement = KernelToReplacement.find(kernels[i]);
332 overallConstantExprElts[i] =
333 (Replacement == KernelToReplacement.end())
334 ? Missing
335 : getAddressesOfVariablesInKernel(
336 Ctx, Variables, Replacement->second.LDSVarsToConstantGEP);
337 }
338
339 Constant *init =
340 ConstantArray::get(AllKernelsOffsetsType, overallConstantExprElts);
341
342 return new GlobalVariable(
343 M, AllKernelsOffsetsType, true, GlobalValue::InternalLinkage, init,
344 "llvm.amdgcn.lds.offset.table", nullptr, GlobalValue::NotThreadLocal,
346 }
347
348 void replaceUseWithTableLookup(Module &M, IRBuilder<> &Builder,
349 GlobalVariable *LookupTable,
350 GlobalVariable *GV, Use &U,
351 Value *OptionalIndex) {
352 // Table is a constant array of the same length as OrderedKernels
353 LLVMContext &Ctx = M.getContext();
354 Type *I32 = Type::getInt32Ty(Ctx);
355 auto *I = cast<Instruction>(U.getUser());
356
357 Value *tableKernelIndex = getTableLookupKernelIndex(M, I->getFunction());
358
359 if (auto *Phi = dyn_cast<PHINode>(I)) {
360 BasicBlock *BB = Phi->getIncomingBlock(U);
361 Builder.SetInsertPoint(&(*(BB->getFirstInsertionPt())));
362 } else {
363 Builder.SetInsertPoint(I);
364 }
365
366 SmallVector<Value *, 3> GEPIdx = {
367 ConstantInt::get(I32, 0),
368 tableKernelIndex,
369 };
370 if (OptionalIndex)
371 GEPIdx.push_back(OptionalIndex);
372
373 Value *Address = Builder.CreateInBoundsGEP(
374 LookupTable->getValueType(), LookupTable, GEPIdx, GV->getName());
375
376 Value *Loaded = Builder.CreateLoad(GV->getType(), Address);
377 U.set(Loaded);
378 }
379
380 void replaceUsesInInstructionsWithTableLookup(
381 Module &M, ArrayRef<GlobalVariable *> ModuleScopeVariables,
382 GlobalVariable *LookupTable) {
383
384 LLVMContext &Ctx = M.getContext();
385 IRBuilder<> Builder(M);
386 Type *I32 = Type::getInt32Ty(Ctx);
387
388 for (size_t Index = 0; Index < ModuleScopeVariables.size(); Index++) {
389 auto *GV = ModuleScopeVariables[Index];
390
391 for (Use &U : make_early_inc_range(GV->uses())) {
392 auto *I = dyn_cast<Instruction>(U.getUser());
393 if (!I)
394 continue;
395
396 replaceUseWithTableLookup(M, Builder, LookupTable, GV, U,
397 ConstantInt::get(I32, Index));
398 }
399 }
400 }
401
402 static DenseSet<Function *> kernelsThatIndirectlyAccessAnyOfPassedVariables(
403 Module &M, GVUsesInfoTy &LDSUsesInfo,
404 DenseSet<GlobalVariable *> const &VariableSet) {
405
406 DenseSet<Function *> KernelSet;
407
408 if (VariableSet.empty())
409 return KernelSet;
410
411 for (Function &Func : M.functions()) {
412 if (Func.isDeclaration() || !isKernel(Func))
413 continue;
414 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[&Func]) {
415 if (VariableSet.contains(GV)) {
416 KernelSet.insert(&Func);
417 break;
418 }
419 }
420 }
421
422 return KernelSet;
423 }
424
425 static GlobalVariable *
426 chooseBestVariableForModuleStrategy(const DataLayout &DL,
427 VariableFunctionMap &LDSVars) {
428 // Find the global variable with the most indirect uses from kernels
429
430 struct CandidateTy {
431 GlobalVariable *GV = nullptr;
432 size_t UserCount = 0;
433 size_t Size = 0;
434
435 CandidateTy() = default;
436
437 CandidateTy(GlobalVariable *GV, uint64_t UserCount, uint64_t AllocSize)
438 : GV(GV), UserCount(UserCount), Size(AllocSize) {}
439
440 bool operator<(const CandidateTy &Other) const {
441 // Fewer users makes module scope variable less attractive
442 if (UserCount < Other.UserCount) {
443 return true;
444 }
445 if (UserCount > Other.UserCount) {
446 return false;
447 }
448
449 // Bigger makes module scope variable less attractive
450 if (Size < Other.Size) {
451 return false;
452 }
453
454 if (Size > Other.Size) {
455 return true;
456 }
457
458 // Arbitrary but consistent
459 return GV->getName() < Other.GV->getName();
460 }
461 };
462
463 CandidateTy MostUsed;
464
465 for (auto &K : LDSVars) {
466 GlobalVariable *GV = K.first;
467 if (K.second.size() <= 1) {
468 // A variable reachable by only one kernel is best lowered with kernel
469 // strategy
470 continue;
471 }
472 CandidateTy Candidate(GV, K.second.size(), GV->getGlobalSize(DL));
473 if (MostUsed < Candidate)
474 MostUsed = Candidate;
475 }
476
477 return MostUsed.GV;
478 }
479
480 static void recordLDSAbsoluteAddress(Module *M, GlobalVariable *GV,
481 uint32_t Address) {
482 // Write the specified address into metadata where it can be retrieved by
483 // the assembler. Format is a half open range, [Address Address+1)
484 LLVMContext &Ctx = M->getContext();
485 auto *IntTy =
486 M->getDataLayout().getIntPtrType(Ctx, AMDGPUAS::LOCAL_ADDRESS);
487 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address));
488 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntTy, Address + 1));
489 GV->setMetadata(LLVMContext::MD_absolute_symbol,
490 MDNode::get(Ctx, {MinC, MaxC}));
491 }
492
493 DenseMap<Function *, Value *> tableKernelIndexCache;
494 Value *getTableLookupKernelIndex(Module &M, Function *F) {
495 // Accesses from a function use the amdgcn_lds_kernel_id intrinsic which
496 // lowers to a read from a live in register. Emit it once in the entry
497 // block to spare deduplicating it later.
498 auto [It, Inserted] = tableKernelIndexCache.try_emplace(F);
499 if (Inserted) {
500 auto InsertAt = F->getEntryBlock().getFirstNonPHIOrAlloca();
501 IRBuilder<> Builder(&*InsertAt);
502
503 It->second = Builder.CreateIntrinsic(Intrinsic::amdgcn_lds_kernel_id, {});
504 }
505
506 return It->second;
507 }
508
509 static std::vector<Function *> assignLDSKernelIDToEachKernel(
510 Module *M, DenseSet<Function *> const &KernelsThatAllocateTableLDS,
511 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS) {
512 // Associate kernels in the set with an arbitrary but reproducible order and
513 // annotate them with that order in metadata. This metadata is recognised by
514 // the backend and lowered to a SGPR which can be read from using
515 // amdgcn_lds_kernel_id.
516
517 std::vector<Function *> OrderedKernels;
518 if (!KernelsThatAllocateTableLDS.empty() ||
519 !KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
520
521 for (Function &Func : M->functions()) {
522 if (Func.isDeclaration())
523 continue;
524 if (!isKernel(Func))
525 continue;
526
527 if (KernelsThatAllocateTableLDS.contains(&Func) ||
528 KernelsThatIndirectlyAllocateDynamicLDS.contains(&Func)) {
529 assert(Func.hasName()); // else fatal error earlier
530 OrderedKernels.push_back(&Func);
531 }
532 }
533
534 // Put them in an arbitrary but reproducible order
535 OrderedKernels = sortByName(std::move(OrderedKernels));
536
537 // Annotate the kernels with their order in this vector
538 LLVMContext &Ctx = M->getContext();
539 IRBuilder<> Builder(*M);
540
541 if (OrderedKernels.size() > UINT32_MAX) {
542 // 32 bit keeps it in one SGPR. > 2**32 kernels won't fit on the GPU
543 reportFatalUsageError("unimplemented LDS lowering for > 2**32 kernels");
544 }
545
546 for (size_t i = 0; i < OrderedKernels.size(); i++) {
547 Metadata *AttrMDArgs[1] = {
548 ConstantAsMetadata::get(Builder.getInt32(i)),
549 };
550 OrderedKernels[i]->setMetadata("llvm.amdgcn.lds.kernel.id",
551 MDNode::get(Ctx, AttrMDArgs));
552 }
553 }
554 return OrderedKernels;
555 }
556
557 void partitionVariablesIntoIndirectStrategies(
558 Module &M, GVUsesInfoTy const &LDSUsesInfo,
559 VariableFunctionMap &LDSToKernelsThatNeedToAccessItIndirectly,
560 DenseSet<GlobalVariable *> &ModuleScopeVariables,
561 DenseSet<GlobalVariable *> &TableLookupVariables,
562 DenseSet<GlobalVariable *> &KernelAccessVariables,
563 DenseSet<GlobalVariable *> &DynamicVariables) {
564 LDSLoweringKind LoweringKind = TM.getCLOpts().lower_module_lds_strategy;
565
566 GlobalVariable *HybridModuleRoot =
567 LoweringKind != LDSLoweringKind::hybrid
568 ? nullptr
569 : chooseBestVariableForModuleStrategy(
570 M.getDataLayout(), LDSToKernelsThatNeedToAccessItIndirectly);
571
572 DenseSet<Function *> const EmptySet;
573 DenseSet<Function *> const &HybridModuleRootKernels =
574 HybridModuleRoot
575 ? LDSToKernelsThatNeedToAccessItIndirectly[HybridModuleRoot]
576 : EmptySet;
577
578 for (auto &K : LDSToKernelsThatNeedToAccessItIndirectly) {
579 // Each iteration of this loop assigns exactly one global variable to
580 // exactly one of the implementation strategies.
581
582 GlobalVariable *GV = K.first;
584 assert(!K.second.empty());
585
586 if (AMDGPU::isDynamicLDS(*GV)) {
587 DynamicVariables.insert(GV);
588 continue;
589 }
590
591 switch (LoweringKind) {
592 case LDSLoweringKind::module:
593 ModuleScopeVariables.insert(GV);
594 break;
595
596 case LDSLoweringKind::table:
597 TableLookupVariables.insert(GV);
598 break;
599
600 case LDSLoweringKind::kernel:
601 if (K.second.size() == 1) {
602 KernelAccessVariables.insert(GV);
603 } else {
604 // FIXME: This should use DiagnosticInfo
606 "cannot lower LDS '" + GV->getName() +
607 "' to kernel access as it is reachable from multiple kernels");
608 }
609 break;
610
611 case LDSLoweringKind::hybrid: {
612 if (GV == HybridModuleRoot) {
613 assert(K.second.size() != 1);
614 ModuleScopeVariables.insert(GV);
615 } else if (K.second.size() == 1) {
616 KernelAccessVariables.insert(GV);
617 } else if (K.second == HybridModuleRootKernels) {
618 ModuleScopeVariables.insert(GV);
619 } else {
620 TableLookupVariables.insert(GV);
621 }
622 break;
623 }
624 }
625 }
626
627 // All LDS variables accessed indirectly have now been partitioned into
628 // the distinct lowering strategies.
629 assert(ModuleScopeVariables.size() + TableLookupVariables.size() +
630 KernelAccessVariables.size() + DynamicVariables.size() ==
631 LDSToKernelsThatNeedToAccessItIndirectly.size());
632 }
633
634 static GlobalVariable *lowerModuleScopeStructVariables(
635 Module &M, DenseSet<GlobalVariable *> const &ModuleScopeVariables,
636 DenseSet<Function *> const &KernelsThatAllocateModuleLDS) {
637 // Create a struct to hold the ModuleScopeVariables
638 // Replace all uses of those variables from non-kernel functions with the
639 // new struct instance Replace only the uses from kernel functions that will
640 // allocate this instance. That is a space optimisation - kernels that use a
641 // subset of the module scope struct and do not need to allocate it for
642 // indirect calls will only allocate the subset they use (they do so as part
643 // of the per-kernel lowering).
644 if (ModuleScopeVariables.empty()) {
645 return nullptr;
646 }
647
648 LLVMContext &Ctx = M.getContext();
649
650 LDSVariableReplacement ModuleScopeReplacement =
651 createLDSVariableReplacement(M, "llvm.amdgcn.module.lds",
652 ModuleScopeVariables);
653
654 appendToCompilerUsed(M, {static_cast<GlobalValue *>(
656 cast<Constant>(ModuleScopeReplacement.SGV),
657 PointerType::getUnqual(Ctx)))});
658
659 // module.lds will be allocated at zero in any kernel that allocates it
660 recordLDSAbsoluteAddress(&M, ModuleScopeReplacement.SGV, 0);
661
662 // historic
663 removeLocalVarsFromUsedLists(M, ModuleScopeVariables);
664
665 // Replace all uses of module scope variable from non-kernel functions
666 replaceLDSVariablesWithStruct(
667 M, ModuleScopeVariables, ModuleScopeReplacement, [&](Use &U) {
668 Instruction *I = dyn_cast<Instruction>(U.getUser());
669 if (!I) {
670 return false;
671 }
672 Function *F = I->getFunction();
673 return !isKernel(*F);
674 });
675
676 // Replace uses of module scope variable from kernel functions that
677 // allocate the module scope variable, otherwise leave them unchanged
678 // Record on each kernel whether the module scope global is used by it
679
680 for (Function &Func : M.functions()) {
681 if (Func.isDeclaration() || !isKernel(Func))
682 continue;
683
684 if (KernelsThatAllocateModuleLDS.contains(&Func)) {
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 F == &Func;
693 });
694
695 markUsedByKernel(&Func, ModuleScopeReplacement.SGV);
696 }
697 }
698
699 return ModuleScopeReplacement.SGV;
700 }
701
703 lowerKernelScopeStructVariables(
704 Module &M, GVUsesInfoTy &LDSUsesInfo,
705 DenseSet<GlobalVariable *> const &ModuleScopeVariables,
706 DenseSet<Function *> const &KernelsThatAllocateModuleLDS,
707 GlobalVariable *MaybeModuleScopeStruct) {
708
709 // Create a struct for each kernel for the non-module-scope variables.
710
712 for (Function &Func : M.functions()) {
713 if (Func.isDeclaration() || !isKernel(Func))
714 continue;
715
716 DenseSet<GlobalVariable *> KernelUsedVariables;
717 // Allocating variables that are used directly in this struct to get
718 // alignment aware allocation and predictable frame size.
719 for (auto &v : LDSUsesInfo.DirectAccess[&Func]) {
720 if (!AMDGPU::isDynamicLDS(*v)) {
721 KernelUsedVariables.insert(v);
722 }
723 }
724
725 // Allocating variables that are accessed indirectly so that a lookup of
726 // this struct instance can find them from nested functions.
727 for (auto &v : LDSUsesInfo.IndirectAccess[&Func]) {
728 if (!AMDGPU::isDynamicLDS(*v)) {
729 KernelUsedVariables.insert(v);
730 }
731 }
732
733 // Variables allocated in module lds must all resolve to that struct,
734 // not to the per-kernel instance.
735 if (KernelsThatAllocateModuleLDS.contains(&Func)) {
736 for (GlobalVariable *v : ModuleScopeVariables) {
737 KernelUsedVariables.erase(v);
738 }
739 }
740
741 if (KernelUsedVariables.empty()) {
742 // Either used no LDS, or the LDS it used was all in the module struct
743 // or dynamically sized
744 continue;
745 }
746
747 // The association between kernel function and LDS struct is done by
748 // symbol name, which only works if the function in question has a
749 // name This is not expected to be a problem in practice as kernels
750 // are called by name making anonymous ones (which are named by the
751 // backend) difficult to use. This does mean that llvm test cases need
752 // to name the kernels.
753 if (!Func.hasName()) {
754 reportFatalUsageError("anonymous kernels cannot use LDS variables");
755 }
756
757 std::string VarName =
758 (Twine("llvm.amdgcn.kernel.") + Func.getName() + ".lds").str();
759
760 auto Replacement =
761 createLDSVariableReplacement(M, VarName, KernelUsedVariables);
762
763 // If any indirect uses, create a direct use to ensure allocation
764 // TODO: Simpler to unconditionally mark used but that regresses
765 // codegen in test/CodeGen/AMDGPU/noclobber-barrier.ll
766 auto Accesses = LDSUsesInfo.IndirectAccess.find(&Func);
767 if ((Accesses != LDSUsesInfo.IndirectAccess.end()) &&
768 !Accesses->second.empty())
769 markUsedByKernel(&Func, Replacement.SGV);
770
771 // remove preserves existing codegen
772 removeLocalVarsFromUsedLists(M, KernelUsedVariables);
773 KernelToReplacement[&Func] = Replacement;
774
775 // Rewrite uses within kernel to the new struct
776 replaceLDSVariablesWithStruct(
777 M, KernelUsedVariables, Replacement, [&Func](Use &U) {
778 Instruction *I = dyn_cast<Instruction>(U.getUser());
779 return I && I->getFunction() == &Func;
780 });
781 }
782 return KernelToReplacement;
783 }
784
785 static GlobalVariable *
786 buildRepresentativeDynamicLDSInstance(Module &M, GVUsesInfoTy &LDSUsesInfo,
787 Function *func) {
788 // Create a dynamic lds variable with a name associated with the passed
789 // function that has the maximum alignment of any dynamic lds variable
790 // reachable from this kernel. Dynamic LDS is allocated after the static LDS
791 // allocation, possibly after alignment padding. The representative variable
792 // created here has the maximum alignment of any other dynamic variable
793 // reachable by that kernel. All dynamic LDS variables are allocated at the
794 // same address in each kernel in order to provide the documented aliasing
795 // semantics. Setting the alignment here allows this IR pass to accurately
796 // predict the exact constant at which it will be allocated.
797
798 assert(isKernel(*func));
799
800 LLVMContext &Ctx = M.getContext();
801 const DataLayout &DL = M.getDataLayout();
802 Align MaxDynamicAlignment(1);
803
804 auto UpdateMaxAlignment = [&MaxDynamicAlignment, &DL](GlobalVariable *GV) {
805 if (AMDGPU::isDynamicLDS(*GV)) {
806 MaxDynamicAlignment =
807 std::max(MaxDynamicAlignment, AMDGPU::getAlign(DL, GV));
808 }
809 };
810
811 for (GlobalVariable *GV : LDSUsesInfo.IndirectAccess[func]) {
812 UpdateMaxAlignment(GV);
813 }
814
815 for (GlobalVariable *GV : LDSUsesInfo.DirectAccess[func]) {
816 UpdateMaxAlignment(GV);
817 }
818
819 assert(func->hasName()); // Checked by caller
820 auto *emptyCharArray = ArrayType::get(Type::getInt8Ty(Ctx), 0);
822 M, emptyCharArray, false, GlobalValue::ExternalLinkage, nullptr,
823 Twine("llvm.amdgcn." + func->getName() + ".dynlds"), nullptr,
825 N->setAlignment(MaxDynamicAlignment);
826
828 return N;
829 }
830
831 DenseMap<Function *, GlobalVariable *> lowerDynamicLDSVariables(
832 Module &M, GVUsesInfoTy &LDSUsesInfo,
833 DenseSet<Function *> const &KernelsThatIndirectlyAllocateDynamicLDS,
834 DenseSet<GlobalVariable *> const &DynamicVariables,
835 std::vector<Function *> const &OrderedKernels) {
836 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS;
837 if (!KernelsThatIndirectlyAllocateDynamicLDS.empty()) {
838 LLVMContext &Ctx = M.getContext();
839 IRBuilder<> Builder(M);
841
842 std::vector<Constant *> newDynamicLDS;
843
844 // Table is built in the same order as OrderedKernels
845 for (auto &func : OrderedKernels) {
846
847 if (KernelsThatIndirectlyAllocateDynamicLDS.contains(func)) {
848 assert(isKernel(*func));
849 if (!func->hasName()) {
850 reportFatalUsageError("anonymous kernels cannot use LDS variables");
851 }
852
854 buildRepresentativeDynamicLDSInstance(M, LDSUsesInfo, func);
855
856 KernelToCreatedDynamicLDS[func] = N;
857
858 markUsedByKernel(func, N);
859
860 newDynamicLDS.push_back(N);
861 } else {
862 newDynamicLDS.push_back(PoisonValue::get(LocalPtrTy));
863 }
864 }
865 assert(OrderedKernels.size() == newDynamicLDS.size());
866
867 ArrayType *t = ArrayType::get(LocalPtrTy, newDynamicLDS.size());
868 Constant *init = ConstantArray::get(t, newDynamicLDS);
870 M, t, true, GlobalValue::InternalLinkage, init,
871 "llvm.amdgcn.dynlds.offset.table", nullptr,
873
874 for (GlobalVariable *GV : DynamicVariables) {
875 for (Use &U : make_early_inc_range(GV->uses())) {
876 auto *I = dyn_cast<Instruction>(U.getUser());
877 if (!I)
878 continue;
879 if (isKernel(*I->getFunction()))
880 continue;
881
882 replaceUseWithTableLookup(M, Builder, table, GV, U, nullptr);
883 }
884 }
885 }
886 return KernelToCreatedDynamicLDS;
887 }
888
889 // Per-TU mode for link-time LDS resolution. Instead of computing a global
890 // layout, create per-function LDS struct declarations so the linker can
891 // assign offsets across TUs.
892 bool runOnModuleLinkTime(Module &M) {
893 bool Changed = superAlignLDSGlobals(M);
894 Changed |=
896
897 CallGraph CG(M);
898 FunctionVariableMap KernelLDSUses, FunctionLDSUses;
899 getUsesOfGVByFunction(CG, M, isLDSVariableToLower, KernelLDSUses,
900 FunctionLDSUses);
901
902 if (KernelLDSUses.empty() && FunctionLDSUses.empty())
903 return Changed;
904
905 std::string ModuleId = getUniqueModuleId(&M);
906 assert(!ModuleId.empty() &&
907 "modules with LDS variables should have a unique ID");
908
909 FunctionVariableMap AllLDSUses;
910 for (auto &[F, Vars] : KernelLDSUses)
911 AllLDSUses[F].insert(Vars.begin(), Vars.end());
912 for (auto &[F, Vars] : FunctionLDSUses)
913 AllLDSUses[F].insert(Vars.begin(), Vars.end());
914
915 // Build reverse map: LDS variable -> functions that use it.
917 for (auto &[F, Vars] : AllLDSUses) {
918 for (GlobalVariable *V : Vars)
919 VarToFuncs[V].push_back(F);
920 }
921
922 // A variable is function-scope iff it has local linkage and exactly one
923 // user function. Everything else is global-scope and must remain as a
924 // standalone external declaration so the linker can assign a single shared
925 // offset.
926 DenseSet<GlobalVariable *> GlobalScopeVars;
927 DenseSet<GlobalVariable *> InternalMultiUserVars;
928 for (auto &[V, Funcs] : VarToFuncs) {
929 if (!V->hasLocalLinkage() || Funcs.size() > 1) {
930 GlobalScopeVars.insert(V);
931 if (V->hasLocalLinkage())
932 InternalMultiUserVars.insert(V);
933 }
934 }
935
936 // Wrap function-scope LDS into per-function structs (unchanged logic,
937 // but global-scope variables are excluded from the set).
939 DenseSet<GlobalVariable *> AllReplacedVars;
940 for (auto &KV : AllLDSUses) {
941 Function *F = KV.first;
942 DenseSet<GlobalVariable *> FuncScopeVars;
943 for (GlobalVariable *V : KV.second) {
944 if (!GlobalScopeVars.count(V))
945 FuncScopeVars.insert(V);
946 }
947
948 if (FuncScopeVars.empty())
949 continue;
950
951 std::string StructName =
952 F->hasLocalLinkage()
953 ? ("__amdgpu_lds." + F->getName() + ModuleId).str()
954 : ("__amdgpu_lds." + F->getName()).str();
955 LDSVariableReplacement Replacement =
956 createLDSVariableReplacement(M, StructName, FuncScopeVars);
957
958 GlobalVariable *SGV = Replacement.SGV;
959 SGV->setLinkage(GlobalValue::ExternalLinkage);
960 SGV->setInitializer(nullptr);
961 FuncToLdsStruct.push_back({F, SGV});
962
963 replaceLDSVariablesWithStruct(
964 M, FuncScopeVars, Replacement, [F](const Use &U) {
965 auto *I = dyn_cast<Instruction>(U.getUser());
966 return I && I->getFunction() == F;
967 });
968
969 AllReplacedVars.insert(FuncScopeVars.begin(), FuncScopeVars.end());
970 }
971
972 // Internal-linkage LDS variables used by multiple functions would collide
973 // across TUs if promoted individually to external linkage (same name in
974 // different TUs). Pack them into a single per-module struct with a
975 // module-unique name so the linker treats them as one allocation unit.
976 if (!InternalMultiUserVars.empty()) {
977 std::string StructName = "__amdgpu_lds.__internal" + ModuleId;
978 LDSVariableReplacement Replacement =
979 createLDSVariableReplacement(M, StructName, InternalMultiUserVars);
980
981 GlobalVariable *SGV = Replacement.SGV;
982 SGV->setLinkage(GlobalValue::ExternalLinkage);
983 SGV->setInitializer(nullptr);
984
985 replaceLDSVariablesWithStruct(
986 M, InternalMultiUserVars, Replacement,
987 [](const Use &U) { return isa<Instruction>(U.getUser()); });
988
989 DenseSet<Function *> FuncsUsingInternalVars;
990 for (GlobalVariable *V : InternalMultiUserVars) {
991 for (Function *F : VarToFuncs[V])
992 FuncsUsingInternalVars.insert(F);
993 }
994 for (Function *F : FuncsUsingInternalVars)
995 FuncToLdsStruct.push_back({F, SGV});
996
997 AllReplacedVars.insert(InternalMultiUserVars.begin(),
998 InternalMultiUserVars.end());
999 }
1000
1001 // Convert global-scope LDS to external declarations. Their uses remain
1002 // intact and ISel generates R_AMDGPU_ABS32_LO relocations for them.
1003 for (GlobalVariable *V : GlobalScopeVars) {
1004 V->setInitializer(nullptr);
1005 V->setLinkage(GlobalValue::ExternalLinkage);
1006 }
1007
1008 // Emit amdgpu.lds.uses metadata for struct and global-scope LDS.
1009 {
1010 LLVMContext &Ctx = M.getContext();
1011 NamedMDNode *LdsMD = M.getOrInsertNamedMetadata("amdgpu.lds.uses");
1012
1013 for (auto &[F, SGV] : FuncToLdsStruct)
1014 LdsMD->addOperand(MDNode::get(
1016
1017 for (auto &[V, Funcs] : VarToFuncs) {
1018 if (GlobalScopeVars.count(V) && !InternalMultiUserVars.count(V)) {
1019 for (Function *F : Funcs) {
1020 LdsMD->addOperand(MDNode::get(
1022 }
1023 }
1024 }
1025 }
1026
1027 DenseSet<GlobalVariable *> AllLDSVarsForCleanup = AllReplacedVars;
1028 AllLDSVarsForCleanup.insert(GlobalScopeVars.begin(), GlobalScopeVars.end());
1029 removeLocalVarsFromUsedLists(M, AllLDSVarsForCleanup);
1030 for (GlobalVariable *GV : AllReplacedVars) {
1032 if (GV->use_empty())
1033 GV->eraseFromParent();
1034 }
1035
1036 return true;
1037 }
1038
1039 bool runOnModule(Module &M) {
1041 return runOnModuleLinkTime(M);
1042 return runOnModuleNormal(M);
1043 }
1044
1045 bool runOnModuleNormal(Module &M) {
1046 bool Changed = superAlignLDSGlobals(M);
1047
1048 Changed |= any_of(M.globals(), isNotYetLoweredLDSVariable);
1049
1050 CallGraph CG(M);
1051
1053 isNotYetLoweredLDSVariable);
1054
1055 // For each kernel, what variables does it access directly or through
1056 // callees
1058
1059 // For each variable accessed through callees, which kernels access it
1060 VariableFunctionMap LDSToKernelsThatNeedToAccessItIndirectly;
1061 for (auto &K : LDSUsesInfo.IndirectAccess) {
1062 Function *F = K.first;
1063 assert(isKernel(*F));
1064 for (GlobalVariable *GV : K.second) {
1065 LDSToKernelsThatNeedToAccessItIndirectly[GV].insert(F);
1066 }
1067 }
1068
1069 // Partition variables accessed indirectly into the different strategies
1070 DenseSet<GlobalVariable *> ModuleScopeVariables;
1071 DenseSet<GlobalVariable *> TableLookupVariables;
1072 DenseSet<GlobalVariable *> KernelAccessVariables;
1073 DenseSet<GlobalVariable *> DynamicVariables;
1074 partitionVariablesIntoIndirectStrategies(
1075 M, LDSUsesInfo, LDSToKernelsThatNeedToAccessItIndirectly,
1076 ModuleScopeVariables, TableLookupVariables, KernelAccessVariables,
1077 DynamicVariables);
1078
1079 // If the kernel accesses a variable that is going to be stored in the
1080 // module instance through a call then that kernel needs to allocate the
1081 // module instance
1082 const DenseSet<Function *> KernelsThatAllocateModuleLDS =
1083 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1084 ModuleScopeVariables);
1085 const DenseSet<Function *> KernelsThatAllocateTableLDS =
1086 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1087 TableLookupVariables);
1088
1089 const DenseSet<Function *> KernelsThatIndirectlyAllocateDynamicLDS =
1090 kernelsThatIndirectlyAccessAnyOfPassedVariables(M, LDSUsesInfo,
1091 DynamicVariables);
1092
1093 GlobalVariable *MaybeModuleScopeStruct = lowerModuleScopeStructVariables(
1094 M, ModuleScopeVariables, KernelsThatAllocateModuleLDS);
1095
1097 lowerKernelScopeStructVariables(M, LDSUsesInfo, ModuleScopeVariables,
1098 KernelsThatAllocateModuleLDS,
1099 MaybeModuleScopeStruct);
1100
1101 // Lower zero cost accesses to the kernel instances just created
1102 for (auto &GV : KernelAccessVariables) {
1103 auto &funcs = LDSToKernelsThatNeedToAccessItIndirectly[GV];
1104 assert(funcs.size() == 1); // Only one kernel can access it
1105 LDSVariableReplacement Replacement =
1106 KernelToReplacement[*(funcs.begin())];
1107
1109 Vec.insert(GV);
1110
1111 replaceLDSVariablesWithStruct(M, Vec, Replacement, [](Use &U) {
1112 return isa<Instruction>(U.getUser());
1113 });
1114 }
1115
1116 // The ith element of this vector is kernel id i
1117 std::vector<Function *> OrderedKernels =
1118 assignLDSKernelIDToEachKernel(&M, KernelsThatAllocateTableLDS,
1119 KernelsThatIndirectlyAllocateDynamicLDS);
1120
1121 if (!KernelsThatAllocateTableLDS.empty()) {
1122 IRBuilder<> Builder(M);
1123
1124 // The order must be consistent between lookup table and accesses to
1125 // lookup table
1126 auto TableLookupVariablesOrdered =
1127 sortByName(std::vector<GlobalVariable *>(TableLookupVariables.begin(),
1128 TableLookupVariables.end()));
1129
1130 GlobalVariable *LookupTable = buildLookupTable(
1131 M, TableLookupVariablesOrdered, OrderedKernels, KernelToReplacement);
1132 replaceUsesInInstructionsWithTableLookup(M, TableLookupVariablesOrdered,
1133 LookupTable);
1134 }
1135
1136 DenseMap<Function *, GlobalVariable *> KernelToCreatedDynamicLDS =
1137 lowerDynamicLDSVariables(M, LDSUsesInfo,
1138 KernelsThatIndirectlyAllocateDynamicLDS,
1139 DynamicVariables, OrderedKernels);
1140
1141 // Strip amdgpu-no-lds-kernel-id from all functions reachable from the
1142 // kernel. We may have inferred this wasn't used prior to the pass.
1143 // TODO: We could filter out subgraphs that do not access LDS globals.
1144 for (auto *KernelSet : {&KernelsThatIndirectlyAllocateDynamicLDS,
1145 &KernelsThatAllocateTableLDS})
1146 for (Function *F : *KernelSet)
1147 removeFnAttrFromReachable(CG, F, {"amdgpu-no-lds-kernel-id"});
1148
1149 // All kernel frames have been allocated. Calculate and record the
1150 // addresses.
1151 {
1152 const DataLayout &DL = M.getDataLayout();
1153
1154 for (Function &Func : M.functions()) {
1155 if (Func.isDeclaration() || !isKernel(Func))
1156 continue;
1157
1158 // All three of these are optional. The first variable is allocated at
1159 // zero. They are allocated by AMDGPUMachineFunctionInfo as one block.
1160 // Layout:
1161 //{
1162 // module.lds
1163 // alignment padding
1164 // kernel instance
1165 // alignment padding
1166 // dynamic lds variables
1167 //}
1168
1169 const bool AllocateModuleScopeStruct =
1170 MaybeModuleScopeStruct &&
1171 KernelsThatAllocateModuleLDS.contains(&Func);
1172
1173 auto Replacement = KernelToReplacement.find(&Func);
1174 const bool AllocateKernelScopeStruct =
1175 Replacement != KernelToReplacement.end();
1176
1177 const bool AllocateDynamicVariable =
1178 KernelToCreatedDynamicLDS.contains(&Func);
1179
1180 uint32_t Offset = 0;
1181
1182 if (AllocateModuleScopeStruct) {
1183 // Allocated at zero, recorded once on construction, not once per
1184 // kernel
1185 Offset += MaybeModuleScopeStruct->getGlobalSize(DL);
1186 }
1187
1188 if (AllocateKernelScopeStruct) {
1189 GlobalVariable *KernelStruct = Replacement->second.SGV;
1190 Offset = alignTo(Offset, AMDGPU::getAlign(DL, KernelStruct));
1191 recordLDSAbsoluteAddress(&M, KernelStruct, Offset);
1192 Offset += KernelStruct->getGlobalSize(DL);
1193 }
1194
1195 // If there is dynamic allocation, the alignment needed is included in
1196 // the static frame size. There may be no reference to the dynamic
1197 // variable in the kernel itself, so without including it here, that
1198 // alignment padding could be missed.
1199 if (AllocateDynamicVariable) {
1200 GlobalVariable *DynamicVariable = KernelToCreatedDynamicLDS[&Func];
1201 Offset = alignTo(Offset, AMDGPU::getAlign(DL, DynamicVariable));
1202 recordLDSAbsoluteAddress(&M, DynamicVariable, Offset);
1203 }
1204
1205 if (Offset != 0) {
1206 (void)TM; // TODO: Account for target maximum LDS
1207 std::string Buffer;
1208 raw_string_ostream SS{Buffer};
1209 SS << format("%u", Offset);
1210
1211 // Instead of explicitly marking kernels that access dynamic variables
1212 // using special case metadata, annotate with min-lds == max-lds, i.e.
1213 // that there is no more space available for allocating more static
1214 // LDS variables. That is the right condition to prevent allocating
1215 // more variables which would collide with the addresses assigned to
1216 // dynamic variables.
1217 if (AllocateDynamicVariable)
1218 SS << format(",%u", Offset);
1219
1220 Func.addFnAttr("amdgpu-lds-size", Buffer);
1221 }
1222 }
1223 }
1224
1225 for (auto &GV : make_early_inc_range(M.globals()))
1226 if (isNotYetLoweredLDSVariable(GV)) {
1227 // probably want to remove from used lists
1229 if (GV.use_empty())
1230 GV.eraseFromParent();
1231 }
1232
1233 return Changed;
1234 }
1235
1236private:
1237 // An absolute address means a previous run already placed the variable.
1238 static bool isNotYetLoweredLDSVariable(const GlobalVariable &GV) {
1239 return isLDSVariableToLower(GV) && !GV.isAbsoluteSymbolRef();
1240 }
1241
1242 // Increase the alignment of LDS globals if necessary to maximise the chance
1243 // that we can use aligned LDS instructions to access them.
1244 bool superAlignLDSGlobals(Module &M) {
1245 const DataLayout &DL = M.getDataLayout();
1246 bool Changed = false;
1247 if (!TM.getCLOpts().super_align_lds_globals) {
1248 return Changed;
1249 }
1250
1251 for (auto &GV : M.globals()) {
1253 // Only changing alignment of LDS variables
1254 continue;
1255 }
1256 if (!GV.hasInitializer()) {
1257 // cuda/hip extern __shared__ variable, leave alignment alone
1258 continue;
1259 }
1260
1261 if (GV.isAbsoluteSymbolRef()) {
1262 // If the variable is already allocated, don't change the alignment
1263 continue;
1264 }
1265
1266 Align Alignment = AMDGPU::getAlign(DL, &GV);
1267 uint64_t GVSize = GV.getGlobalSize(DL);
1268
1269 if (GVSize > 8) {
1270 // We might want to use a b96 or b128 load/store
1271 Alignment = std::max(Alignment, Align(16));
1272 } else if (GVSize > 4) {
1273 // We might want to use a b64 load/store
1274 Alignment = std::max(Alignment, Align(8));
1275 } else if (GVSize > 2) {
1276 // We might want to use a b32 load/store
1277 Alignment = std::max(Alignment, Align(4));
1278 } else if (GVSize > 1) {
1279 // We might want to use a b16 load/store
1280 Alignment = std::max(Alignment, Align(2));
1281 }
1282
1283 if (Alignment != AMDGPU::getAlign(DL, &GV)) {
1284 Changed = true;
1285 GV.setAlignment(Alignment);
1286 }
1287 }
1288 return Changed;
1289 }
1290
1291 static LDSVariableReplacement createLDSVariableReplacement(
1292 Module &M, std::string VarName,
1293 DenseSet<GlobalVariable *> const &LDSVarsToTransform) {
1294 // Create a struct instance containing LDSVarsToTransform and map from those
1295 // variables to ConstantExprGEP
1296 // Variables may be introduced to meet alignment requirements. No aliasing
1297 // metadata is useful for these as they have no uses. Erased before return.
1298
1299 LLVMContext &Ctx = M.getContext();
1300 const DataLayout &DL = M.getDataLayout();
1301 assert(!LDSVarsToTransform.empty());
1302
1304 LayoutFields.reserve(LDSVarsToTransform.size());
1305 {
1306 // The order of fields in this struct depends on the order of
1307 // variables in the argument which varies when changing how they
1308 // are identified, leading to spurious test breakage.
1309 auto Sorted = sortByName(std::vector<GlobalVariable *>(
1310 LDSVarsToTransform.begin(), LDSVarsToTransform.end()));
1311
1312 for (GlobalVariable *GV : Sorted) {
1314 AMDGPU::getAlign(DL, GV));
1315 LayoutFields.emplace_back(F);
1316 }
1317 }
1318
1319 performOptimizedStructLayout(LayoutFields);
1320
1321 std::vector<GlobalVariable *> LocalVars;
1322 BitVector IsPaddingField;
1323 LocalVars.reserve(LDSVarsToTransform.size()); // will be at least this large
1324 IsPaddingField.reserve(LDSVarsToTransform.size());
1325 {
1326 uint64_t CurrentOffset = 0;
1327 for (auto &F : LayoutFields) {
1328 GlobalVariable *FGV =
1329 static_cast<GlobalVariable *>(const_cast<void *>(F.Id));
1330 Align DataAlign = F.Alignment;
1331
1332 uint64_t DataAlignV = DataAlign.value();
1333 if (uint64_t Rem = CurrentOffset % DataAlignV) {
1334 uint64_t Padding = DataAlignV - Rem;
1335
1336 // Append an array of padding bytes to meet alignment requested
1337 // Note (o + (a - (o % a)) ) % a == 0
1338 // (offset + Padding ) % align == 0
1339
1340 Type *ATy = ArrayType::get(Type::getInt8Ty(Ctx), Padding);
1341 LocalVars.push_back(new GlobalVariable(
1342 M, ATy, false, GlobalValue::InternalLinkage,
1344 AMDGPUAS::LOCAL_ADDRESS, false));
1345 IsPaddingField.push_back(true);
1346 CurrentOffset += Padding;
1347 }
1348
1349 LocalVars.push_back(FGV);
1350 IsPaddingField.push_back(false);
1351 CurrentOffset += F.Size;
1352 }
1353 }
1354
1355 std::vector<Type *> LocalVarTypes;
1356 LocalVarTypes.reserve(LocalVars.size());
1357 std::transform(
1358 LocalVars.cbegin(), LocalVars.cend(), std::back_inserter(LocalVarTypes),
1359 [](const GlobalVariable *V) -> Type * { return V->getValueType(); });
1360
1361 StructType *LDSTy = StructType::create(Ctx, LocalVarTypes, VarName + ".t");
1362
1363 Align StructAlign = AMDGPU::getAlign(DL, LocalVars[0]);
1364
1365 GlobalVariable *SGV = new GlobalVariable(
1366 M, LDSTy, false, GlobalValue::InternalLinkage, PoisonValue::get(LDSTy),
1368 false);
1369 SGV->setAlignment(StructAlign);
1370
1372 Type *I32 = Type::getInt32Ty(Ctx);
1373 for (size_t I = 0; I < LocalVars.size(); I++) {
1374 GlobalVariable *GV = LocalVars[I];
1375 Constant *GEPIdx[] = {ConstantInt::get(I32, 0), ConstantInt::get(I32, I)};
1377 DL, LDSTy, SGV, GEPIdx, GEPNoWrapFlags::inBounds());
1378 if (IsPaddingField[I]) {
1379 assert(GV->use_empty());
1380 GV->eraseFromParent();
1381 } else {
1382 Map[GV] = GEP;
1383 }
1384 }
1385 assert(Map.size() == LDSVarsToTransform.size());
1386 return {SGV, std::move(Map)};
1387 }
1388
1389 template <typename PredicateTy>
1390 static void replaceLDSVariablesWithStruct(
1391 Module &M, DenseSet<GlobalVariable *> const &LDSVarsToTransformArg,
1392 const LDSVariableReplacement &Replacement, PredicateTy Predicate) {
1393 LLVMContext &Ctx = M.getContext();
1394 const DataLayout &DL = M.getDataLayout();
1395
1396 // A hack... we need to insert the aliasing info in a predictable order for
1397 // lit tests. Would like to have them in a stable order already, ideally the
1398 // same order they get allocated, which might mean an ordered set container
1399 auto LDSVarsToTransform = sortByName(std::vector<GlobalVariable *>(
1400 LDSVarsToTransformArg.begin(), LDSVarsToTransformArg.end()));
1401
1402 // Create alias.scope and their lists. Each field in the new structure
1403 // does not alias with all other fields.
1404 SmallVector<MDNode *> AliasScopes;
1405 SmallVector<Metadata *> NoAliasList;
1406 const size_t NumberVars = LDSVarsToTransform.size();
1407 if (NumberVars > 1) {
1408 MDBuilder MDB(Ctx);
1409 AliasScopes.reserve(NumberVars);
1411 for (size_t I = 0; I < NumberVars; I++) {
1413 AliasScopes.push_back(Scope);
1414 }
1415 NoAliasList.append(&AliasScopes[1], AliasScopes.end());
1416 }
1417
1418 // Replace uses of ith variable with a constantexpr to the corresponding
1419 // field of the instance that will be allocated by AMDGPUMachineFunctionInfo
1420 for (size_t I = 0; I < NumberVars; I++) {
1421 GlobalVariable *GV = LDSVarsToTransform[I];
1422 Constant *GEP = Replacement.LDSVarsToConstantGEP.at(GV);
1423
1425
1426 APInt APOff(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1427 GEP->stripAndAccumulateInBoundsConstantOffsets(DL, APOff);
1428 uint64_t Offset = APOff.getZExtValue();
1429
1430 Align A =
1431 commonAlignment(Replacement.SGV->getAlign().valueOrOne(), Offset);
1432
1433 if (I)
1434 NoAliasList[I - 1] = AliasScopes[I - 1];
1435 MDNode *NoAlias =
1436 NoAliasList.empty() ? nullptr : MDNode::get(Ctx, NoAliasList);
1437 MDNode *AliasScope =
1438 AliasScopes.empty() ? nullptr : MDNode::get(Ctx, {AliasScopes[I]});
1439
1440 refineUsesAlignmentAndAA(GEP, A, DL, AliasScope, NoAlias);
1441 }
1442 }
1443
1444 static void refineUsesAlignmentAndAA(Value *Ptr, Align A,
1445 const DataLayout &DL, MDNode *AliasScope,
1446 MDNode *NoAlias, unsigned MaxDepth = 5) {
1447 if (!MaxDepth || (A == 1 && !AliasScope))
1448 return;
1449
1450 for (User *U : Ptr->users()) {
1451 if (auto *I = dyn_cast<Instruction>(U)) {
1452 if (AliasScope && I->mayReadOrWriteMemory()) {
1453 MDNode *AS = I->getMetadata(LLVMContext::MD_alias_scope);
1454 AS = (AS ? MDNode::getMostGenericAliasScope(AS, AliasScope)
1455 : AliasScope);
1456 I->setMetadata(LLVMContext::MD_alias_scope, AS);
1457
1458 MDNode *NA = I->getMetadata(LLVMContext::MD_noalias);
1459
1460 // Scoped aliases can originate from two different domains.
1461 // First domain would be from LDS domain (created by this pass).
1462 // All entries (LDS vars) into LDS struct will have same domain.
1463
1464 // Second domain could be existing scoped aliases that are the
1465 // results of noalias params and subsequent optimizations that
1466 // may alter thesse sets.
1467
1468 // We need to be careful how we create new alias sets, and
1469 // have right scopes and domains for loads/stores of these new
1470 // LDS variables. We intersect NoAlias set if alias sets belong
1471 // to the same domain. This is the case if we have memcpy using
1472 // LDS variables. Both src and dst of memcpy would belong to
1473 // LDS struct, they donot alias.
1474 // On the other hand, if one of the domains is LDS and other is
1475 // existing domain prior to LDS, we need to have a union of all
1476 // these aliases set to preserve existing aliasing information.
1477
1478 SmallPtrSet<const MDNode *, 16> ExistingDomains, LDSDomains;
1481 auto Intersection = set_intersection(ExistingDomains, LDSDomains);
1482 if (Intersection.empty()) {
1483 NA = NA ? MDNode::concatenate(NA, NoAlias) : NoAlias;
1484 } else {
1485 NA = NA ? MDNode::intersect(NA, NoAlias) : NoAlias;
1486 }
1487 I->setMetadata(LLVMContext::MD_noalias, NA);
1488 }
1489 }
1490
1491 if (auto *LI = dyn_cast<LoadInst>(U)) {
1492 LI->setAlignment(std::max(A, LI->getAlign()));
1493 continue;
1494 }
1495 if (auto *SI = dyn_cast<StoreInst>(U)) {
1496 if (SI->getPointerOperand() == Ptr)
1497 SI->setAlignment(std::max(A, SI->getAlign()));
1498 continue;
1499 }
1500 if (auto *AI = dyn_cast<AtomicRMWInst>(U)) {
1501 // None of atomicrmw operations can work on pointers, but let's
1502 // check it anyway in case it will or we will process ConstantExpr.
1503 if (AI->getPointerOperand() == Ptr)
1504 AI->setAlignment(std::max(A, AI->getAlign()));
1505 continue;
1506 }
1507 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(U)) {
1508 if (AI->getPointerOperand() == Ptr)
1509 AI->setAlignment(std::max(A, AI->getAlign()));
1510 continue;
1511 }
1512 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
1513 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1514 APInt Off(BitWidth, 0);
1515 if (GEP->getPointerOperand() == Ptr) {
1516 Align GA;
1517 if (GEP->accumulateConstantOffset(DL, Off))
1518 GA = commonAlignment(A, Off.getLimitedValue());
1519 refineUsesAlignmentAndAA(GEP, GA, DL, AliasScope, NoAlias,
1520 MaxDepth - 1);
1521 }
1522 continue;
1523 }
1524 if (auto *I = dyn_cast<Instruction>(U)) {
1525 if (I->getOpcode() == Instruction::BitCast ||
1526 I->getOpcode() == Instruction::AddrSpaceCast)
1527 refineUsesAlignmentAndAA(I, A, DL, AliasScope, NoAlias, MaxDepth - 1);
1528 }
1529 }
1530 }
1531};
1532
1533class AMDGPULowerModuleLDSLegacy : public ModulePass {
1534public:
1535 const AMDGPUTargetMachine *TM;
1536 static char ID;
1537
1538 AMDGPULowerModuleLDSLegacy(const AMDGPUTargetMachine *TM = nullptr)
1539 : ModulePass(ID), TM(TM) {}
1540
1541 void getAnalysisUsage(AnalysisUsage &AU) const override {
1542 if (!TM)
1544 }
1545
1546 bool runOnModule(Module &M) override {
1547 if (!TM) {
1548 auto &TPC = getAnalysis<TargetPassConfig>();
1549 TM = &TPC.getTM<AMDGPUTargetMachine>();
1550 }
1551
1552 return AMDGPULowerModuleLDS(*TM).runOnModule(M);
1553 }
1554};
1555
1556} // namespace
1557char AMDGPULowerModuleLDSLegacy::ID = 0;
1558
1559char &llvm::AMDGPULowerModuleLDSLegacyPassID = AMDGPULowerModuleLDSLegacy::ID;
1560
1561INITIALIZE_PASS_BEGIN(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1562 "Lower uses of LDS variables from non-kernel functions",
1563 false, false)
1565INITIALIZE_PASS_END(AMDGPULowerModuleLDSLegacy, DEBUG_TYPE,
1566 "Lower uses of LDS variables from non-kernel functions",
1568
1569ModulePass *
1571 return new AMDGPULowerModuleLDSLegacy(TM);
1572}
1573
1576 return AMDGPULowerModuleLDS(TM).runOnModule(M) ? PreservedAnalyses::none()
1578}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t 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 ...
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.
const AMDGPUOptions & getCLOpts() const
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
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:548
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH 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:1477
This is an important base class in LLVM.
Definition Constant.h:44
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
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
static GEPNoWrapFlags inBounds()
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
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
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:2984
bool runOnModule(Module &) override
ImmutablePasses are never run.
Definition Pass.h:300
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
MDNode * createAnonymousAliasScope(MDNode *Domain, StringRef Name=StringRef())
Return metadata appropriate for an alias scope root node.
Definition MDBuilder.h:195
LLVM_ABI MDNode * createAnonymousAliasScopeDomain(StringRef Description=StringRef(), bool DisjointScopes=false)
Return metadata appropriate for an alias scope domain node, described by Description,...
Metadata node.
Definition Metadata.h:1081
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:1579
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
bool empty() const
Definition MapVector.h:80
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
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:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A tuple of MDNodes.
Definition Metadata.h:1797
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:887
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
static LLVM_ABI void collectScopedDomains(const MDNode *NoAlias, SmallPtrSetImpl< const MDNode * > &Domains, bool DisjointOnly=false)
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:662
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:299
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:297
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:512
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
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:556
iterator_range< use_iterator > uses()
Definition Value.h:382
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
bool erase(const ValueT &V)
Definition DenseSet.h:98
size_type size() const
Definition DenseSet.h:85
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:188
A raw_ostream that writes to an std::string.
@ 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.
MapVector< Function *, DenseSet< GlobalVariable * > > FunctionVariableMap
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.
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:649
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:1762
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:1652
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
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:206
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:193
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:82