LLVM 19.0.0git
AMDGPUMemoryUtils.cpp
Go to the documentation of this file.
1//===-- AMDGPUMemoryUtils.cpp - -------------------------------------------===//
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#include "AMDGPUMemoryUtils.h"
10#include "AMDGPU.h"
11#include "AMDGPUBaseInfo.h"
13#include "llvm/ADT/SmallSet.h"
17#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/IntrinsicsAMDGPU.h"
21#include "llvm/IR/Operator.h"
23
24#define DEBUG_TYPE "amdgpu-memory-utils"
25
26using namespace llvm;
27
28namespace llvm {
29
30namespace AMDGPU {
31
33 return DL.getValueOrABITypeAlignment(GV->getPointerAlignment(DL),
34 GV->getValueType());
35}
36
38 // external zero size addrspace(3) without initializer is dynlds.
39 const Module *M = GV.getParent();
40 const DataLayout &DL = M->getDataLayout();
42 return false;
43 return DL.getTypeAllocSize(GV.getValueType()) == 0;
44}
45
48 return false;
49 }
50 if (isDynamicLDS(GV)) {
51 return true;
52 }
53 if (GV.isConstant()) {
54 // A constant undef variable can't be written to, and any load is
55 // undef, so it should be eliminated by the optimizer. It could be
56 // dropped by the back end if not. This pass skips over it.
57 return false;
58 }
59 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
60 // Initializers are unimplemented for LDS address space.
61 // Leave such variables in place for consistent error reporting.
62 return false;
63 }
64 return true;
65}
66
68 // Constants are uniqued within LLVM. A ConstantExpr referring to a LDS
69 // global may have uses from multiple different functions as a result.
70 // This pass specialises LDS variables with respect to the kernel that
71 // allocates them.
72
73 // This is semantically equivalent to (the unimplemented as slow):
74 // for (auto &F : M.functions())
75 // for (auto &BB : F)
76 // for (auto &I : BB)
77 // for (Use &Op : I.operands())
78 // if (constantExprUsesLDS(Op))
79 // replaceConstantExprInFunction(I, Op);
80
81 SmallVector<Constant *> LDSGlobals;
82 for (auto &GV : M.globals())
84 LDSGlobals.push_back(&GV);
86}
87
89 FunctionVariableMap &kernels,
90 FunctionVariableMap &Functions) {
91 // Get uses from the current function, excluding uses by called Functions
92 // Two output variables to avoid walking the globals list twice
93 for (auto &GV : M.globals()) {
95 continue;
96 for (User *V : GV.users()) {
97 if (auto *I = dyn_cast<Instruction>(V)) {
98 Function *F = I->getFunction();
99 if (isKernelLDS(F))
100 kernels[F].insert(&GV);
101 else
102 Functions[F].insert(&GV);
103 }
104 }
105 }
106}
107
108bool isKernelLDS(const Function *F) {
109 // Some weirdness here. AMDGPU::isKernelCC does not call into
110 // AMDGPU::isKernel with the calling conv, it instead calls into
111 // isModuleEntryFunction which returns true for more calling conventions
112 // than AMDGPU::isKernel does. There's a FIXME on AMDGPU::isKernel.
113 // There's also a test that checks that the LDS lowering does not hit on
114 // a graphics shader, denoted amdgpu_ps, so stay with the limited case.
115 // Putting LDS in the name of the function to draw attention to this.
116 return AMDGPU::isKernel(F->getCallingConv());
117}
118
120
121 FunctionVariableMap DirectMapKernel;
122 FunctionVariableMap DirectMapFunction;
123 getUsesOfLDSByFunction(CG, M, DirectMapKernel, DirectMapFunction);
124
125 // Collect variables that are used by functions whose address has escaped
126 DenseSet<GlobalVariable *> VariablesReachableThroughFunctionPointer;
127 for (Function &F : M.functions()) {
128 if (!isKernelLDS(&F))
129 if (F.hasAddressTaken(nullptr,
130 /* IgnoreCallbackUses */ false,
131 /* IgnoreAssumeLikeCalls */ false,
132 /* IgnoreLLVMUsed */ true,
133 /* IgnoreArcAttachedCall */ false)) {
134 set_union(VariablesReachableThroughFunctionPointer,
135 DirectMapFunction[&F]);
136 }
137 }
138
139 auto FunctionMakesUnknownCall = [&](const Function *F) -> bool {
140 assert(!F->isDeclaration());
141 for (const CallGraphNode::CallRecord &R : *CG[F]) {
142 if (!R.second->getFunction())
143 return true;
144 }
145 return false;
146 };
147
148 // Work out which variables are reachable through function calls
149 FunctionVariableMap TransitiveMapFunction = DirectMapFunction;
150
151 // If the function makes any unknown call, assume the worst case that it can
152 // access all variables accessed by functions whose address escaped
153 for (Function &F : M.functions()) {
154 if (!F.isDeclaration() && FunctionMakesUnknownCall(&F)) {
155 if (!isKernelLDS(&F)) {
156 set_union(TransitiveMapFunction[&F],
157 VariablesReachableThroughFunctionPointer);
158 }
159 }
160 }
161
162 // Direct implementation of collecting all variables reachable from each
163 // function
164 for (Function &Func : M.functions()) {
165 if (Func.isDeclaration() || isKernelLDS(&Func))
166 continue;
167
168 DenseSet<Function *> seen; // catches cycles
169 SmallVector<Function *, 4> wip = {&Func};
170
171 while (!wip.empty()) {
172 Function *F = wip.pop_back_val();
173
174 // Can accelerate this by referring to transitive map for functions that
175 // have already been computed, with more care than this
176 set_union(TransitiveMapFunction[&Func], DirectMapFunction[F]);
177
178 for (const CallGraphNode::CallRecord &R : *CG[F]) {
179 Function *Ith = R.second->getFunction();
180 if (Ith) {
181 if (!seen.contains(Ith)) {
182 seen.insert(Ith);
183 wip.push_back(Ith);
184 }
185 }
186 }
187 }
188 }
189
190 // DirectMapKernel lists which variables are used by the kernel
191 // find the variables which are used through a function call
192 FunctionVariableMap IndirectMapKernel;
193
194 for (Function &Func : M.functions()) {
195 if (Func.isDeclaration() || !isKernelLDS(&Func))
196 continue;
197
198 for (const CallGraphNode::CallRecord &R : *CG[&Func]) {
199 Function *Ith = R.second->getFunction();
200 if (Ith) {
201 set_union(IndirectMapKernel[&Func], TransitiveMapFunction[Ith]);
202 } else {
203 set_union(IndirectMapKernel[&Func],
204 VariablesReachableThroughFunctionPointer);
205 }
206 }
207 }
208
209 // Verify that we fall into one of 2 cases:
210 // - All variables are absolute: this is a re-run of the pass
211 // so we don't have anything to do.
212 // - No variables are absolute.
213 std::optional<bool> HasAbsoluteGVs;
214 for (auto &Map : {DirectMapKernel, IndirectMapKernel}) {
215 for (auto &[Fn, GVs] : Map) {
216 for (auto *GV : GVs) {
217 bool IsAbsolute = GV->isAbsoluteSymbolRef();
218 if (HasAbsoluteGVs.has_value()) {
219 if (*HasAbsoluteGVs != IsAbsolute) {
221 "Module cannot mix absolute and non-absolute LDS GVs");
222 }
223 } else
224 HasAbsoluteGVs = IsAbsolute;
225 }
226 }
227 }
228
229 // If we only had absolute GVs, we have nothing to do, return an empty
230 // result.
231 if (HasAbsoluteGVs && *HasAbsoluteGVs)
233
234 return {std::move(DirectMapKernel), std::move(IndirectMapKernel)};
235}
236
239 KernelRoot->removeFnAttr(FnAttr);
240
241 SmallVector<Function *> WorkList = {CG[KernelRoot]->getFunction()};
243 bool SeenUnknownCall = false;
244
245 while (!WorkList.empty()) {
246 Function *F = WorkList.pop_back_val();
247
248 for (auto &CallRecord : *CG[F]) {
249 if (!CallRecord.second)
250 continue;
251
252 Function *Callee = CallRecord.second->getFunction();
253 if (!Callee) {
254 if (!SeenUnknownCall) {
255 SeenUnknownCall = true;
256
257 // If we see any indirect calls, assume nothing about potential
258 // targets.
259 // TODO: This could be refined to possible LDS global users.
260 for (auto &ExternalCallRecord : *CG.getExternalCallingNode()) {
261 Function *PotentialCallee =
262 ExternalCallRecord.second->getFunction();
263 assert(PotentialCallee);
264 if (!isKernelLDS(PotentialCallee))
265 PotentialCallee->removeFnAttr(FnAttr);
266 }
267 }
268 } else {
269 Callee->removeFnAttr(FnAttr);
270 if (Visited.insert(Callee).second)
271 WorkList.push_back(Callee);
272 }
273 }
274 }
275}
276
278 Instruction *DefInst = Def->getMemoryInst();
279
280 if (isa<FenceInst>(DefInst))
281 return false;
282
283 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
284 switch (II->getIntrinsicID()) {
285 case Intrinsic::amdgcn_s_barrier:
286 case Intrinsic::amdgcn_s_barrier_signal:
287 case Intrinsic::amdgcn_s_barrier_signal_var:
288 case Intrinsic::amdgcn_s_barrier_signal_isfirst:
289 case Intrinsic::amdgcn_s_barrier_signal_isfirst_var:
290 case Intrinsic::amdgcn_s_barrier_init:
291 case Intrinsic::amdgcn_s_barrier_join:
292 case Intrinsic::amdgcn_s_barrier_wait:
293 case Intrinsic::amdgcn_s_barrier_leave:
294 case Intrinsic::amdgcn_s_get_barrier_state:
295 case Intrinsic::amdgcn_s_wakeup_barrier:
296 case Intrinsic::amdgcn_wave_barrier:
297 case Intrinsic::amdgcn_sched_barrier:
298 case Intrinsic::amdgcn_sched_group_barrier:
299 return false;
300 default:
301 break;
302 }
303 }
304
305 // Ignore atomics not aliasing with the original load, any atomic is a
306 // universal MemoryDef from MSSA's point of view too, just like a fence.
307 const auto checkNoAlias = [AA, Ptr](auto I) -> bool {
308 return I && AA->isNoAlias(I->getPointerOperand(), Ptr);
309 };
310
311 if (checkNoAlias(dyn_cast<AtomicCmpXchgInst>(DefInst)) ||
312 checkNoAlias(dyn_cast<AtomicRMWInst>(DefInst)))
313 return false;
314
315 return true;
316}
317
319 AAResults *AA) {
320 MemorySSAWalker *Walker = MSSA->getWalker();
324
325 LLVM_DEBUG(dbgs() << "Checking clobbering of: " << *Load << '\n');
326
327 // Start with a nearest dominating clobbering access, it will be either
328 // live on entry (nothing to do, load is not clobbered), MemoryDef, or
329 // MemoryPhi if several MemoryDefs can define this memory state. In that
330 // case add all Defs to WorkList and continue going up and checking all
331 // the definitions of this memory location until the root. When all the
332 // defs are exhausted and came to the entry state we have no clobber.
333 // Along the scan ignore barriers and fences which are considered clobbers
334 // by the MemorySSA, but not really writing anything into the memory.
335 while (!WorkList.empty()) {
336 MemoryAccess *MA = WorkList.pop_back_val();
337 if (!Visited.insert(MA).second)
338 continue;
339
340 if (MSSA->isLiveOnEntryDef(MA))
341 continue;
342
343 if (MemoryDef *Def = dyn_cast<MemoryDef>(MA)) {
344 LLVM_DEBUG(dbgs() << " Def: " << *Def->getMemoryInst() << '\n');
345
346 if (isReallyAClobber(Load->getPointerOperand(), Def, AA)) {
347 LLVM_DEBUG(dbgs() << " -> load is clobbered\n");
348 return true;
349 }
350
351 WorkList.push_back(
352 Walker->getClobberingMemoryAccess(Def->getDefiningAccess(), Loc));
353 continue;
354 }
355
356 const MemoryPhi *Phi = cast<MemoryPhi>(MA);
357 for (const auto &Use : Phi->incoming_values())
358 WorkList.push_back(cast<MemoryAccess>(&Use));
359 }
360
361 LLVM_DEBUG(dbgs() << " -> no clobber\n");
362 return false;
363}
364
365} // end namespace AMDGPU
366
367} // end namespace llvm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
@ FnAttr
Definition: Attributes.cpp:666
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define LLVM_DEBUG(X)
Definition: Debug.h:101
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallSet class.
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are no-alias.
std::pair< std::optional< WeakTrackingVH >, CallGraphNode * > CallRecord
A pair of the calling instruction (a call or invoke) and the call graph node being called.
Definition: CallGraph.h:178
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:72
CallGraphNode * getExternalCallingNode() const
Returns the CallGraphNode which is used to represent undetermined calls into the callgraph.
Definition: CallGraph.h:127
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
const Function & getFunction() const
Definition: Function.h:162
void removeFnAttr(Attribute::AttrKind Kind)
Remove function attributes from this function.
Definition: Function.cpp:633
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:293
Type * getValueType() const
Definition: GlobalValue.h:295
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
An instruction for reading from memory.
Definition: Instructions.h:184
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition: MemorySSA.h:373
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Represents phi nodes for memory accesses.
Definition: MemorySSA.h:480
This is the generic walker interface for walkers of MemorySSA.
Definition: MemorySSA.h:1016
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition: MemorySSA.h:1045
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:701
MemorySSAWalker * getWalker()
Definition: MemorySSA.cpp:1590
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition: MemorySSA.h:739
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:179
bool empty() const
Definition: SmallVector.h:94
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
LLVM Value Representation.
Definition: Value.h:74
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:926
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
@ LOCAL_ADDRESS
Address space for local memory.
LLVM_READNONE bool isKernel(CallingConv::ID CC)
bool isDynamicLDS(const GlobalVariable &GV)
void removeFnAttrFromReachable(CallGraph &CG, Function *KernelRoot, StringRef FnAttr)
Strip FnAttr attribute from any functions where we may have introduced its use.
void getUsesOfLDSByFunction(const CallGraph &CG, Module &M, FunctionVariableMap &kernels, FunctionVariableMap &Functions)
bool isReallyAClobber(const Value *Ptr, MemoryDef *Def, AAResults *AA)
Given a Def clobbering a load from Ptr according to the MSSA check if this is actually a memory updat...
LDSUsesInfoTy getTransitiveUsesOfLDS(const CallGraph &CG, Module &M)
bool isLDSVariableToLower(const GlobalVariable &GV)
bool eliminateConstantExprUsesOfLDSFromAllInstructions(Module &M)
Align getAlign(const DataLayout &DL, const GlobalVariable *GV)
bool isKernelLDS(const Function *F)
bool isClobberedInFunction(const LoadInst *Load, MemorySSA *MSSA, AAResults *AA)
Check is a Load is clobbered in its function.
DenseMap< Function *, DenseSet< GlobalVariable * > > FunctionVariableMap
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts)
Replace constant expressions users of the given constants with instructions.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
Definition: SetOperations.h:23
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39