Matt Arsenault | c06574f | 2017-07-28 18:40:05 +0000 | [diff] [blame^] | 1 | //===-- 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 | |
| 59 | using namespace llvm; |
| 60 | |
| 61 | namespace { |
| 62 | |
| 63 | static 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 | |
| 70 | static 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 | |
| 76 | STATISTIC(NumOutArgumentsReplaced, |
| 77 | "Number out arguments moved to struct return values"); |
| 78 | STATISTIC(NumOutArgumentFunctionsReplaced, |
| 79 | "Number of functions with out arguments moved to struct return values"); |
| 80 | |
| 81 | class AMDGPURewriteOutArguments : public FunctionPass { |
| 82 | private: |
| 83 | const DataLayout *DL = nullptr; |
| 84 | MemoryDependenceResults *MDA = nullptr; |
| 85 | |
| 86 | bool isOutArgumentCandidate(Argument &Arg) const; |
| 87 | |
| 88 | public: |
| 89 | static char ID; |
| 90 | |
| 91 | AMDGPURewriteOutArguments() : |
| 92 | FunctionPass(ID) {} |
| 93 | |
| 94 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 95 | AU.addRequired<MemoryDependenceWrapperPass>(); |
| 96 | FunctionPass::getAnalysisUsage(AU); |
| 97 | } |
| 98 | |
| 99 | bool doInitialization(Module &M) override; |
| 100 | bool runOnFunction(Function &M) override; |
| 101 | }; |
| 102 | |
| 103 | } // End anonymous namespace |
| 104 | |
| 105 | INITIALIZE_PASS_BEGIN(AMDGPURewriteOutArguments, DEBUG_TYPE, |
| 106 | "AMDGPU Rewrite Out Arguments", false, false) |
| 107 | INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) |
| 108 | INITIALIZE_PASS_END(AMDGPURewriteOutArguments, DEBUG_TYPE, |
| 109 | "AMDGPU Rewrite Out Arguments", false, false) |
| 110 | |
| 111 | char AMDGPURewriteOutArguments::ID = 0; |
| 112 | |
| 113 | bool AMDGPURewriteOutArguments::isOutArgumentCandidate(Argument &Arg) const { |
| 114 | const int MaxUses = 10; |
| 115 | const unsigned MaxOutArgSizeBytes = 4 * MaxNumRetRegs; |
| 116 | int UseCount = 0; |
| 117 | |
| 118 | PointerType *ArgTy = dyn_cast<PointerType>(Arg.getType()); |
| 119 | |
| 120 | // TODO: It might be useful for any out arguments, not just privates. |
| 121 | if (!ArgTy || (ArgTy->getAddressSpace() != DL->getAllocaAddrSpace() && |
| 122 | !AnyAddressSpace) || |
| 123 | Arg.hasByValAttr() || Arg.hasStructRetAttr() || |
| 124 | DL->getTypeStoreSize(ArgTy->getPointerElementType()) > MaxOutArgSizeBytes) { |
| 125 | return false; |
| 126 | } |
| 127 | |
| 128 | for (Use &U : Arg.uses()) { |
| 129 | StoreInst *SI = dyn_cast<StoreInst>(U.getUser()); |
| 130 | if (UseCount > MaxUses) |
| 131 | return false; |
| 132 | |
| 133 | if (!SI || !SI->isSimple() || |
| 134 | U.getOperandNo() != StoreInst::getPointerOperandIndex()) |
| 135 | return false; |
| 136 | |
| 137 | ++UseCount; |
| 138 | } |
| 139 | |
| 140 | // Skip unused arguments. |
| 141 | return UseCount > 0; |
| 142 | } |
| 143 | |
| 144 | bool AMDGPURewriteOutArguments::doInitialization(Module &M) { |
| 145 | DL = &M.getDataLayout(); |
| 146 | return false; |
| 147 | } |
| 148 | |
| 149 | bool AMDGPURewriteOutArguments::runOnFunction(Function &F) { |
| 150 | if (skipFunction(F)) |
| 151 | return false; |
| 152 | |
| 153 | // TODO: Could probably handle variadic functions. |
| 154 | if (F.isVarArg() || F.hasStructRetAttr() || |
| 155 | AMDGPU::isEntryFunctionCC(F.getCallingConv())) |
| 156 | return false; |
| 157 | |
| 158 | MDA = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); |
| 159 | |
| 160 | unsigned ReturnNumRegs = 0; |
| 161 | SmallSet<int, 4> OutArgIndexes; |
| 162 | SmallVector<Type *, 4> ReturnTypes; |
| 163 | Type *RetTy = F.getReturnType(); |
| 164 | if (!RetTy->isVoidTy()) { |
| 165 | ReturnNumRegs = DL->getTypeStoreSize(RetTy) / 4; |
| 166 | |
| 167 | if (ReturnNumRegs >= MaxNumRetRegs) |
| 168 | return false; |
| 169 | |
| 170 | ReturnTypes.push_back(RetTy); |
| 171 | } |
| 172 | |
| 173 | SmallVector<Argument *, 4> OutArgs; |
| 174 | for (Argument &Arg : F.args()) { |
| 175 | if (isOutArgumentCandidate(Arg)) { |
| 176 | DEBUG(dbgs() << "Found possible out argument " << Arg |
| 177 | << " in function " << F.getName() << '\n'); |
| 178 | OutArgs.push_back(&Arg); |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | if (OutArgs.empty()) |
| 183 | return false; |
| 184 | |
| 185 | typedef SmallVector<std::pair<Argument *, Value *>, 4> ReplacementVec; |
| 186 | DenseMap<ReturnInst *, ReplacementVec> Replacements; |
| 187 | |
| 188 | SmallVector<ReturnInst *, 4> Returns; |
| 189 | for (BasicBlock &BB : F) { |
| 190 | if (ReturnInst *RI = dyn_cast<ReturnInst>(&BB.back())) |
| 191 | Returns.push_back(RI); |
| 192 | } |
| 193 | |
| 194 | if (Returns.empty()) |
| 195 | return false; |
| 196 | |
| 197 | bool Changing; |
| 198 | |
| 199 | do { |
| 200 | Changing = false; |
| 201 | |
| 202 | // Keep retrying if we are able to successfully eliminate an argument. This |
| 203 | // helps with cases with multiple arguments which may alias, such as in a |
| 204 | // sincos implemntation. If we have 2 stores to arguments, on the first |
| 205 | // attempt the MDA query will succeed for the second store but not the |
| 206 | // first. On the second iteration we've removed that out clobbering argument |
| 207 | // (by effectively moving it into another function) and will find the second |
| 208 | // argument is OK to move. |
| 209 | for (Argument *OutArg : OutArgs) { |
| 210 | bool ThisReplaceable = true; |
| 211 | SmallVector<std::pair<ReturnInst *, StoreInst *>, 4> ReplaceableStores; |
| 212 | |
| 213 | Type *ArgTy = OutArg->getType()->getPointerElementType(); |
| 214 | |
| 215 | // Skip this argument if converting it will push us over the register |
| 216 | // count to return limit. |
| 217 | |
| 218 | // TODO: This is an approximation. When legalized this could be more. We |
| 219 | // can ask TLI for exactly how many. |
| 220 | unsigned ArgNumRegs = DL->getTypeStoreSize(ArgTy) / 4; |
| 221 | if (ArgNumRegs + ReturnNumRegs > MaxNumRetRegs) |
| 222 | continue; |
| 223 | |
| 224 | // An argument is convertible only if all exit blocks are able to replace |
| 225 | // it. |
| 226 | for (ReturnInst *RI : Returns) { |
| 227 | BasicBlock *BB = RI->getParent(); |
| 228 | |
| 229 | MemDepResult Q = MDA->getPointerDependencyFrom(MemoryLocation(OutArg), |
| 230 | true, BB->end(), BB, RI); |
| 231 | StoreInst *SI = nullptr; |
| 232 | if (Q.isDef()) |
| 233 | SI = dyn_cast<StoreInst>(Q.getInst()); |
| 234 | |
| 235 | if (SI) { |
| 236 | DEBUG(dbgs() << "Found out argument store: " << *SI << '\n'); |
| 237 | ReplaceableStores.emplace_back(RI, SI); |
| 238 | } else { |
| 239 | ThisReplaceable = false; |
| 240 | break; |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | if (!ThisReplaceable) |
| 245 | continue; // Try the next argument candidate. |
| 246 | |
| 247 | for (std::pair<ReturnInst *, StoreInst *> Store : ReplaceableStores) { |
| 248 | Value *ReplVal = Store.second->getValueOperand(); |
| 249 | |
| 250 | auto &ValVec = Replacements[Store.first]; |
| 251 | if (llvm::find_if(ValVec, |
| 252 | [OutArg](const std::pair<Argument *, Value *> &Entry) { |
| 253 | return Entry.first == OutArg;}) != ValVec.end()) { |
| 254 | DEBUG(dbgs() << "Saw multiple out arg stores" << *OutArg << '\n'); |
| 255 | // It is possible to see stores to the same argument multiple times, |
| 256 | // but we expect these would have been optimized out already. |
| 257 | ThisReplaceable = false; |
| 258 | break; |
| 259 | } |
| 260 | |
| 261 | ValVec.emplace_back(OutArg, ReplVal); |
| 262 | Store.second->eraseFromParent(); |
| 263 | } |
| 264 | |
| 265 | if (ThisReplaceable) { |
| 266 | ReturnTypes.push_back(ArgTy); |
| 267 | OutArgIndexes.insert(OutArg->getArgNo()); |
| 268 | ++NumOutArgumentsReplaced; |
| 269 | Changing = true; |
| 270 | } |
| 271 | } |
| 272 | } while (Changing); |
| 273 | |
| 274 | if (Replacements.empty()) |
| 275 | return false; |
| 276 | |
| 277 | LLVMContext &Ctx = F.getParent()->getContext(); |
| 278 | StructType *NewRetTy = StructType::create(Ctx, ReturnTypes, F.getName()); |
| 279 | |
| 280 | FunctionType *NewFuncTy = FunctionType::get(NewRetTy, |
| 281 | F.getFunctionType()->params(), |
| 282 | F.isVarArg()); |
| 283 | |
| 284 | DEBUG(dbgs() << "Computed new return type: " << *NewRetTy << '\n'); |
| 285 | |
| 286 | Function *NewFunc = Function::Create(NewFuncTy, Function::PrivateLinkage, |
| 287 | F.getName() + ".body"); |
| 288 | F.getParent()->getFunctionList().insert(F.getIterator(), NewFunc); |
| 289 | NewFunc->copyAttributesFrom(&F); |
| 290 | NewFunc->setComdat(F.getComdat()); |
| 291 | |
| 292 | // We want to preserve the function and param attributes, but need to strip |
| 293 | // off any return attributes, e.g. zeroext doesn't make sense with a struct. |
| 294 | NewFunc->stealArgumentListFrom(F); |
| 295 | |
| 296 | AttrBuilder RetAttrs; |
| 297 | RetAttrs.addAttribute(Attribute::SExt); |
| 298 | RetAttrs.addAttribute(Attribute::ZExt); |
| 299 | RetAttrs.addAttribute(Attribute::NoAlias); |
| 300 | NewFunc->removeAttributes(AttributeList::ReturnIndex, RetAttrs); |
| 301 | // TODO: How to preserve metadata? |
| 302 | |
| 303 | // Move the body of the function into the new rewritten function, and replace |
| 304 | // this function with a stub. |
| 305 | NewFunc->getBasicBlockList().splice(NewFunc->begin(), F.getBasicBlockList()); |
| 306 | |
| 307 | for (std::pair<ReturnInst *, ReplacementVec> &Replacement : Replacements) { |
| 308 | ReturnInst *RI = Replacement.first; |
| 309 | IRBuilder<> B(RI); |
| 310 | B.SetCurrentDebugLocation(RI->getDebugLoc()); |
| 311 | |
| 312 | int RetIdx = 0; |
| 313 | Value *NewRetVal = UndefValue::get(NewRetTy); |
| 314 | |
| 315 | Value *RetVal = RI->getReturnValue(); |
| 316 | if (RetVal) |
| 317 | NewRetVal = B.CreateInsertValue(NewRetVal, RetVal, RetIdx++); |
| 318 | |
| 319 | for (std::pair<Argument *, Value *> ReturnPoint : Replacement.second) { |
| 320 | NewRetVal = B.CreateInsertValue(NewRetVal, ReturnPoint.second, RetIdx++); |
| 321 | } |
| 322 | |
| 323 | if (RetVal) |
| 324 | RI->setOperand(0, NewRetVal); |
| 325 | else { |
| 326 | B.CreateRet(NewRetVal); |
| 327 | RI->eraseFromParent(); |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | SmallVector<Value *, 16> StubCallArgs; |
| 332 | for (Argument &Arg : F.args()) { |
| 333 | if (OutArgIndexes.count(Arg.getArgNo())) { |
| 334 | // It's easier to preserve the type of the argument list. We rely on |
| 335 | // DeadArgumentElimination to take care of these. |
| 336 | StubCallArgs.push_back(UndefValue::get(Arg.getType())); |
| 337 | } else { |
| 338 | StubCallArgs.push_back(&Arg); |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | BasicBlock *StubBB = BasicBlock::Create(Ctx, "", &F); |
| 343 | IRBuilder<> B(StubBB); |
| 344 | CallInst *StubCall = B.CreateCall(NewFunc, StubCallArgs); |
| 345 | |
| 346 | int RetIdx = RetTy->isVoidTy() ? 0 : 1; |
| 347 | for (Argument &Arg : F.args()) { |
| 348 | if (!OutArgIndexes.count(Arg.getArgNo())) |
| 349 | continue; |
| 350 | |
| 351 | auto *EltTy = Arg.getType()->getPointerElementType(); |
| 352 | unsigned Align = Arg.getParamAlignment(); |
| 353 | if (Align == 0) |
| 354 | Align = DL->getABITypeAlignment(EltTy); |
| 355 | |
| 356 | Value *Val = B.CreateExtractValue(StubCall, RetIdx++); |
| 357 | B.CreateAlignedStore(Val, &Arg, Align); |
| 358 | } |
| 359 | |
| 360 | if (!RetTy->isVoidTy()) { |
| 361 | B.CreateRet(B.CreateExtractValue(StubCall, 0)); |
| 362 | } else { |
| 363 | B.CreateRetVoid(); |
| 364 | } |
| 365 | |
| 366 | // The function is now a stub we want to inline. |
| 367 | F.addFnAttr(Attribute::AlwaysInline); |
| 368 | |
| 369 | ++NumOutArgumentFunctionsReplaced; |
| 370 | return true; |
| 371 | } |
| 372 | |
| 373 | FunctionPass *llvm::createAMDGPURewriteOutArgumentsPass() { |
| 374 | return new AMDGPURewriteOutArguments(); |
| 375 | } |