LLVM 23.0.0git
AMDGPURewriteOutArguments.cpp
Go to the documentation of this file.
1//===- AMDGPURewriteOutArgumentsPass.cpp - Create struct returns ----------===//
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/// \file This pass attempts to replace out argument usage with a return of a
10/// struct.
11///
12/// We can support returning a lot of values directly in registers, but
13/// idiomatic C code frequently uses a pointer argument to return a second value
14/// rather than returning a struct by value. GPU stack access is also quite
15/// painful, so we want to avoid that if possible. Passing a stack object
16/// pointer to a function also requires an additional address expansion code
17/// sequence to convert the pointer to be relative to the kernel's scratch wave
18/// offset register since the callee doesn't know what stack frame the incoming
19/// pointer is relative to.
20///
21/// The goal is to try rewriting code that looks like this:
22///
23/// int foo(int a, int b, int* out) {
24/// *out = bar();
25/// return a + b;
26/// }
27///
28/// into something like this:
29///
30/// std::pair<int, int> foo(int a, int b) {
31/// return std::pair(a + b, bar());
32/// }
33///
34/// Typically the incoming pointer is a simple alloca for a temporary variable
35/// to use the API, which if replaced with a struct return will be easily SROA'd
36/// out when the stub function we create is inlined
37///
38/// This pass introduces the struct return, but leaves the unused pointer
39/// arguments and introduces a new stub function calling the struct returning
40/// body. DeadArgumentElimination should be run after this to clean these up.
41//
42//===----------------------------------------------------------------------===//
43
44#include "AMDGPU.h"
46#include "llvm/ADT/Statistic.h"
50#include "llvm/IR/IRBuilder.h"
53#include "llvm/Pass.h"
55#include "llvm/Support/Debug.h"
57
58#define DEBUG_TYPE "amdgpu-rewrite-out-arguments"
59
60using namespace llvm;
61
63 "amdgpu-any-address-space-out-arguments",
64 cl::desc("Replace pointer out arguments with "
65 "struct returns for non-private address space"),
67 cl::init(false));
68
70 "amdgpu-max-return-arg-num-regs",
71 cl::desc("Approximately limit number of return registers for replacing out arguments"),
73 cl::init(16));
74
75STATISTIC(NumOutArgumentsReplaced,
76 "Number out arguments moved to struct return values");
77STATISTIC(NumOutArgumentFunctionsReplaced,
78 "Number of functions with out arguments moved to struct return values");
79
80namespace {
81
82class AMDGPURewriteOutArguments : public FunctionPass {
83private:
84 const DataLayout *DL = nullptr;
85 MemorySSA *MSSA = nullptr;
86 MemorySSAUpdater *MSSAU = nullptr;
87 AAResults *AA = nullptr;
88
89 Type *getStoredType(Value &Arg) const;
90 Type *getOutArgumentType(Argument &Arg) const;
91
92public:
93 static char ID;
94
95 AMDGPURewriteOutArguments() : FunctionPass(ID) {}
96
97 void getAnalysisUsage(AnalysisUsage &AU) const override {
98 AU.addRequired<MemorySSAWrapperPass>();
99 AU.addRequired<AAResultsWrapperPass>();
100 FunctionPass::getAnalysisUsage(AU);
101 }
102
103 bool doInitialization(Module &M) override;
104 bool runOnFunction(Function &F) override;
105};
106
107} // end anonymous namespace
108
109INITIALIZE_PASS_BEGIN(AMDGPURewriteOutArguments, DEBUG_TYPE,
110 "AMDGPU Rewrite Out Arguments", false, false)
112INITIALIZE_PASS_END(AMDGPURewriteOutArguments, DEBUG_TYPE,
113 "AMDGPU Rewrite Out Arguments", false, false)
114
115char AMDGPURewriteOutArguments::ID = 0;
116
117Type *AMDGPURewriteOutArguments::getStoredType(Value &Arg) const {
118 const int MaxUses = 10;
119 int UseCount = 0;
120
121 SmallVector<Use *> Worklist(llvm::make_pointer_range(Arg.uses()));
122
123 Type *StoredType = nullptr;
124 while (!Worklist.empty()) {
125 Use *U = Worklist.pop_back_val();
126
127 if (auto *BCI = dyn_cast<BitCastInst>(U->getUser())) {
128 for (Use &U : BCI->uses())
129 Worklist.push_back(&U);
130 continue;
131 }
132
133 if (auto *SI = dyn_cast<StoreInst>(U->getUser())) {
134 if (UseCount++ > MaxUses)
135 return nullptr;
136
137 if (!SI->isSimple() ||
138 U->getOperandNo() != StoreInst::getPointerOperandIndex())
139 return nullptr;
140
141 if (StoredType && StoredType != SI->getValueOperand()->getType())
142 return nullptr; // More than one type.
143 StoredType = SI->getValueOperand()->getType();
144 continue;
145 }
146
147 // Unsupported user.
148 return nullptr;
149 }
150
151 return StoredType;
152}
153
154Type *AMDGPURewriteOutArguments::getOutArgumentType(Argument &Arg) const {
155 const unsigned MaxOutArgSizeBytes = 4 * MaxNumRetRegs;
157
158 // TODO: It might be useful for any out arguments, not just privates.
159 if (!ArgTy || (ArgTy->getAddressSpace() != DL->getAllocaAddrSpace() &&
160 !AnyAddressSpace) ||
161 Arg.hasByValAttr() || Arg.hasStructRetAttr()) {
162 return nullptr;
163 }
164
165 Type *StoredType = getStoredType(Arg);
166 if (!StoredType || DL->getTypeStoreSize(StoredType) > MaxOutArgSizeBytes)
167 return nullptr;
168
169 return StoredType;
170}
171
172bool AMDGPURewriteOutArguments::doInitialization(Module &M) {
173 DL = &M.getDataLayout();
174 return false;
175}
176
178 MemorySSA &MSSA,
179 BatchAAResults &BAA) {
181 const auto *Accesses = MSSA.getBlockAccesses(BB);
182 if (!Accesses)
183 return nullptr;
184
185 for (const MemoryAccess &Access : reverse(*Accesses)) {
186 const auto *UseOrDef = dyn_cast<MemoryUseOrDef>(&Access);
187 if (!UseOrDef)
188 continue;
189
190 Instruction *I = UseOrDef->getMemoryInst();
191
192 // Return the must-alias store to the out argument.
193 if (auto *Store = dyn_cast<StoreInst>(I))
194 if (Store->getPointerOperand() == OutArg)
195 return Store;
196
197 if (auto *FI = dyn_cast<FenceInst>(I))
198 if (FI->getOrdering() == AtomicOrdering::Release)
199 continue;
200
201 if (auto *LI = dyn_cast<LoadInst>(I)) {
202 if (LI->isAtomic()) {
203 // May-alias reads with monotonic ordering are ignored.
204 if (isStrongerThan(LI->getOrdering(), AtomicOrdering::Monotonic))
205 return nullptr;
206 continue;
207 }
208 }
209
210 // Any other memory access that writes the location prevents the
211 // rewrite.
212 // FIXME: should handle aliasing reads too.
213 if (isModSet(BAA.getModRefInfo(I, ArgLoc)))
214 return nullptr;
215 }
216
217 return nullptr;
218}
219
220bool AMDGPURewriteOutArguments::runOnFunction(Function &F) {
221 if (skipFunction(F))
222 return false;
223
224 // TODO: Could probably handle variadic functions.
225 if (F.isVarArg() || F.hasStructRetAttr() ||
226 AMDGPU::isEntryFunctionCC(F.getCallingConv()))
227 return false;
228
229 unsigned ReturnNumRegs = 0;
230 // Maps an out-argument number to its field index in the return struct.
231 // Fields are in processing order, which the retry loop below can reorder
232 // relative to argument order, so the index must be tracked, not recomputed.
233 SmallDenseMap<unsigned, unsigned, 4> OutArgIndexes;
234 SmallVector<Type *, 4> ReturnTypes;
235 Type *RetTy = F.getReturnType();
236 if (!RetTy->isVoidTy()) {
237 ReturnNumRegs = DL->getTypeStoreSize(RetTy) / 4;
238
239 if (ReturnNumRegs >= MaxNumRetRegs)
240 return false;
241
242 ReturnTypes.push_back(RetTy);
243 }
244
246 for (Argument &Arg : F.args()) {
247 if (Type *Ty = getOutArgumentType(Arg)) {
248 LLVM_DEBUG(dbgs() << "Found possible out argument " << Arg
249 << " in function " << F.getName() << '\n');
250 OutArgs.push_back({&Arg, Ty});
251 }
252 }
253
254 if (OutArgs.empty())
255 return false;
256
257 using ReplacementVec = SmallVector<std::pair<Argument *, Value *>, 4>;
258
259 DenseMap<ReturnInst *, ReplacementVec> Replacements;
260
262 for (BasicBlock &BB : F) {
263 if (ReturnInst *RI = dyn_cast<ReturnInst>(&BB.back()))
264 Returns.push_back(RI);
265 }
266
267 if (Returns.empty())
268 return false;
269
270 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
271 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
272
273 BatchAAResults BatchAA(*AA);
274 MemorySSAUpdater MSSAUpdater(MSSA);
275 MSSAU = &MSSAUpdater;
276
277 bool Changing;
278
279 do {
280 Changing = false;
281
282 // Keep retrying if we are able to successfully eliminate an argument. This
283 // helps with cases with multiple arguments which may alias, such as in a
284 // sincos implementation. With 2 stores to may-aliasing arguments, MDA
285 // returns the second store for the first argument too; the identity guard
286 // below rejects it, and a later iteration folds the first argument once the
287 // second store has been removed.
288 for (const auto &Pair : OutArgs) {
289 bool ThisReplaceable = true;
291
292 Argument *OutArg = Pair.first;
293 Type *ArgTy = Pair.second;
294
295 // Skip this argument if converting it will push us over the register
296 // count to return limit.
297
298 // TODO: This is an approximation. When legalized this could be more. We
299 // can ask TLI for exactly how many.
300 unsigned ArgNumRegs = DL->getTypeStoreSize(ArgTy) / 4;
301 if (ArgNumRegs + ReturnNumRegs > MaxNumRetRegs)
302 continue;
303
304 // An argument is convertible only if all exit blocks are able to replace
305 // it.
306 for (ReturnInst *RI : Returns) {
307 BasicBlock *BB = RI->getParent();
308
309 StoreInst *SI = findStoreForOutArgument(BB, OutArg, *MSSA, BatchAA);
310 if (SI) {
311 LLVM_DEBUG(dbgs() << "Found out argument store: " << *SI << '\n');
312 ReplaceableStores.emplace_back(RI, SI);
313 } else {
314 ThisReplaceable = false;
315 break;
316 }
317 }
318
319 if (!ThisReplaceable)
320 continue; // Try the next argument candidate.
321
322 for (std::pair<ReturnInst *, StoreInst *> Store : ReplaceableStores) {
323 Value *ReplVal = Store.second->getValueOperand();
324
325 auto &ValVec = Replacements[Store.first];
326 if (llvm::is_contained(llvm::make_first_range(ValVec), OutArg)) {
328 << "Saw multiple out arg stores" << *OutArg << '\n');
329 // It is possible to see stores to the same argument multiple times,
330 // but we expect these would have been optimized out already.
331 ThisReplaceable = false;
332 break;
333 }
334
335 ValVec.emplace_back(OutArg, ReplVal);
336 MSSAU->removeMemoryAccess(Store.second);
337 Store.second->eraseFromParent();
338 }
339
340 if (ThisReplaceable) {
341 OutArgIndexes.insert({OutArg->getArgNo(), ReturnTypes.size()});
342 ReturnTypes.push_back(ArgTy);
343 ++NumOutArgumentsReplaced;
344 Changing = true;
345 }
346 }
347 } while (Changing);
348
349 if (Replacements.empty())
350 return false;
351
352 LLVMContext &Ctx = F.getContext();
353 StructType *NewRetTy = StructType::create(Ctx, ReturnTypes, F.getName());
354
355 FunctionType *NewFuncTy = FunctionType::get(NewRetTy,
356 F.getFunctionType()->params(),
357 F.isVarArg());
358
359 LLVM_DEBUG(dbgs() << "Computed new return type: " << *NewRetTy << '\n');
360
361 Function *NewFunc = Function::Create(NewFuncTy, Function::PrivateLinkage,
362 F.getName() + ".body");
363 F.getParent()->getFunctionList().insert(F.getIterator(), NewFunc);
364 NewFunc->copyAttributesFrom(&F);
365 NewFunc->setComdat(F.getComdat());
366
367 // We want to preserve the function and param attributes, but need to strip
368 // off any return attributes, e.g. zeroext doesn't make sense with a struct.
369 NewFunc->stealArgumentListFrom(F);
370
371 AttributeMask RetAttrs;
372 RetAttrs.addAttribute(Attribute::SExt);
373 RetAttrs.addAttribute(Attribute::ZExt);
374 RetAttrs.addAttribute(Attribute::NoAlias);
375 NewFunc->removeRetAttrs(RetAttrs);
376 // TODO: How to preserve metadata?
377
378 // Move the body of the function into the new rewritten function, and replace
379 // this function with a stub.
380 NewFunc->splice(NewFunc->begin(), &F);
381
382 for (std::pair<ReturnInst *, ReplacementVec> &Replacement : Replacements) {
383 ReturnInst *RI = Replacement.first;
384 IRBuilder<> B(RI);
385 B.SetCurrentDebugLocation(RI->getDebugLoc());
386
387 Value *NewRetVal = PoisonValue::get(NewRetTy);
388
389 Value *RetVal = RI->getReturnValue();
390 if (RetVal)
391 NewRetVal = B.CreateInsertValue(NewRetVal, RetVal, 0);
392
393 // Use OutArgIndexes so body and stub agree on the field for each argument.
394 for (std::pair<Argument *, Value *> ReturnPoint : Replacement.second) {
395 unsigned FieldIdx = OutArgIndexes.lookup(ReturnPoint.first->getArgNo());
396 NewRetVal = B.CreateInsertValue(NewRetVal, ReturnPoint.second, FieldIdx);
397 }
398
399 if (RetVal)
400 RI->setOperand(0, NewRetVal);
401 else {
402 B.CreateRet(NewRetVal);
403 RI->eraseFromParent();
404 }
405 }
406
407 SmallVector<Value *, 16> StubCallArgs;
408 for (Argument &Arg : F.args()) {
409 if (OutArgIndexes.count(Arg.getArgNo())) {
410 // It's easier to preserve the type of the argument list. We rely on
411 // DeadArgumentElimination to take care of these.
412 StubCallArgs.push_back(PoisonValue::get(Arg.getType()));
413 } else {
414 StubCallArgs.push_back(&Arg);
415 }
416 }
417
418 BasicBlock *StubBB = BasicBlock::Create(Ctx, "", &F);
419 IRBuilder<> B(StubBB);
420 CallInst *StubCall = B.CreateCall(NewFunc, StubCallArgs);
421
422 for (Argument &Arg : F.args()) {
423 auto It = OutArgIndexes.find(Arg.getArgNo());
424 if (It == OutArgIndexes.end())
425 continue;
426
427 unsigned FieldIdx = It->second;
428 Type *EltTy = NewRetTy->getElementType(FieldIdx);
429 const auto Align =
430 DL->getValueOrABITypeAlignment(Arg.getParamAlign(), EltTy);
431
432 Value *Val = B.CreateExtractValue(StubCall, FieldIdx);
433 B.CreateAlignedStore(Val, &Arg, Align);
434 }
435
436 if (!RetTy->isVoidTy()) {
437 B.CreateRet(B.CreateExtractValue(StubCall, 0));
438 } else {
439 B.CreateRetVoid();
440 }
441
442 // The function is now a stub we want to inline.
443 F.addFnAttr(Attribute::AlwaysInline);
444
445 ++NumOutArgumentFunctionsReplaced;
446 return true;
447}
448
450 return new AMDGPURewriteOutArguments();
451}
static cl::opt< unsigned > MaxNumRetRegs("amdgpu-max-return-arg-num-regs", cl::desc("Approximately limit number of return registers for replacing out arguments"), cl::Hidden, cl::init(16))
static cl::opt< bool > AnyAddressSpace("amdgpu-any-address-space-out-arguments", cl::desc("Replace pointer out arguments with " "struct returns for non-private address space"), cl::Hidden, cl::init(false))
static StoreInst * findStoreForOutArgument(BasicBlock *BB, Argument *OutArg, MemorySSA &MSSA, BatchAAResults &BAA)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Forward Handle Accesses
DXIL Resource Access
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#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 defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
AnalysisUsage & addRequired()
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
Definition Function.cpp:127
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
LLVM_ABI MaybeAlign getParamAlign() const
If this is a byval or inalloca argument, return its alignment.
Definition Function.cpp:210
LLVM_ABI bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
Definition Function.cpp:282
AttributeMask & addAttribute(Attribute::AttrKind Val)
Add an attribute to the mask.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool empty() const
Definition DenseMap.h:171
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:735
iterator begin()
Definition Function.h:827
void stealArgumentListFrom(Function &Src)
Steal arguments from another function.
Definition Function.cpp:562
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
Definition Function.cpp:701
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:838
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Representation for a specific memory location.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:975
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:758
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:683
Type * getElementType(unsigned N) const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
iterator_range< use_iterator > uses()
Definition Value.h:380
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
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
FunctionPass * createAMDGPURewriteOutArgumentsPass()
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1399
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...