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