LLVM 24.0.0git
SPIRVLowerDynamicLocalMemory.cpp
Go to the documentation of this file.
1//===- SPIRVLowerDynamicLocalMemory.cpp - Lower dynamic local memory ------===//
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// Dynamic local memory, i.e. an unsized external Workgroup array such as
10// CUDA's `extern __shared__ T Buf[]`, has a size only known at launch. OpenCL
11// and Level Zero runtimes cannot specify the size of such an array and instead
12// they rely on `ptr addrspace(3)` kernel arguments to provide such memory.
13//
14// This pass appends a `ptr addrspace(3)` parameter to every kernel of a module
15// referencing dynamic local memory. Each kernel stores the parameter into an
16// internal Workgroup variable on entry, and every use of the dynamic local
17// memory is replaced with a load of that variable. All declarations of dynamic
18// local memory alias the same memory, as in CUDA.
19//
20// Going through a variable rather than threading the pointer through every
21// function keeps indirect calls and functions shared between kernels working.
22// The first work-item stores the value, then a workgroup barrier makes it
23// visible to every work-item before any loads. All kernels get the parameter,
24// whether they access the memory or not, so the runtime can treat the kernels
25// of a module alike.
26//
27// The lowering changes the kernel signatures, so it is limited to
28// triples with an OpenCL or unknown OS whose runtime sets the argument.
29//
30//===----------------------------------------------------------------------===//
31
32#include "SPIRV.h"
33#include "SPIRVTargetMachine.h"
34#include "SPIRVUtils.h"
35#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/Twine.h"
38#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/IntrinsicsSPIRV.h"
41#include "llvm/IR/Module.h"
43#include "llvm/Pass.h"
45#include "llvm/Support/ModRef.h"
48
49#define DEBUG_TYPE "spirv-lower-dynamic-local-memory"
50
51using namespace llvm;
52
53namespace {
54
55/// Returns whether \p GV is dynamic local memory: an external Workgroup array
56/// without a size.
57bool isDynamicLocalMemory(const GlobalVariable &GV) {
58 if (!GV.isDeclaration() ||
59 GV.getAddressSpace() !=
60 storageClassToAddressSpace(SPIRV::StorageClass::Workgroup))
61 return false;
62 const auto *ArrTy = dyn_cast<ArrayType>(GV.getValueType());
63 return ArrTy && ArrTy->getNumElements() == 0;
64}
65
66/// Replaces the kernel \p F with a copy taking an additional trailing
67/// parameter of type \p ParamTy, and returns the copy. Kernels cannot be
68/// called, so only their other uses need updating.
69Function *appendKernelParam(Function &F, Type *ParamTy) {
70 FunctionType *OldTy = F.getFunctionType();
71 SmallVector<Type *> Params(OldTy->params());
72 Params.push_back(ParamTy);
73 FunctionType *NewTy =
74 FunctionType::get(OldTy->getReturnType(), Params, OldTy->isVarArg());
75
76 Function *NewF = Function::Create(NewTy, F.getLinkage(), F.getAddressSpace());
77 F.getParent()->getFunctionList().insert(F.getIterator(), NewF);
78 NewF->copyAttributesFrom(&F);
79 NewF->setComdat(F.getComdat());
80 NewF->copyMetadata(&F, 0);
81 NewF->splice(NewF->begin(), &F);
82 for (auto [OldArg, NewArg] : zip(F.args(), NewF->args())) {
83 OldArg.replaceAllUsesWith(&NewArg);
84 NewArg.takeName(&OldArg);
85 }
86 NewF->getArg(NewF->arg_size() - 1)->setName("dyn_local_mem");
87
88 NewF->takeName(&F);
89 F.replaceAllUsesWith(NewF);
90 F.eraseFromParent();
91 return NewF;
92}
93
94void updateMemoryEffects(Function *F, MemoryEffects NewEffects) {
97 Worklist.push_back(F);
98
99 while (!Worklist.empty()) {
100 Function *Current = Worklist.pop_back_val();
101
102 // Record visited functions, skip if function was
103 // already processed.
104 if (!Visited.insert(Current).second)
105 continue;
106
107 Current->setMemoryEffects(Current->getMemoryEffects() | NewEffects);
108
109 // Add callers of the function into worklist
110 for (auto &U : Current->uses()) {
111 if (auto *CB = dyn_cast<CallBase>(U.getUser())) {
112 if (CB->isCallee(&U)) {
113 auto *Caller = CB->getCaller();
114 Worklist.push_back(Caller);
115
116 // Update call instruction with new effects
117 CB->setMemoryEffects(CB->getMemoryEffects() | NewEffects);
118 }
119 }
120 }
121 }
122}
123
124bool lowerDynamicLocalMemory(Module &M, const SPIRVTargetMachine &TM) {
125 // Shaders have no kernel arguments, so the pass is disabled.
126 // It is only used for OpenCL/Level Zero runtimes, because they
127 // have no API to size extern workgroup array.
128 // UnknownOS implies OpenCL
129 // https://llvm.org/docs/SPIRVUsage.html#target-triples.
130 if (TM.getSubtargetImpl()->isShader() ||
131 (M.getTargetTriple().getOS() != Triple::UnknownOS &&
132 M.getTargetTriple().getOS() != Triple::OpenCL))
133 return false;
134
135 // The frontend opts in for languages whose runtime sets the argument.
137 M.getModuleFlag("spirv-dynamic-local-memory"));
138 if (!Enable || Enable->isZero())
139 return false;
140
142 for (GlobalVariable &GV : M.globals())
143 if (isDynamicLocalMemory(GV) && !GV.use_empty())
144 DynMems.push_back(&GV);
145 if (DynMems.empty())
146 return false;
147
149 for (Function &F : M)
150 if (!F.isDeclaration() && F.getCallingConv() == CallingConv::SPIR_KERNEL)
151 Kernels.push_back(&F);
152 // Leave the memory to be resolved by linking with a module defining kernels.
153 if (Kernels.empty())
154 return false;
155
156 unsigned LocalAS = storageClassToAddressSpace(SPIRV::StorageClass::Workgroup);
157 auto *LocalPtrTy = PointerType::get(M.getContext(), LocalAS);
158 auto *Slot = new GlobalVariable(
159 M, LocalPtrTy, /*isConstant=*/false, GlobalValue::InternalLinkage,
160 PoisonValue::get(LocalPtrTy), "__spirv_dynamic_local_memory",
161 /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal, LocalAS);
162 Slot->setAlignment(M.getDataLayout().getPointerABIAlignment(LocalAS));
163 Slot->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
164
165 // Marker detected by the Level Zero plugin to add SLM argument.
166 auto *MarkerTy = Type::getInt8Ty(M.getContext());
167 new GlobalVariable(
168 M, MarkerTy, /*isConstant=*/true, GlobalValue::ExternalLinkage,
169 ConstantInt::get(MarkerTy, 1), "__spirv_dynamic_local_memory_present",
170 /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,
171 storageClassToAddressSpace(SPIRV::StorageClass::CrossWorkgroup));
172
173 // Replace the uses of the memory, which must all be in instructions.
174 SmallVector<Constant *> DynMemConsts(DynMems.begin(), DynMems.end());
176 for (GlobalVariable *GV : DynMems) {
178 for (Use &U : GV->uses()) {
179 auto *I = dyn_cast<Instruction>(U.getUser());
180 if (!I)
181 reportFatalUsageError("dynamic local memory '" + GV->getName() +
182 "' cannot be referenced by a constant");
183
184 Function *F = I->getFunction();
185 UsesOfGV[F].push_back(&U);
186 }
187
188 for (auto &[F, Uses] : UsesOfGV) {
189 IRBuilder<> Builder(F->getEntryBlock().getFirstNonPHIOrAlloca());
190 auto *LoadedSlot = Builder.CreateLoad(LocalPtrTy, Slot, "dyn_local_mem");
191
192 for (Use *U : Uses)
193 U->set(LoadedSlot);
194
195 // Modify memory effects of the function and its callers, a function that
196 // would reference SLM pointer might have ModRefInfo::NoModRef, but
197 // adding the load requires changing it to at least ModRefInfo::Ref.
198 updateMemoryEffects(F, MemoryEffects::otherMemOnly(ModRefInfo::Ref));
199 }
200
201 GV->eraseFromParent();
202 }
203
204 // Give every kernel the memory as an argument stored on entry.
205 for (Function *F : Kernels) {
206 Function *NewF = appendKernelParam(*F, LocalPtrTy);
207 Instruction *InsertBefore =
209 IRBuilder<> Builder(InsertBefore);
210
211 // Only thread [0][0][0] performs the store
212 Type *ThreadIdTy = M.getDataLayout().getIntPtrType(M.getContext(), LocalAS);
213 Value *IsFirst = Builder.getTrue();
214 for (unsigned Dim = 0; Dim != 3; ++Dim) {
215 // Get thread ID and check if it's zero
216 Value *ThreadId =
217 Builder.CreateIntrinsic(Intrinsic::spv_thread_id_in_group,
218 {ThreadIdTy}, {Builder.getInt32(Dim)});
219 IsFirst = Builder.CreateAnd(
220 IsFirst,
221 Builder.CreateICmpEQ(ThreadId, ConstantInt::get(ThreadIdTy, 0)));
222 }
223 Instruction *ThenTerm =
224 SplitBlockAndInsertIfThen(IsFirst, InsertBefore, false);
225
226 // Insert store on thread [0][0][0]
227 Builder.SetInsertPoint(ThenTerm);
228 Builder.CreateStore(NewF->getArg(NewF->arg_size() - 1), Slot);
229
230 // All threads do workgroup barrier
231 Builder.SetInsertPoint(InsertBefore);
232 Builder.CreateIntrinsic(Intrinsic::spv_group_memory_barrier_with_group_sync,
233 {});
234
235 NewF->setMemoryEffects(NewF->getMemoryEffects() |
237 }
238
239 return true;
240}
241
242class SPIRVLowerDynamicLocalMemoryLegacy : public ModulePass {
243public:
244 static char ID;
245 SPIRVLowerDynamicLocalMemoryLegacy(const SPIRVTargetMachine &TM)
246 : ModulePass(ID), TM(TM) {}
247
248 StringRef getPassName() const override {
249 return "SPIRV lower dynamic local memory";
250 }
251
252 bool runOnModule(Module &M) override {
253 return lowerDynamicLocalMemory(M, TM);
254 }
255
256private:
257 const SPIRVTargetMachine &TM;
258};
259
260} // namespace
261
264 return lowerDynamicLocalMemory(M, TM) ? PreservedAnalyses::none()
266}
267
268char SPIRVLowerDynamicLocalMemoryLegacy::ID = 0;
269
270INITIALIZE_PASS(SPIRVLowerDynamicLocalMemoryLegacy,
271 "spirv-lower-dynamic-local-memory",
272 "Lower SPIR-V dynamic local memory to kernel arguments", false,
273 false)
274
277 return new SPIRVLowerDynamicLocalMemoryLegacy(TM);
278}
aarch64 promote const
This file defines the DenseMap class.
@ Enable
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Remove Loads Into Fake Uses
This file defines the SmallVector class.
LLVM_ABI const_iterator getFirstNonPHIOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a static alloca,...
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:755
const BasicBlock & getEntryBlock() const
Definition Function.h:803
iterator_range< arg_iterator > args()
Definition Function.h:886
MemoryEffects getMemoryEffects() const
Definition Function.cpp:862
iterator begin()
Definition Function.h:847
size_t arg_size() const
Definition Function.h:895
void setMemoryEffects(MemoryEffects ME)
Definition Function.cpp:865
Argument * getArg(unsigned i) const
Definition Function.h:880
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:846
LLVM_ABI void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
unsigned getAddressSpace() const
@ 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 eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:159
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
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:882
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
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const SPIRVSubtarget * getSubtargetImpl() const
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.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
@ SPIR_KERNEL
Used for SPIR kernel functions.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:695
This is an optimization pass for GlobalISel generic memory operations.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
Definition SPIRVUtils.h:234
LLVM_ABI bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts, Function *RestrictToFunc=nullptr, bool RemoveDeadConstants=true, bool IncludeSelf=false)
Replace constant expressions users of the given constants with instructions.
ModulePass * createSPIRVLowerDynamicLocalMemoryPass(const SPIRVTargetMachine &TM)
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
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