blob: 9f659d5afaa38161b4ed949d1ac8a8e4258535ac [file] [log] [blame]
Gordon Henriksena8a118b2008-05-08 17:46:35 +00001//===-- StructRetPromotion.cpp - Promote sret arguments ------------------===//
Devang Patelca891ec2008-02-29 23:34:08 +00002//
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//
Gordon Henriksena8a118b2008-05-08 17:46:35 +000010// This pass finds functions that return a struct (using a pointer to the struct
11// as the first argument of the function, marked with the 'sret' attribute) and
12// replaces them with a new function that simply returns each of the elements of
13// that struct (using multiple return values).
14//
15// This pass works under a number of conditions:
16// 1. The returned struct must not contain other structs
17// 2. The returned struct must only be used to load values from
18// 3. The placeholder struct passed in is the result of an alloca
19//
Devang Patelca891ec2008-02-29 23:34:08 +000020//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "sretpromotion"
23#include "llvm/Transforms/IPO.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000026#include "llvm/LLVMContext.h"
Devang Patelca891ec2008-02-29 23:34:08 +000027#include "llvm/Module.h"
28#include "llvm/CallGraphSCCPass.h"
29#include "llvm/Instructions.h"
30#include "llvm/Analysis/CallGraph.h"
31#include "llvm/Support/CallSite.h"
32#include "llvm/Support/CFG.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/SmallVector.h"
Devang Patel98a6e062008-03-04 17:44:37 +000036#include "llvm/ADT/Statistic.h"
Daniel Dunbar460f6562009-07-26 09:48:23 +000037#include "llvm/Support/raw_ostream.h"
Devang Patelca891ec2008-02-29 23:34:08 +000038using namespace llvm;
39
Devang Patel98a6e062008-03-04 17:44:37 +000040STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
41STATISTIC(NumSRET , "Number of sret promoted");
Devang Patelca891ec2008-02-29 23:34:08 +000042namespace {
43 /// SRETPromotion - This pass removes sret parameter and updates
44 /// function to use multiple return value.
45 ///
Nick Lewycky6726b6d2009-10-25 06:33:48 +000046 struct SRETPromotion : public CallGraphSCCPass {
Devang Patelca891ec2008-02-29 23:34:08 +000047 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 CallGraphSCCPass::getAnalysisUsage(AU);
49 }
50
Chris Lattner5095e3d2009-08-31 00:19:58 +000051 virtual bool runOnSCC(std::vector<CallGraphNode *> &SCC);
Devang Patelca891ec2008-02-29 23:34:08 +000052 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000053 SRETPromotion() : CallGraphSCCPass(&ID) {}
Devang Patelca891ec2008-02-29 23:34:08 +000054
55 private:
Chris Lattner5095e3d2009-08-31 00:19:58 +000056 CallGraphNode *PromoteReturn(CallGraphNode *CGN);
Devang Patelca891ec2008-02-29 23:34:08 +000057 bool isSafeToUpdateAllCallers(Function *F);
58 Function *cloneFunctionBody(Function *F, const StructType *STy);
Chris Lattner5095e3d2009-08-31 00:19:58 +000059 CallGraphNode *updateCallSites(Function *F, Function *NF);
Devang Patela9fe8bb2008-03-04 21:32:09 +000060 bool nestedStructType(const StructType *STy);
Devang Patelca891ec2008-02-29 23:34:08 +000061 };
Devang Patelca891ec2008-02-29 23:34:08 +000062}
63
Dan Gohman844731a2008-05-13 00:00:25 +000064char SRETPromotion::ID = 0;
65static RegisterPass<SRETPromotion>
66X("sretpromotion", "Promote sret arguments to multiple ret values");
67
Devang Patelca891ec2008-02-29 23:34:08 +000068Pass *llvm::createStructRetPromotionPass() {
69 return new SRETPromotion();
70}
71
Chris Lattner5095e3d2009-08-31 00:19:58 +000072bool SRETPromotion::runOnSCC(std::vector<CallGraphNode *> &SCC) {
Devang Patelca891ec2008-02-29 23:34:08 +000073 bool Changed = false;
74
75 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
Chris Lattner5095e3d2009-08-31 00:19:58 +000076 if (CallGraphNode *NewNode = PromoteReturn(SCC[i])) {
77 SCC[i] = NewNode;
78 Changed = true;
79 }
Devang Patelca891ec2008-02-29 23:34:08 +000080
81 return Changed;
82}
83
84/// PromoteReturn - This method promotes function that uses StructRet paramater
Chris Lattner5095e3d2009-08-31 00:19:58 +000085/// into a function that uses multiple return values.
86CallGraphNode *SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
Devang Patelca891ec2008-02-29 23:34:08 +000087 Function *F = CGN->getFunction();
88
Rafael Espindolabb46f522009-01-15 20:18:42 +000089 if (!F || F->isDeclaration() || !F->hasLocalLinkage())
Chris Lattner5095e3d2009-08-31 00:19:58 +000090 return 0;
Devang Patelca891ec2008-02-29 23:34:08 +000091
92 // Make sure that function returns struct.
Devang Patel41e23972008-03-03 21:46:28 +000093 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
Chris Lattner5095e3d2009-08-31 00:19:58 +000094 return 0;
Devang Patelca891ec2008-02-29 23:34:08 +000095
David Greene09d70db2010-01-05 01:27:54 +000096 DEBUG(dbgs() << "SretPromotion: Looking at sret function "
Daniel Dunbar460f6562009-07-26 09:48:23 +000097 << F->getName() << "\n");
Matthijs Kooijman81ec2482008-08-07 15:14:04 +000098
Chris Lattner5095e3d2009-08-31 00:19:58 +000099 assert(F->getReturnType() == Type::getVoidTy(F->getContext()) &&
100 "Invalid function return type");
Devang Patelca891ec2008-02-29 23:34:08 +0000101 Function::arg_iterator AI = F->arg_begin();
102 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
Chris Lattner5095e3d2009-08-31 00:19:58 +0000103 assert(FArgType && "Invalid sret parameter type");
Devang Patelca891ec2008-02-29 23:34:08 +0000104 const llvm::StructType *STy =
105 dyn_cast<StructType>(FArgType->getElementType());
Chris Lattner5095e3d2009-08-31 00:19:58 +0000106 assert(STy && "Invalid sret parameter element type");
Devang Patelca891ec2008-02-29 23:34:08 +0000107
108 // Check if it is ok to perform this promotion.
Devang Patel98a6e062008-03-04 17:44:37 +0000109 if (isSafeToUpdateAllCallers(F) == false) {
David Greene09d70db2010-01-05 01:27:54 +0000110 DEBUG(dbgs() << "SretPromotion: Not all callers can be updated\n");
Devang Patel98a6e062008-03-04 17:44:37 +0000111 NumRejectedSRETUses++;
Chris Lattner5095e3d2009-08-31 00:19:58 +0000112 return 0;
Devang Patel98a6e062008-03-04 17:44:37 +0000113 }
Devang Patelca891ec2008-02-29 23:34:08 +0000114
David Greene09d70db2010-01-05 01:27:54 +0000115 DEBUG(dbgs() << "SretPromotion: sret argument will be promoted\n");
Devang Pateldf1d15c2008-03-04 17:48:11 +0000116 NumSRET++;
Devang Patelca891ec2008-02-29 23:34:08 +0000117 // [1] Replace use of sret parameter
Owen Anderson50dead02009-07-15 23:53:25 +0000118 AllocaInst *TheAlloca = new AllocaInst(STy, NULL, "mrv",
119 F->getEntryBlock().begin());
Devang Patelca891ec2008-02-29 23:34:08 +0000120 Value *NFirstArg = F->arg_begin();
121 NFirstArg->replaceAllUsesWith(TheAlloca);
122
Devang Patel98a6e062008-03-04 17:44:37 +0000123 // [2] Find and replace ret instructions
Devang Patelca891ec2008-02-29 23:34:08 +0000124 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
125 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
126 Instruction *I = BI;
127 ++BI;
128 if (isa<ReturnInst>(I)) {
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000129 Value *NV = new LoadInst(TheAlloca, "mrv.ld", I);
Owen Anderson1d0be152009-08-13 21:58:54 +0000130 ReturnInst *NR = ReturnInst::Create(F->getContext(), NV, I);
Devang Patelca891ec2008-02-29 23:34:08 +0000131 I->replaceAllUsesWith(NR);
132 I->eraseFromParent();
133 }
134 }
135
Devang Patel98a6e062008-03-04 17:44:37 +0000136 // [3] Create the new function body and insert it into the module.
Devang Patelca891ec2008-02-29 23:34:08 +0000137 Function *NF = cloneFunctionBody(F, STy);
138
Devang Patel98a6e062008-03-04 17:44:37 +0000139 // [4] Update all call sites to use new function
Chris Lattner5095e3d2009-08-31 00:19:58 +0000140 CallGraphNode *NF_CFN = updateCallSites(F, NF);
Devang Patelca891ec2008-02-29 23:34:08 +0000141
Chris Lattner5095e3d2009-08-31 00:19:58 +0000142 CallGraph &CG = getAnalysis<CallGraph>();
143 NF_CFN->stealCalledFunctionsFrom(CG[F]);
144
145 delete CG.removeFunctionFromModule(F);
146 return NF_CFN;
Devang Patelca891ec2008-02-29 23:34:08 +0000147}
148
Duncan Sands33af59d2008-05-09 12:20:10 +0000149// Check if it is ok to perform this promotion.
Devang Patelca891ec2008-02-29 23:34:08 +0000150bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
151
152 if (F->use_empty())
153 // No users. OK to modify signature.
154 return true;
155
156 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
157 FnUseI != FnUseE; ++FnUseI) {
Matthijs Kooijman257da0a2008-06-05 08:48:32 +0000158 // The function is passed in as an argument to (possibly) another function,
159 // we can't change it!
Devang Patelca891ec2008-02-29 23:34:08 +0000160 CallSite CS = CallSite::get(*FnUseI);
161 Instruction *Call = CS.getInstruction();
Matthijs Kooijman47c6fd72008-06-05 08:57:20 +0000162 // The function is used by something else than a call or invoke instruction,
163 // we can't change it!
Gabor Greifedc4d692009-01-22 21:35:57 +0000164 if (!Call || !CS.isCallee(FnUseI))
Matthijs Kooijman47c6fd72008-06-05 08:57:20 +0000165 return false;
Devang Patelca891ec2008-02-29 23:34:08 +0000166 CallSite::arg_iterator AI = CS.arg_begin();
167 Value *FirstArg = *AI;
168
169 if (!isa<AllocaInst>(FirstArg))
170 return false;
171
172 // Check FirstArg's users.
173 for (Value::use_iterator ArgI = FirstArg->use_begin(),
174 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
175
176 // If FirstArg user is a CallInst that does not correspond to current
177 // call site then this function F is not suitable for sret promotion.
178 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
179 if (CI != Call)
180 return false;
181 }
182 // If FirstArg user is a GEP whose all users are not LoadInst then
183 // this function F is not suitable for sret promotion.
184 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
Devang Patele0a6a3f2008-03-05 23:39:23 +0000185 // TODO : Use dom info and insert PHINodes to collect get results
186 // from multiple call sites for this GEP.
187 if (GEP->getParent() != Call->getParent())
188 return false;
Devang Patelca891ec2008-02-29 23:34:08 +0000189 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
190 GEPI != GEPE; ++GEPI)
191 if (!isa<LoadInst>(GEPI))
192 return false;
193 }
194 // Any other FirstArg users make this function unsuitable for sret
195 // promotion.
196 else
197 return false;
198 }
199 }
200
201 return true;
202}
203
204/// cloneFunctionBody - Create a new function based on F and
205/// insert it into module. Remove first argument. Use STy as
206/// the return type for new function.
207Function *SRETPromotion::cloneFunctionBody(Function *F,
208 const StructType *STy) {
209
Devang Patelca891ec2008-02-29 23:34:08 +0000210 const FunctionType *FTy = F->getFunctionType();
211 std::vector<const Type*> Params;
212
Devang Patel05988662008-09-25 21:00:45 +0000213 // Attributes - Keep track of the parameter attributes for the arguments.
214 SmallVector<AttributeWithIndex, 8> AttributesVec;
215 const AttrListPtr &PAL = F->getAttributes();
Devang Patel2a4821b2008-03-03 18:36:03 +0000216
217 // Add any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000218 if (Attributes attrs = PAL.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +0000219 AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000220
Devang Patelca891ec2008-02-29 23:34:08 +0000221 // Skip first argument.
222 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
223 ++I;
Devang Patel8f9b5512008-03-12 00:07:03 +0000224 // 0th parameter attribute is reserved for return type.
225 // 1th parameter attribute is for first 1st sret argument.
226 unsigned ParamIndex = 2;
Devang Patelca891ec2008-02-29 23:34:08 +0000227 while (I != E) {
228 Params.push_back(I->getType());
Devang Patel19c87462008-09-26 22:53:05 +0000229 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
Devang Patel05988662008-09-25 21:00:45 +0000230 AttributesVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
Devang Patelca891ec2008-02-29 23:34:08 +0000231 ++I;
Devang Patel2a4821b2008-03-03 18:36:03 +0000232 ++ParamIndex;
Devang Patelca891ec2008-02-29 23:34:08 +0000233 }
234
Devang Patel19c87462008-09-26 22:53:05 +0000235 // Add any fn attributes.
236 if (Attributes attrs = PAL.getFnAttributes())
237 AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
238
239
Owen Andersondebcb012009-07-29 22:17:13 +0000240 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
Matthijs Kooijman7d942002008-08-07 16:01:23 +0000241 Function *NF = Function::Create(NFTy, F->getLinkage());
242 NF->takeName(F);
Duncan Sands28c3cff2008-05-26 19:58:59 +0000243 NF->copyAttributesFrom(F);
Devang Patel05988662008-09-25 21:00:45 +0000244 NF->setAttributes(AttrListPtr::get(AttributesVec.begin(), AttributesVec.end()));
Devang Patelca891ec2008-02-29 23:34:08 +0000245 F->getParent()->getFunctionList().insert(F, NF);
246 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
247
248 // Replace arguments
249 I = F->arg_begin();
250 E = F->arg_end();
251 Function::arg_iterator NI = NF->arg_begin();
252 ++I;
253 while (I != E) {
Chris Lattner5095e3d2009-08-31 00:19:58 +0000254 I->replaceAllUsesWith(NI);
255 NI->takeName(I);
256 ++I;
257 ++NI;
Devang Patelca891ec2008-02-29 23:34:08 +0000258 }
259
260 return NF;
261}
262
263/// updateCallSites - Update all sites that call F to use NF.
Chris Lattner5095e3d2009-08-31 00:19:58 +0000264CallGraphNode *SRETPromotion::updateCallSites(Function *F, Function *NF) {
Duncan Sandsa9c32512008-09-08 11:08:09 +0000265 CallGraph &CG = getAnalysis<CallGraph>();
Devang Patelca891ec2008-02-29 23:34:08 +0000266 SmallVector<Value*, 16> Args;
267
Devang Patel05988662008-09-25 21:00:45 +0000268 // Attributes - Keep track of the parameter attributes for the arguments.
269 SmallVector<AttributeWithIndex, 8> ArgAttrsVec;
Devang Patel2a4821b2008-03-03 18:36:03 +0000270
Chris Lattner5095e3d2009-08-31 00:19:58 +0000271 // Get a new callgraph node for NF.
272 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
273
Matthijs Kooijmanc1f1d462008-08-14 15:03:05 +0000274 while (!F->use_empty()) {
275 CallSite CS = CallSite::get(*F->use_begin());
Devang Patelca891ec2008-02-29 23:34:08 +0000276 Instruction *Call = CS.getInstruction();
277
Devang Patel05988662008-09-25 21:00:45 +0000278 const AttrListPtr &PAL = F->getAttributes();
Devang Patel2a4821b2008-03-03 18:36:03 +0000279 // Add any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000280 if (Attributes attrs = PAL.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +0000281 ArgAttrsVec.push_back(AttributeWithIndex::get(0, attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000282
Devang Patelca891ec2008-02-29 23:34:08 +0000283 // Copy arguments, however skip first one.
284 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
285 Value *FirstCArg = *AI;
286 ++AI;
Devang Patel8f9b5512008-03-12 00:07:03 +0000287 // 0th parameter attribute is reserved for return type.
288 // 1th parameter attribute is for first 1st sret argument.
289 unsigned ParamIndex = 2;
Devang Patelca891ec2008-02-29 23:34:08 +0000290 while (AI != AE) {
291 Args.push_back(*AI);
Devang Patel19c87462008-09-26 22:53:05 +0000292 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
Devang Patel05988662008-09-25 21:00:45 +0000293 ArgAttrsVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000294 ++ParamIndex;
Devang Patelca891ec2008-02-29 23:34:08 +0000295 ++AI;
296 }
297
Devang Patel19c87462008-09-26 22:53:05 +0000298 // Add any function attributes.
299 if (Attributes attrs = PAL.getFnAttributes())
300 ArgAttrsVec.push_back(AttributeWithIndex::get(~0, attrs));
Chris Lattner58d74912008-03-12 17:45:29 +0000301
Devang Patel05988662008-09-25 21:00:45 +0000302 AttrListPtr NewPAL = AttrListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());
Chris Lattner58d74912008-03-12 17:45:29 +0000303
Devang Patelca891ec2008-02-29 23:34:08 +0000304 // Build new call instruction.
305 Instruction *New;
306 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000307 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
308 Args.begin(), Args.end(), "", Call);
Devang Patelca891ec2008-02-29 23:34:08 +0000309 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000310 cast<InvokeInst>(New)->setAttributes(NewPAL);
Devang Patelca891ec2008-02-29 23:34:08 +0000311 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000312 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Devang Patelca891ec2008-02-29 23:34:08 +0000313 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000314 cast<CallInst>(New)->setAttributes(NewPAL);
Devang Patelca891ec2008-02-29 23:34:08 +0000315 if (cast<CallInst>(Call)->isTailCall())
316 cast<CallInst>(New)->setTailCall();
317 }
318 Args.clear();
Devang Patel544b92b2008-03-04 19:12:58 +0000319 ArgAttrsVec.clear();
Devang Patelca891ec2008-02-29 23:34:08 +0000320 New->takeName(Call);
321
Duncan Sandsa9c32512008-09-08 11:08:09 +0000322 // Update the callgraph to know that the callsite has been transformed.
Chris Lattnerda230cb2009-09-01 18:52:39 +0000323 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
324 CalleeNode->removeCallEdgeFor(Call);
325 CalleeNode->addCalledFunction(New, NF_CGN);
Chris Lattner7c8c1ba2009-09-01 18:50:55 +0000326
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000327 // Update all users of sret parameter to extract value using extractvalue.
Devang Patelca891ec2008-02-29 23:34:08 +0000328 for (Value::use_iterator UI = FirstCArg->use_begin(),
329 UE = FirstCArg->use_end(); UI != UE; ) {
330 User *U2 = *UI++;
331 CallInst *C2 = dyn_cast<CallInst>(U2);
332 if (C2 && (C2 == Call))
333 continue;
Chris Lattner5095e3d2009-08-31 00:19:58 +0000334
Chris Lattner7c8c1ba2009-09-01 18:50:55 +0000335 GetElementPtrInst *UGEP = cast<GetElementPtrInst>(U2);
336 ConstantInt *Idx = cast<ConstantInt>(UGEP->getOperand(2));
337 Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),
338 "evi", UGEP);
339 while(!UGEP->use_empty()) {
340 // isSafeToUpdateAllCallers has checked that all GEP uses are
341 // LoadInsts
342 LoadInst *L = cast<LoadInst>(*UGEP->use_begin());
343 L->replaceAllUsesWith(GR);
344 L->eraseFromParent();
Devang Patelca891ec2008-02-29 23:34:08 +0000345 }
Chris Lattner7c8c1ba2009-09-01 18:50:55 +0000346 UGEP->eraseFromParent();
347 continue;
Devang Patelca891ec2008-02-29 23:34:08 +0000348 }
349 Call->eraseFromParent();
350 }
Chris Lattner5095e3d2009-08-31 00:19:58 +0000351
352 return NF_CGN;
Devang Patelca891ec2008-02-29 23:34:08 +0000353}
Devang Patela9fe8bb2008-03-04 21:32:09 +0000354
355/// nestedStructType - Return true if STy includes any
356/// other aggregate types
357bool SRETPromotion::nestedStructType(const StructType *STy) {
358 unsigned Num = STy->getNumElements();
359 for (unsigned i = 0; i < Num; i++) {
360 const Type *Ty = STy->getElementType(i);
Owen Anderson1d0be152009-08-13 21:58:54 +0000361 if (!Ty->isSingleValueType() && Ty != Type::getVoidTy(STy->getContext()))
Devang Patela9fe8bb2008-03-04 21:32:09 +0000362 return true;
363 }
364 return false;
365}