LLVM 23.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"
16#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/IntrinsicsAMDGPU.h"
20#include "llvm/IR/LLVMContext.h"
22
23#define DEBUG_TYPE "amdgpu-memory-utils"
24
25using namespace llvm;
26
27namespace llvm::AMDGPU {
28
30 return DL.getValueOrABITypeAlignment(GV->getPointerAlignment(DL),
31 GV->getValueType());
32}
33
34void copyMetadataForWidenedLoad(LoadInst &Dest, const LoadInst &Source) {
36 Source.getAllMetadata(MD);
37 for (const auto [ID, N] : MD) {
38 switch (ID) {
39 case LLVMContext::MD_dbg:
40 case LLVMContext::MD_invariant_load:
41 case LLVMContext::MD_nontemporal:
42 Dest.setMetadata(ID, N);
43 break;
44 default:
45 break;
46 }
47 }
48}
49
50// Returns the target extension type of a global variable,
51// which can only be a TargetExtType, an array or single-element struct of it,
52// or their nesting combination.
53// TODO: allow struct of multiple TargetExtType elements of the same type.
54// TODO: Disallow other uses of target("amdgcn.named.barrier") including:
55// - Structs containing barriers in different scope/rank
56// - Structs containing a mixture of barriers and other data.
57// - Globals in other address spaces.
58// - Allocas.
60 Type *Ty = GV.getValueType();
61 while (true) {
62 if (auto *TTy = dyn_cast<TargetExtType>(Ty))
63 return TTy;
64 if (auto *STy = dyn_cast<StructType>(Ty)) {
65 if (STy->getNumElements() != 1)
66 return nullptr;
67 Ty = STy->getElementType(0);
68 continue;
69 }
70 if (auto *ATy = dyn_cast<ArrayType>(Ty)) {
71 Ty = ATy->getElementType();
72 continue;
73 }
74 return nullptr;
75 }
76}
77
79 if (TargetExtType *Ty = getTargetExtType(GV))
80 return Ty->getName() == "amdgcn.named.barrier" ? Ty : nullptr;
81 return nullptr;
82}
83
85 // external zero size addrspace(3) without initializer is dynlds.
86 const Module *M = GV.getParent();
87 const DataLayout &DL = M->getDataLayout();
89 return false;
90 return GV.getGlobalSize(DL) == 0;
91}
92
95 return false;
96 }
97 if (isDynamicLDS(GV)) {
98 return true;
99 }
100 if (GV.isConstant()) {
101 // A constant undef variable can't be written to, and any load is
102 // undef, so it should be eliminated by the optimizer. It could be
103 // dropped by the back end if not. This pass skips over it.
104 return false;
105 }
106 if (GV.hasInitializer() && !isa<UndefValue>(GV.getInitializer())) {
107 // Initializers are unimplemented for LDS address space.
108 // Leave such variables in place for consistent error reporting.
109 return false;
110 }
111 return true;
112}
113
115 // Constants are uniqued within LLVM. A ConstantExpr referring to a LDS
116 // global may have uses from multiple different functions as a result.
117 // This pass specialises LDS variables with respect to the kernel that
118 // allocates them.
119
120 // This is semantically equivalent to (the unimplemented as slow):
121 // for (auto &F : M.functions())
122 // for (auto &BB : F)
123 // for (auto &I : BB)
124 // for (Use &Op : I.operands())
125 // if (constantExprUsesLDS(Op))
126 // replaceConstantExprInFunction(I, Op);
127
128 SmallVector<Constant *> LDSGlobals;
129 for (auto &GV : M.globals())
131 LDSGlobals.push_back(&GV);
132 return convertUsersOfConstantsToInstructions(LDSGlobals);
133}
134
136 FunctionVariableMap &kernels,
137 FunctionVariableMap &Functions) {
138 // Get uses from the current function, excluding uses by called Functions
139 // Two output variables to avoid walking the globals list twice
140 for (auto &GV : M.globals()) {
142 continue;
143 for (User *V : GV.users()) {
144 if (auto *I = dyn_cast<Instruction>(V)) {
145 Function *F = I->getFunction();
146 if (isKernel(*F))
147 kernels[F].insert(&GV);
148 else
149 Functions[F].insert(&GV);
150 }
151 }
152 }
153}
154
156
157 FunctionVariableMap DirectMapKernel;
158 FunctionVariableMap DirectMapFunction;
159 getUsesOfLDSByFunction(CG, M, DirectMapKernel, DirectMapFunction);
160
161 // Collect functions whose address has escaped
162 DenseSet<Function *> AddressTakenFuncs;
163 for (Function &F : M.functions()) {
164 if (!isKernel(F))
165 if (F.hasAddressTaken(nullptr,
166 /* IgnoreCallbackUses */ false,
167 /* IgnoreAssumeLikeCalls */ false,
168 /* IgnoreLLVMUsed */ true,
169 /* IgnoreArcAttachedCall */ false)) {
170 AddressTakenFuncs.insert(&F);
171 }
172 }
173
174 // Collect variables that are used by functions whose address has escaped
175 DenseSet<GlobalVariable *> VariablesReachableThroughFunctionPointer;
176 for (Function *F : AddressTakenFuncs) {
177 set_union(VariablesReachableThroughFunctionPointer, DirectMapFunction[F]);
178 }
179
180 auto FunctionMakesUnknownCall = [&](const Function *F) -> bool {
181 assert(!F->isDeclaration());
182 for (const CallGraphNode::CallRecord &R : *CG[F]) {
183 if (!R.second->getFunction())
184 return true;
185 }
186 return false;
187 };
188
189 // Work out which variables are reachable through function calls
190 FunctionVariableMap TransitiveMapFunction = DirectMapFunction;
191
192 // If the function makes any unknown call, assume the worst case that it can
193 // access all variables accessed by functions whose address escaped
194 for (Function &F : M.functions()) {
195 if (!F.isDeclaration() && FunctionMakesUnknownCall(&F)) {
196 if (!isKernel(F)) {
197 set_union(TransitiveMapFunction[&F],
198 VariablesReachableThroughFunctionPointer);
199 }
200 }
201 }
202
203 // Direct implementation of collecting all variables reachable from each
204 // function
205 for (Function &Func : M.functions()) {
206 if (Func.isDeclaration() || isKernel(Func))
207 continue;
208
209 DenseSet<Function *> seen; // catches cycles
210 SmallVector<Function *, 4> wip = {&Func};
211
212 while (!wip.empty()) {
213 Function *F = wip.pop_back_val();
214
215 // Can accelerate this by referring to transitive map for functions that
216 // have already been computed, with more care than this
217 set_union(TransitiveMapFunction[&Func], DirectMapFunction[F]);
218
219 for (const CallGraphNode::CallRecord &R : *CG[F]) {
220 Function *Ith = R.second->getFunction();
221 if (Ith) {
222 if (!seen.contains(Ith)) {
223 seen.insert(Ith);
224 wip.push_back(Ith);
225 }
226 }
227 }
228 }
229 }
230
231 // Collect variables that are transitively used by functions whose address has
232 // escaped
233 for (Function *F : AddressTakenFuncs) {
234 set_union(VariablesReachableThroughFunctionPointer,
235 TransitiveMapFunction[F]);
236 }
237
238 // DirectMapKernel lists which variables are used by the kernel
239 // find the variables which are used through a function call
240 FunctionVariableMap IndirectMapKernel;
241
242 for (Function &Func : M.functions()) {
243 if (Func.isDeclaration() || !isKernel(Func))
244 continue;
245
246 for (const CallGraphNode::CallRecord &R : *CG[&Func]) {
247 Function *Ith = R.second->getFunction();
248 if (Ith) {
249 set_union(IndirectMapKernel[&Func], TransitiveMapFunction[Ith]);
250 }
251 }
252
253 // Check if the kernel encounters unknows calls, wheher directly or
254 // indirectly.
255 bool SeesUnknownCalls = [&]() {
256 SmallVector<Function *> WorkList = {CG[&Func]->getFunction()};
258
259 while (!WorkList.empty()) {
260 Function *F = WorkList.pop_back_val();
261
262 for (const CallGraphNode::CallRecord &CallRecord : *CG[F]) {
263 if (!CallRecord.second)
264 continue;
265
266 Function *Callee = CallRecord.second->getFunction();
267 if (!Callee)
268 return true;
269
270 if (Visited.insert(Callee).second)
271 WorkList.push_back(Callee);
272 }
273 }
274 return false;
275 }();
276
277 if (SeesUnknownCalls) {
278 set_union(IndirectMapKernel[&Func],
279 VariablesReachableThroughFunctionPointer);
280 }
281 }
282
283 // Verify that we fall into one of 2 cases:
284 // - All variables are either absolute
285 // or direct mapped dynamic LDS that is not lowered.
286 // this is a re-run of the pass
287 // so we don't have anything to do.
288 // - No variables are absolute.
289 // Named-barriers which are absolute symbols are removed
290 // from the maps.
291 std::optional<bool> HasAbsoluteGVs;
292 bool HasSpecialGVs = false;
293 for (auto &Map : {DirectMapKernel, IndirectMapKernel}) {
294 for (auto &[Fn, GVs] : Map) {
295 for (auto *GV : GVs) {
296 bool IsAbsolute = GV->isAbsoluteSymbolRef();
297 bool IsDirectMapDynLDSGV =
298 AMDGPU::isDynamicLDS(*GV) && DirectMapKernel.contains(Fn);
299 if (IsDirectMapDynLDSGV)
300 continue;
301 if (isNamedBarrier(*GV)) {
302 if (IsAbsolute) {
303 DirectMapKernel[Fn].erase(GV);
304 IndirectMapKernel[Fn].erase(GV);
305 }
306 HasSpecialGVs = true;
307 continue;
308 }
309 if (HasAbsoluteGVs.has_value()) {
310 if (*HasAbsoluteGVs != IsAbsolute) {
312 "module cannot mix absolute and non-absolute LDS GVs");
313 }
314 } else
315 HasAbsoluteGVs = IsAbsolute;
316 }
317 }
318 }
319
320 // If we only had absolute GVs, we have nothing to do, return an empty
321 // result.
322 if (HasAbsoluteGVs && *HasAbsoluteGVs)
323 return {FunctionVariableMap(), FunctionVariableMap(), false};
324
325 return {std::move(DirectMapKernel), std::move(IndirectMapKernel),
326 HasSpecialGVs};
327}
328
330 ArrayRef<StringRef> FnAttrs) {
331 for (StringRef Attr : FnAttrs)
332 KernelRoot->removeFnAttr(Attr);
333
334 SmallVector<Function *> WorkList = {CG[KernelRoot]->getFunction()};
336 bool SeenUnknownCall = false;
337
338 while (!WorkList.empty()) {
339 Function *F = WorkList.pop_back_val();
340
341 for (auto &CallRecord : *CG[F]) {
342 if (!CallRecord.second)
343 continue;
344
345 Function *Callee = CallRecord.second->getFunction();
346 if (!Callee) {
347 if (!SeenUnknownCall) {
348 SeenUnknownCall = true;
349
350 // If we see any indirect calls, assume nothing about potential
351 // targets.
352 // TODO: This could be refined to possible LDS global users.
353 for (auto &ExternalCallRecord : *CG.getExternalCallingNode()) {
354 Function *PotentialCallee =
355 ExternalCallRecord.second->getFunction();
356 assert(PotentialCallee);
357 if (!isKernel(*PotentialCallee)) {
358 for (StringRef Attr : FnAttrs)
359 PotentialCallee->removeFnAttr(Attr);
360 }
361 }
362 }
363 } else {
364 for (StringRef Attr : FnAttrs)
365 Callee->removeFnAttr(Attr);
366 if (Visited.insert(Callee).second)
367 WorkList.push_back(Callee);
368 }
369 }
370 }
371}
372
373bool isReallyAClobber(const Value *Ptr, MemoryDef *Def, AAResults *AA) {
374 Instruction *DefInst = Def->getMemoryInst();
375
376 if (isa<FenceInst>(DefInst))
377 return false;
378
379 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
380 switch (II->getIntrinsicID()) {
381 case Intrinsic::amdgcn_s_barrier:
382 case Intrinsic::amdgcn_s_cluster_barrier:
383 case Intrinsic::amdgcn_s_barrier_signal:
384 case Intrinsic::amdgcn_s_barrier_signal_var:
385 case Intrinsic::amdgcn_s_barrier_signal_isfirst:
386 case Intrinsic::amdgcn_s_barrier_init:
387 case Intrinsic::amdgcn_s_barrier_join:
388 case Intrinsic::amdgcn_s_barrier_wait:
389 case Intrinsic::amdgcn_s_barrier_leave:
390 case Intrinsic::amdgcn_s_get_barrier_state:
391 case Intrinsic::amdgcn_s_wakeup_barrier:
392 case Intrinsic::amdgcn_wave_barrier:
393 case Intrinsic::amdgcn_sched_barrier:
394 case Intrinsic::amdgcn_sched_group_barrier:
395 case Intrinsic::amdgcn_iglp_opt:
396 return false;
397 default:
398 break;
399 }
400 }
401
402 // Ignore atomics not aliasing with the original load, any atomic is a
403 // universal MemoryDef from MSSA's point of view too, just like a fence.
404 const auto checkNoAlias = [AA, Ptr](auto I) -> bool {
405 return I && AA->isNoAlias(I->getPointerOperand(), Ptr);
406 };
407
408 if (checkNoAlias(dyn_cast<AtomicCmpXchgInst>(DefInst)) ||
409 checkNoAlias(dyn_cast<AtomicRMWInst>(DefInst)))
410 return false;
411
412 return true;
413}
414
416 AAResults *AA) {
417 MemorySSAWalker *Walker = MSSA->getWalker();
421
422 LLVM_DEBUG(dbgs() << "Checking clobbering of: " << *Load << '\n');
423
424 // Start with a nearest dominating clobbering access, it will be either
425 // live on entry (nothing to do, load is not clobbered), MemoryDef, or
426 // MemoryPhi if several MemoryDefs can define this memory state. In that
427 // case add all Defs to WorkList and continue going up and checking all
428 // the definitions of this memory location until the root. When all the
429 // defs are exhausted and came to the entry state we have no clobber.
430 // Along the scan ignore barriers and fences which are considered clobbers
431 // by the MemorySSA, but not really writing anything into the memory.
432 while (!WorkList.empty()) {
433 MemoryAccess *MA = WorkList.pop_back_val();
434 if (!Visited.insert(MA).second)
435 continue;
436
437 if (MSSA->isLiveOnEntryDef(MA))
438 continue;
439
440 if (MemoryDef *Def = dyn_cast<MemoryDef>(MA)) {
441 LLVM_DEBUG(dbgs() << " Def: " << *Def->getMemoryInst() << '\n');
442
443 if (isReallyAClobber(Load->getPointerOperand(), Def, AA)) {
444 LLVM_DEBUG(dbgs() << " -> load is clobbered\n");
445 return true;
446 }
447
448 WorkList.push_back(
449 Walker->getClobberingMemoryAccess(Def->getDefiningAccess(), Loc));
450 continue;
451 }
452
453 const MemoryPhi *Phi = cast<MemoryPhi>(MA);
454 for (const auto &Use : Phi->incoming_values())
455 WorkList.push_back(cast<MemoryAccess>(&Use));
456 }
457
458 LLVM_DEBUG(dbgs() << " -> no clobber\n");
459 return false;
460}
461
462} // end namespace llvm::AMDGPU
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t IntrinsicInst * II
This file defines generic set operations that may be used on set's of different types,...
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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:174
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:64
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
const Function & getFunction() const
Definition Function.h:166
void removeFnAttr(Attribute::AttrKind Kind)
Remove function attributes from this function.
Definition Function.cpp:686
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
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:569
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition MemorySSA.h:371
Representation for a specific memory location.
static LLVM_ABI 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:479
This is the generic walker interface for walkers of MemorySSA.
Definition MemorySSA.h:1006
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:1035
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
LLVM_ABI MemorySSAWalker * getWalker()
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:740
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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)
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
Class to represent target extensions types, which are generally unintrospectable from target-independ...
StringRef getName() const
Return the name for this target extension type.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI 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:35
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:972
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:185
Abstract Attribute helper functions.
Definition Attributor.h:165
@ LOCAL_ADDRESS
Address space for local memory.
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.
LLVM_READNONE constexpr bool isKernel(CallingConv::ID CC)
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)
static TargetExtType * getTargetExtType(const GlobalVariable &GV)
DenseMap< Function *, DenseSet< GlobalVariable * > > FunctionVariableMap
TargetExtType * isNamedBarrier(const GlobalVariable &GV)
bool isLDSVariableToLower(const GlobalVariable &GV)
bool eliminateConstantExprUsesOfLDSFromAllInstructions(Module &M)
Align getAlign(const DataLayout &DL, const GlobalVariable *GV)
void copyMetadataForWidenedLoad(LoadInst &Dest, const LoadInst &Source)
bool isClobberedInFunction(const LoadInst *Load, MemorySSA *MSSA, AAResults *AA)
Check is a Load is clobbered in its function.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
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
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39