blob: 8c04e2b19624a1904d8fe9789183d30334b4bcf7 [file] [log] [blame]
Matt Arsenaultc06574f2017-07-28 18:40:05 +00001//===-- AMDGPURewriteOutArgumentsPass.cpp - Create struct returns ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file This pass attempts to replace out argument usage with a return of a
11/// struct.
12///
13/// We can support returning a lot of values directly in registers, but
14/// idiomatic C code frequently uses a pointer argument to return a second value
15/// rather than returning a struct by value. GPU stack access is also quite
16/// painful, so we want to avoid that if possible. Passing a stack object
17/// pointer to a function also requires an additional address expansion code
18/// sequence to convert the pointer to be relative to the kernel's scratch wave
19/// offset register since the callee doesn't know what stack frame the incoming
20/// pointer is relative to.
21///
22/// The goal is to try rewriting code that looks like this:
23///
24/// int foo(int a, int b, int* out) {
25/// *out = bar();
26/// return a + b;
27/// }
28///
29/// into something like this:
30///
31/// std::pair<int, int> foo(int a, int b) {
32/// return std::make_pair(a + b, bar());
33/// }
34///
35/// Typically the incoming pointer is a simple alloca for a temporary variable
36/// to use the API, which if replaced with a struct return will be easily SROA'd
37/// out when the stub function we create is inlined
38///
39/// This pass introduces the struct return, but leaves the unused pointer
40/// arguments and introduces a new stub function calling the struct returning
41/// body. DeadArgumentElimination should be run after this to clean these up.
42//
43//===----------------------------------------------------------------------===//
44
45#include "AMDGPU.h"
46#include "Utils/AMDGPUBaseInfo.h"
47
48#include "llvm/Analysis/MemoryDependenceAnalysis.h"
49#include "llvm/ADT/BitVector.h"
50#include "llvm/ADT/SetVector.h"
51#include "llvm/ADT/Statistic.h"
52#include "llvm/IR/IRBuilder.h"
53#include "llvm/IR/Module.h"
54#include "llvm/Transforms/Utils/Cloning.h"
55#include "llvm/Support/Debug.h"
56
57#define DEBUG_TYPE "amdgpu-rewrite-out-arguments"
58
59using namespace llvm;
60
61namespace {
62
63static cl::opt<bool> AnyAddressSpace(
64 "amdgpu-any-address-space-out-arguments",
65 cl::desc("Replace pointer out arguments with "
66 "struct returns for non-private address space"),
67 cl::Hidden,
68 cl::init(false));
69
70static cl::opt<unsigned> MaxNumRetRegs(
71 "amdgpu-max-return-arg-num-regs",
72 cl::desc("Approximately limit number of return registers for replacing out arguments"),
73 cl::Hidden,
74 cl::init(16));
75
76STATISTIC(NumOutArgumentsReplaced,
77 "Number out arguments moved to struct return values");
78STATISTIC(NumOutArgumentFunctionsReplaced,
79 "Number of functions with out arguments moved to struct return values");
80
81class AMDGPURewriteOutArguments : public FunctionPass {
82private:
83 const DataLayout *DL = nullptr;
84 MemoryDependenceResults *MDA = nullptr;
85
Matt Arsenaultda9ab142017-07-28 19:06:16 +000086 bool checkArgumentUses(Value &Arg) const;
Matt Arsenaultc06574f2017-07-28 18:40:05 +000087 bool isOutArgumentCandidate(Argument &Arg) const;
88
Davide Italianoffb10982017-08-01 19:07:20 +000089#ifndef NDEBUG
Matt Arsenaultda9ab142017-07-28 19:06:16 +000090 bool isVec3ToVec4Shuffle(Type *Ty0, Type* Ty1) const;
Davide Italianoffb10982017-08-01 19:07:20 +000091#endif
Matt Arsenaultc06574f2017-07-28 18:40:05 +000092public:
93 static char ID;
94
95 AMDGPURewriteOutArguments() :
96 FunctionPass(ID) {}
97
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
99 AU.addRequired<MemoryDependenceWrapperPass>();
100 FunctionPass::getAnalysisUsage(AU);
101 }
102
103 bool doInitialization(Module &M) override;
104 bool runOnFunction(Function &M) override;
105};
106
107} // End anonymous namespace
108
109INITIALIZE_PASS_BEGIN(AMDGPURewriteOutArguments, DEBUG_TYPE,
110 "AMDGPU Rewrite Out Arguments", false, false)
111INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
112INITIALIZE_PASS_END(AMDGPURewriteOutArguments, DEBUG_TYPE,
113 "AMDGPU Rewrite Out Arguments", false, false)
114
115char AMDGPURewriteOutArguments::ID = 0;
116
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000117bool AMDGPURewriteOutArguments::checkArgumentUses(Value &Arg) const {
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000118 const int MaxUses = 10;
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000119 int UseCount = 0;
120
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000121 for (Use &U : Arg.uses()) {
122 StoreInst *SI = dyn_cast<StoreInst>(U.getUser());
123 if (UseCount > MaxUses)
124 return false;
125
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000126 if (!SI) {
127 auto *BCI = dyn_cast<BitCastInst>(U.getUser());
128 if (!BCI || !BCI->hasOneUse())
129 return false;
130
131 // We don't handle multiple stores currently, so stores to aggregate
132 // pointers aren't worth the trouble since they are canonically split up.
133 Type *DestEltTy = BCI->getType()->getPointerElementType();
134 if (DestEltTy->isAggregateType())
135 return false;
136
137 // We could handle these if we had a convenient way to bitcast between
138 // them.
139 Type *SrcEltTy = Arg.getType()->getPointerElementType();
140 if (SrcEltTy->isArrayTy())
141 return false;
142
143 // Special case handle structs with single members. It is useful to handle
144 // some casts between structs and non-structs, but we can't bitcast
145 // directly between them. directly bitcast between them. Blender uses
146 // some casts that look like { <3 x float> }* to <4 x float>*
147 if ((SrcEltTy->isStructTy() && (SrcEltTy->getNumContainedTypes() != 1)))
148 return false;
149
150 // Clang emits OpenCL 3-vector type accesses with a bitcast to the
151 // equivalent 4-element vector and accesses that, and we're looking for
152 // this pointer cast.
153 if (DL->getTypeAllocSize(SrcEltTy) != DL->getTypeAllocSize(DestEltTy))
154 return false;
155
156 return checkArgumentUses(*BCI);
157 }
158
159 if (!SI->isSimple() ||
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000160 U.getOperandNo() != StoreInst::getPointerOperandIndex())
161 return false;
162
163 ++UseCount;
164 }
165
166 // Skip unused arguments.
167 return UseCount > 0;
168}
169
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000170bool AMDGPURewriteOutArguments::isOutArgumentCandidate(Argument &Arg) const {
171 const unsigned MaxOutArgSizeBytes = 4 * MaxNumRetRegs;
172 PointerType *ArgTy = dyn_cast<PointerType>(Arg.getType());
173
174 // TODO: It might be useful for any out arguments, not just privates.
175 if (!ArgTy || (ArgTy->getAddressSpace() != DL->getAllocaAddrSpace() &&
176 !AnyAddressSpace) ||
177 Arg.hasByValAttr() || Arg.hasStructRetAttr() ||
178 DL->getTypeStoreSize(ArgTy->getPointerElementType()) > MaxOutArgSizeBytes) {
179 return false;
180 }
181
182 return checkArgumentUses(Arg);
183}
184
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000185bool AMDGPURewriteOutArguments::doInitialization(Module &M) {
186 DL = &M.getDataLayout();
187 return false;
188}
189
Davide Italianoffb10982017-08-01 19:07:20 +0000190#ifndef NDEBUG
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000191bool AMDGPURewriteOutArguments::isVec3ToVec4Shuffle(Type *Ty0, Type* Ty1) const {
192 VectorType *VT0 = dyn_cast<VectorType>(Ty0);
193 VectorType *VT1 = dyn_cast<VectorType>(Ty1);
194 if (!VT0 || !VT1)
195 return false;
196
197 if (VT0->getNumElements() != 3 ||
198 VT1->getNumElements() != 4)
199 return false;
200
201 return DL->getTypeSizeInBits(VT0->getElementType()) ==
202 DL->getTypeSizeInBits(VT1->getElementType());
203}
Davide Italianoffb10982017-08-01 19:07:20 +0000204#endif
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000205
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000206bool AMDGPURewriteOutArguments::runOnFunction(Function &F) {
207 if (skipFunction(F))
208 return false;
209
210 // TODO: Could probably handle variadic functions.
211 if (F.isVarArg() || F.hasStructRetAttr() ||
212 AMDGPU::isEntryFunctionCC(F.getCallingConv()))
213 return false;
214
215 MDA = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
216
217 unsigned ReturnNumRegs = 0;
218 SmallSet<int, 4> OutArgIndexes;
219 SmallVector<Type *, 4> ReturnTypes;
220 Type *RetTy = F.getReturnType();
221 if (!RetTy->isVoidTy()) {
222 ReturnNumRegs = DL->getTypeStoreSize(RetTy) / 4;
223
224 if (ReturnNumRegs >= MaxNumRetRegs)
225 return false;
226
227 ReturnTypes.push_back(RetTy);
228 }
229
230 SmallVector<Argument *, 4> OutArgs;
231 for (Argument &Arg : F.args()) {
232 if (isOutArgumentCandidate(Arg)) {
233 DEBUG(dbgs() << "Found possible out argument " << Arg
234 << " in function " << F.getName() << '\n');
235 OutArgs.push_back(&Arg);
236 }
237 }
238
239 if (OutArgs.empty())
240 return false;
241
242 typedef SmallVector<std::pair<Argument *, Value *>, 4> ReplacementVec;
243 DenseMap<ReturnInst *, ReplacementVec> Replacements;
244
245 SmallVector<ReturnInst *, 4> Returns;
246 for (BasicBlock &BB : F) {
247 if (ReturnInst *RI = dyn_cast<ReturnInst>(&BB.back()))
248 Returns.push_back(RI);
249 }
250
251 if (Returns.empty())
252 return false;
253
254 bool Changing;
255
256 do {
257 Changing = false;
258
259 // Keep retrying if we are able to successfully eliminate an argument. This
260 // helps with cases with multiple arguments which may alias, such as in a
261 // sincos implemntation. If we have 2 stores to arguments, on the first
262 // attempt the MDA query will succeed for the second store but not the
263 // first. On the second iteration we've removed that out clobbering argument
264 // (by effectively moving it into another function) and will find the second
265 // argument is OK to move.
266 for (Argument *OutArg : OutArgs) {
267 bool ThisReplaceable = true;
268 SmallVector<std::pair<ReturnInst *, StoreInst *>, 4> ReplaceableStores;
269
270 Type *ArgTy = OutArg->getType()->getPointerElementType();
271
272 // Skip this argument if converting it will push us over the register
273 // count to return limit.
274
275 // TODO: This is an approximation. When legalized this could be more. We
276 // can ask TLI for exactly how many.
277 unsigned ArgNumRegs = DL->getTypeStoreSize(ArgTy) / 4;
278 if (ArgNumRegs + ReturnNumRegs > MaxNumRetRegs)
279 continue;
280
281 // An argument is convertible only if all exit blocks are able to replace
282 // it.
283 for (ReturnInst *RI : Returns) {
284 BasicBlock *BB = RI->getParent();
285
286 MemDepResult Q = MDA->getPointerDependencyFrom(MemoryLocation(OutArg),
287 true, BB->end(), BB, RI);
288 StoreInst *SI = nullptr;
289 if (Q.isDef())
290 SI = dyn_cast<StoreInst>(Q.getInst());
291
292 if (SI) {
293 DEBUG(dbgs() << "Found out argument store: " << *SI << '\n');
294 ReplaceableStores.emplace_back(RI, SI);
295 } else {
296 ThisReplaceable = false;
297 break;
298 }
299 }
300
301 if (!ThisReplaceable)
302 continue; // Try the next argument candidate.
303
304 for (std::pair<ReturnInst *, StoreInst *> Store : ReplaceableStores) {
305 Value *ReplVal = Store.second->getValueOperand();
306
307 auto &ValVec = Replacements[Store.first];
308 if (llvm::find_if(ValVec,
309 [OutArg](const std::pair<Argument *, Value *> &Entry) {
310 return Entry.first == OutArg;}) != ValVec.end()) {
311 DEBUG(dbgs() << "Saw multiple out arg stores" << *OutArg << '\n');
312 // It is possible to see stores to the same argument multiple times,
313 // but we expect these would have been optimized out already.
314 ThisReplaceable = false;
315 break;
316 }
317
318 ValVec.emplace_back(OutArg, ReplVal);
319 Store.second->eraseFromParent();
320 }
321
322 if (ThisReplaceable) {
323 ReturnTypes.push_back(ArgTy);
324 OutArgIndexes.insert(OutArg->getArgNo());
325 ++NumOutArgumentsReplaced;
326 Changing = true;
327 }
328 }
329 } while (Changing);
330
331 if (Replacements.empty())
332 return false;
333
334 LLVMContext &Ctx = F.getParent()->getContext();
335 StructType *NewRetTy = StructType::create(Ctx, ReturnTypes, F.getName());
336
337 FunctionType *NewFuncTy = FunctionType::get(NewRetTy,
338 F.getFunctionType()->params(),
339 F.isVarArg());
340
341 DEBUG(dbgs() << "Computed new return type: " << *NewRetTy << '\n');
342
343 Function *NewFunc = Function::Create(NewFuncTy, Function::PrivateLinkage,
344 F.getName() + ".body");
345 F.getParent()->getFunctionList().insert(F.getIterator(), NewFunc);
346 NewFunc->copyAttributesFrom(&F);
347 NewFunc->setComdat(F.getComdat());
348
349 // We want to preserve the function and param attributes, but need to strip
350 // off any return attributes, e.g. zeroext doesn't make sense with a struct.
351 NewFunc->stealArgumentListFrom(F);
352
353 AttrBuilder RetAttrs;
354 RetAttrs.addAttribute(Attribute::SExt);
355 RetAttrs.addAttribute(Attribute::ZExt);
356 RetAttrs.addAttribute(Attribute::NoAlias);
357 NewFunc->removeAttributes(AttributeList::ReturnIndex, RetAttrs);
358 // TODO: How to preserve metadata?
359
360 // Move the body of the function into the new rewritten function, and replace
361 // this function with a stub.
362 NewFunc->getBasicBlockList().splice(NewFunc->begin(), F.getBasicBlockList());
363
364 for (std::pair<ReturnInst *, ReplacementVec> &Replacement : Replacements) {
365 ReturnInst *RI = Replacement.first;
366 IRBuilder<> B(RI);
367 B.SetCurrentDebugLocation(RI->getDebugLoc());
368
369 int RetIdx = 0;
370 Value *NewRetVal = UndefValue::get(NewRetTy);
371
372 Value *RetVal = RI->getReturnValue();
373 if (RetVal)
374 NewRetVal = B.CreateInsertValue(NewRetVal, RetVal, RetIdx++);
375
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000376
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000377 for (std::pair<Argument *, Value *> ReturnPoint : Replacement.second) {
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000378 Argument *Arg = ReturnPoint.first;
379 Value *Val = ReturnPoint.second;
380 Type *EltTy = Arg->getType()->getPointerElementType();
381 if (Val->getType() != EltTy) {
382 Type *EffectiveEltTy = EltTy;
383 if (StructType *CT = dyn_cast<StructType>(EltTy)) {
384 assert(CT->getNumContainedTypes() == 1);
385 EffectiveEltTy = CT->getContainedType(0);
386 }
387
388 if (DL->getTypeSizeInBits(EffectiveEltTy) !=
389 DL->getTypeSizeInBits(Val->getType())) {
390 assert(isVec3ToVec4Shuffle(EffectiveEltTy, Val->getType()));
391 Val = B.CreateShuffleVector(Val, UndefValue::get(Val->getType()),
392 { 0, 1, 2 });
393 }
394
395 Val = B.CreateBitCast(Val, EffectiveEltTy);
396
397 // Re-create single element composite.
398 if (EltTy != EffectiveEltTy)
399 Val = B.CreateInsertValue(UndefValue::get(EltTy), Val, 0);
400 }
401
402 NewRetVal = B.CreateInsertValue(NewRetVal, Val, RetIdx++);
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000403 }
404
405 if (RetVal)
406 RI->setOperand(0, NewRetVal);
407 else {
408 B.CreateRet(NewRetVal);
409 RI->eraseFromParent();
410 }
411 }
412
413 SmallVector<Value *, 16> StubCallArgs;
414 for (Argument &Arg : F.args()) {
415 if (OutArgIndexes.count(Arg.getArgNo())) {
416 // It's easier to preserve the type of the argument list. We rely on
417 // DeadArgumentElimination to take care of these.
418 StubCallArgs.push_back(UndefValue::get(Arg.getType()));
419 } else {
420 StubCallArgs.push_back(&Arg);
421 }
422 }
423
424 BasicBlock *StubBB = BasicBlock::Create(Ctx, "", &F);
425 IRBuilder<> B(StubBB);
426 CallInst *StubCall = B.CreateCall(NewFunc, StubCallArgs);
427
428 int RetIdx = RetTy->isVoidTy() ? 0 : 1;
429 for (Argument &Arg : F.args()) {
430 if (!OutArgIndexes.count(Arg.getArgNo()))
431 continue;
432
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000433 PointerType *ArgType = cast<PointerType>(Arg.getType());
434
435 auto *EltTy = ArgType->getElementType();
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000436 unsigned Align = Arg.getParamAlignment();
437 if (Align == 0)
438 Align = DL->getABITypeAlignment(EltTy);
439
440 Value *Val = B.CreateExtractValue(StubCall, RetIdx++);
Matt Arsenaultda9ab142017-07-28 19:06:16 +0000441 Type *PtrTy = Val->getType()->getPointerTo(ArgType->getAddressSpace());
442
443 // We can peek through bitcasts, so the type may not match.
444 Value *PtrVal = B.CreateBitCast(&Arg, PtrTy);
445
446 B.CreateAlignedStore(Val, PtrVal, Align);
Matt Arsenaultc06574f2017-07-28 18:40:05 +0000447 }
448
449 if (!RetTy->isVoidTy()) {
450 B.CreateRet(B.CreateExtractValue(StubCall, 0));
451 } else {
452 B.CreateRetVoid();
453 }
454
455 // The function is now a stub we want to inline.
456 F.addFnAttr(Attribute::AlwaysInline);
457
458 ++NumOutArgumentFunctionsReplaced;
459 return true;
460}
461
462FunctionPass *llvm::createAMDGPURewriteOutArgumentsPass() {
463 return new AMDGPURewriteOutArguments();
464}