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