Collect statistics.
[oota-llvm.git] / lib / Transforms / IPO / StructRetPromotion.cpp
1 //===-- StructRetPromotion.cpp - Promote sret arguments -000000------------===//
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 // TODO : Describe this pass.
11 //===----------------------------------------------------------------------===//
12
13 #define DEBUG_TYPE "sretpromotion"
14 #include "llvm/Transforms/IPO.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ParamAttrsList.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Compiler.h"
29 using namespace llvm;
30
31 STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
32 STATISTIC(NumSRET , "Number of sret promoted");
33 namespace {
34   /// SRETPromotion - This pass removes sret parameter and updates
35   /// function to use multiple return value.
36   ///
37   struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
38     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
39       CallGraphSCCPass::getAnalysisUsage(AU);
40     }
41
42     virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
43     static char ID; // Pass identification, replacement for typeid
44     SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
45
46   private:
47     bool PromoteReturn(CallGraphNode *CGN);
48     bool isSafeToUpdateAllCallers(Function *F);
49     Function *cloneFunctionBody(Function *F, const StructType *STy);
50     void updateCallSites(Function *F, Function *NF);
51   };
52
53   char SRETPromotion::ID = 0;
54   RegisterPass<SRETPromotion> X("sretpromotion",
55                                "Promote sret arguments to multiple ret values");
56 }
57
58 Pass *llvm::createStructRetPromotionPass() {
59   return new SRETPromotion();
60 }
61
62 bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
63   bool Changed = false;
64
65   for (unsigned i = 0, e = SCC.size(); i != e; ++i)
66     Changed |= PromoteReturn(SCC[i]);
67
68   return Changed;
69 }
70
71 /// PromoteReturn - This method promotes function that uses StructRet paramater 
72 /// into a function that uses mulitple return value.
73 bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
74   Function *F = CGN->getFunction();
75
76   // Make sure that it is local to this module.
77   if (!F || !F->hasInternalLinkage())
78     return false;
79
80   // Make sure that function returns struct.
81   if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
82     return false;
83
84   assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
85   Function::arg_iterator AI = F->arg_begin();
86   const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
87   assert (FArgType && "Invalid sret paramater type");
88   const llvm::StructType *STy = 
89     dyn_cast<StructType>(FArgType->getElementType());
90   assert (STy && "Invalid sret parameter element type");
91
92   // Check if it is ok to perform this promotion.
93   if (isSafeToUpdateAllCallers(F) == false) {
94     NumRejectedSRETUses++;
95     return false;
96   }
97
98   // [1] Replace use of sret parameter 
99   AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv", 
100                                           F->getEntryBlock().begin());
101   Value *NFirstArg = F->arg_begin();
102   NFirstArg->replaceAllUsesWith(TheAlloca);
103
104   // [2] Find and replace ret instructions
105   SmallVector<Value *,4> RetVals;
106   for (Function::iterator FI = F->begin(), FE = F->end();  FI != FE; ++FI) 
107     for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
108       Instruction *I = BI;
109       ++BI;
110       if (isa<ReturnInst>(I)) {
111         RetVals.clear();
112         for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
113           SmallVector<Value*, 2> GEPIdx;
114           GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
115           GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
116           Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(),
117                                                "mrv.gep", I);
118           Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
119           RetVals.push_back(NV);
120         }
121     
122         ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I);
123         I->replaceAllUsesWith(NR);
124         I->eraseFromParent();
125       }
126     }
127
128   // [3] Create the new function body and insert it into the module.
129   Function *NF = cloneFunctionBody(F, STy);
130
131   // [4] Update all call sites to use new function
132   updateCallSites(F, NF);
133
134   F->eraseFromParent();
135   getAnalysis<CallGraph>().changeFunction(F, NF);
136   return true;
137 }
138
139   // Check if it is ok to perform this promotion.
140 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
141
142   if (F->use_empty())
143     // No users. OK to modify signature.
144     return true;
145
146   for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
147        FnUseI != FnUseE; ++FnUseI) {
148
149     CallSite CS = CallSite::get(*FnUseI);
150     Instruction *Call = CS.getInstruction();
151     CallSite::arg_iterator AI = CS.arg_begin();
152     Value *FirstArg = *AI;
153
154     if (!isa<AllocaInst>(FirstArg))
155       return false;
156
157     // Check FirstArg's users.
158     for (Value::use_iterator ArgI = FirstArg->use_begin(), 
159            ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
160
161       // If FirstArg user is a CallInst that does not correspond to current
162       // call site then this function F is not suitable for sret promotion.
163       if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
164         if (CI != Call)
165           return false;
166       }
167       // If FirstArg user is a GEP whose all users are not LoadInst then
168       // this function F is not suitable for sret promotion.
169       else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
170         for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
171              GEPI != GEPE; ++GEPI) 
172           if (!isa<LoadInst>(GEPI))
173             return false;
174       } 
175       // Any other FirstArg users make this function unsuitable for sret 
176       // promotion.
177       else
178         return false;
179     }
180   }
181
182   return true;
183 }
184
185 /// cloneFunctionBody - Create a new function based on F and
186 /// insert it into module. Remove first argument. Use STy as
187 /// the return type for new function.
188 Function *SRETPromotion::cloneFunctionBody(Function *F, 
189                                            const StructType *STy) {
190
191   const FunctionType *FTy = F->getFunctionType();
192   std::vector<const Type*> Params;
193
194   // ParamAttrs - Keep track of the parameter attributes for the arguments.
195   ParamAttrsVector ParamAttrsVec;
196   const ParamAttrsList *PAL = F->getParamAttrs();
197
198   // Add any return attributes.
199   if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
200     ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
201
202   // Skip first argument.
203   Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
204   ++I;
205   unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
206   while (I != E) {
207     Params.push_back(I->getType());
208     if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(ParamIndex) : 
209         ParamAttr::None)
210       ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
211     ++I;
212     ++ParamIndex;
213   }
214
215   FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
216   Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
217   NF->setCallingConv(F->getCallingConv());
218   NF->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
219   F->getParent()->getFunctionList().insert(F, NF);
220   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
221
222   // Replace arguments
223   I = F->arg_begin();
224   E = F->arg_end();
225   Function::arg_iterator NI = NF->arg_begin();
226   ++I;
227   while (I != E) {
228       I->replaceAllUsesWith(NI);
229       NI->takeName(I);
230       ++I;
231       ++NI;
232   }
233
234   return NF;
235 }
236
237 /// updateCallSites - Update all sites that call F to use NF.
238 void SRETPromotion::updateCallSites(Function *F, Function *NF) {
239
240   SmallVector<Value*, 16> Args;
241
242   // ParamAttrs - Keep track of the parameter attributes for the arguments.
243   ParamAttrsVector ParamAttrsVec;
244
245   for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) {
246     CallSite CS = CallSite::get(*FUI);
247     ++FUI;
248     Instruction *Call = CS.getInstruction();
249
250     const ParamAttrsList *PAL = F->getParamAttrs();
251     // Add any return attributes.
252     if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
253       ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
254
255     // Copy arguments, however skip first one.
256     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
257     Value *FirstCArg = *AI;
258     ++AI;
259     unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
260     while (AI != AE) {
261       Args.push_back(*AI); 
262       if (ParameterAttributes Attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
263           ParamAttr::None)
264         ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
265       ++ParamIndex;
266       ++AI;
267     }
268
269     // Build new call instruction.
270     Instruction *New;
271     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
272       New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
273                            Args.begin(), Args.end(), "", Call);
274       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
275       cast<InvokeInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
276     } else {
277       New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
278       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
279       cast<CallInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
280       if (cast<CallInst>(Call)->isTailCall())
281         cast<CallInst>(New)->setTailCall();
282     }
283     Args.clear();
284     ParamAttrsVec.clear();
285     New->takeName(Call);
286
287     // Update all users of sret parameter to extract value using getresult.
288     for (Value::use_iterator UI = FirstCArg->use_begin(), 
289            UE = FirstCArg->use_end(); UI != UE; ) {
290       User *U2 = *UI++;
291       CallInst *C2 = dyn_cast<CallInst>(U2);
292       if (C2 && (C2 == Call))
293         continue;
294       else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
295         Value *GR = new GetResultInst(New, 5, "xxx", UGEP);
296         for (Value::use_iterator GI = UGEP->use_begin(),
297                GE = UGEP->use_end(); GI != GE; ++GI) {
298           if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
299             L->replaceAllUsesWith(GR);
300             L->eraseFromParent();
301           }
302         }
303         UGEP->eraseFromParent();
304       }
305       else assert( 0 && "Unexpected sret parameter use");
306     }
307     Call->eraseFromParent();
308   }
309 }