Fix many bugs when merging weak-strong and weak-weak pairs. We now merge all
[oota-llvm.git] / lib / Transforms / IPO / StructRetPromotion.cpp
1 //===-- StructRetPromotion.cpp - Promote sret arguments -------------------===//
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 // 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 //
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "sretpromotion"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/LLVMContext.h"
27 #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"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/raw_ostream.h"
38 using namespace llvm;
39
40 STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
41 STATISTIC(NumSRET , "Number of sret promoted");
42 namespace {
43   /// SRETPromotion - This pass removes sret parameter and updates
44   /// function to use multiple return value.
45   ///
46   struct SRETPromotion : public CallGraphSCCPass {
47     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48       CallGraphSCCPass::getAnalysisUsage(AU);
49     }
50
51     virtual bool runOnSCC(CallGraphSCC &SCC);
52     static char ID; // Pass identification, replacement for typeid
53     SRETPromotion() : CallGraphSCCPass(ID) {}
54
55   private:
56     CallGraphNode *PromoteReturn(CallGraphNode *CGN);
57     bool isSafeToUpdateAllCallers(Function *F);
58     Function *cloneFunctionBody(Function *F, const StructType *STy);
59     CallGraphNode *updateCallSites(Function *F, Function *NF);
60   };
61 }
62
63 char SRETPromotion::ID = 0;
64 INITIALIZE_PASS(SRETPromotion, "sretpromotion",
65                 "Promote sret arguments to multiple ret values", false, false);
66
67 Pass *llvm::createStructRetPromotionPass() {
68   return new SRETPromotion();
69 }
70
71 bool SRETPromotion::runOnSCC(CallGraphSCC &SCC) {
72   bool Changed = false;
73
74   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
75     if (CallGraphNode *NewNode = PromoteReturn(*I)) {
76       SCC.ReplaceNode(*I, NewNode);
77       Changed = true;
78     }
79
80   return Changed;
81 }
82
83 /// PromoteReturn - This method promotes function that uses StructRet paramater 
84 /// into a function that uses multiple return values.
85 CallGraphNode *SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
86   Function *F = CGN->getFunction();
87
88   if (!F || F->isDeclaration() || !F->hasLocalLinkage())
89     return 0;
90
91   // Make sure that function returns struct.
92   if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
93     return 0;
94
95   DEBUG(dbgs() << "SretPromotion: Looking at sret function " 
96         << F->getName() << "\n");
97
98   assert(F->getReturnType()->isVoidTy() && "Invalid function return type");
99   Function::arg_iterator AI = F->arg_begin();
100   const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
101   assert(FArgType && "Invalid sret parameter type");
102   const llvm::StructType *STy = 
103     dyn_cast<StructType>(FArgType->getElementType());
104   assert(STy && "Invalid sret parameter element type");
105
106   // Check if it is ok to perform this promotion.
107   if (isSafeToUpdateAllCallers(F) == false) {
108     DEBUG(dbgs() << "SretPromotion: Not all callers can be updated\n");
109     ++NumRejectedSRETUses;
110     return 0;
111   }
112
113   DEBUG(dbgs() << "SretPromotion: sret argument will be promoted\n");
114   ++NumSRET;
115   // [1] Replace use of sret parameter 
116   AllocaInst *TheAlloca = new AllocaInst(STy, NULL, "mrv", 
117                                          F->getEntryBlock().begin());
118   Value *NFirstArg = F->arg_begin();
119   NFirstArg->replaceAllUsesWith(TheAlloca);
120
121   // [2] Find and replace ret instructions
122   for (Function::iterator FI = F->begin(), FE = F->end();  FI != FE; ++FI) 
123     for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
124       Instruction *I = BI;
125       ++BI;
126       if (isa<ReturnInst>(I)) {
127         Value *NV = new LoadInst(TheAlloca, "mrv.ld", I);
128         ReturnInst *NR = ReturnInst::Create(F->getContext(), NV, I);
129         I->replaceAllUsesWith(NR);
130         I->eraseFromParent();
131       }
132     }
133
134   // [3] Create the new function body and insert it into the module.
135   Function *NF = cloneFunctionBody(F, STy);
136
137   // [4] Update all call sites to use new function
138   CallGraphNode *NF_CFN = updateCallSites(F, NF);
139
140   CallGraph &CG = getAnalysis<CallGraph>();
141   NF_CFN->stealCalledFunctionsFrom(CG[F]);
142
143   delete CG.removeFunctionFromModule(F);
144   return NF_CFN;
145 }
146
147 // Check if it is ok to perform this promotion.
148 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
149
150   if (F->use_empty())
151     // No users. OK to modify signature.
152     return true;
153
154   for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
155        FnUseI != FnUseE; ++FnUseI) {
156     // The function is passed in as an argument to (possibly) another function,
157     // we can't change it!
158     CallSite CS(*FnUseI);
159     Instruction *Call = CS.getInstruction();
160     // The function is used by something else than a call or invoke instruction,
161     // we can't change it!
162     if (!Call || !CS.isCallee(FnUseI))
163       return false;
164     CallSite::arg_iterator AI = CS.arg_begin();
165     Value *FirstArg = *AI;
166
167     if (!isa<AllocaInst>(FirstArg))
168       return false;
169
170     // Check FirstArg's users.
171     for (Value::use_iterator ArgI = FirstArg->use_begin(), 
172            ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
173       User *U = *ArgI;
174       // If FirstArg user is a CallInst that does not correspond to current
175       // call site then this function F is not suitable for sret promotion.
176       if (CallInst *CI = dyn_cast<CallInst>(U)) {
177         if (CI != Call)
178           return false;
179       }
180       // If FirstArg user is a GEP whose all users are not LoadInst then
181       // this function F is not suitable for sret promotion.
182       else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
183         // TODO : Use dom info and insert PHINodes to collect get results
184         // from multiple call sites for this GEP.
185         if (GEP->getParent() != Call->getParent())
186           return false;
187         for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
188              GEPI != GEPE; ++GEPI) 
189           if (!isa<LoadInst>(*GEPI))
190             return false;
191       } 
192       // Any other FirstArg users make this function unsuitable for sret 
193       // promotion.
194       else
195         return false;
196     }
197   }
198
199   return true;
200 }
201
202 /// cloneFunctionBody - Create a new function based on F and
203 /// insert it into module. Remove first argument. Use STy as
204 /// the return type for new function.
205 Function *SRETPromotion::cloneFunctionBody(Function *F, 
206                                            const StructType *STy) {
207
208   const FunctionType *FTy = F->getFunctionType();
209   std::vector<const Type*> Params;
210
211   // Attributes - Keep track of the parameter attributes for the arguments.
212   SmallVector<AttributeWithIndex, 8> AttributesVec;
213   const AttrListPtr &PAL = F->getAttributes();
214
215   // Add any return attributes.
216   if (Attributes attrs = PAL.getRetAttributes())
217     AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
218
219   // Skip first argument.
220   Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
221   ++I;
222   // 0th parameter attribute is reserved for return type.
223   // 1th parameter attribute is for first 1st sret argument.
224   unsigned ParamIndex = 2; 
225   while (I != E) {
226     Params.push_back(I->getType());
227     if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
228       AttributesVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
229     ++I;
230     ++ParamIndex;
231   }
232
233   // Add any fn attributes.
234   if (Attributes attrs = PAL.getFnAttributes())
235     AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
236
237
238   FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
239   Function *NF = Function::Create(NFTy, F->getLinkage());
240   NF->takeName(F);
241   NF->copyAttributesFrom(F);
242   NF->setAttributes(AttrListPtr::get(AttributesVec.begin(), AttributesVec.end()));
243   F->getParent()->getFunctionList().insert(F, NF);
244   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
245
246   // Replace arguments
247   I = F->arg_begin();
248   E = F->arg_end();
249   Function::arg_iterator NI = NF->arg_begin();
250   ++I;
251   while (I != E) {
252     I->replaceAllUsesWith(NI);
253     NI->takeName(I);
254     ++I;
255     ++NI;
256   }
257
258   return NF;
259 }
260
261 /// updateCallSites - Update all sites that call F to use NF.
262 CallGraphNode *SRETPromotion::updateCallSites(Function *F, Function *NF) {
263   CallGraph &CG = getAnalysis<CallGraph>();
264   SmallVector<Value*, 16> Args;
265
266   // Attributes - Keep track of the parameter attributes for the arguments.
267   SmallVector<AttributeWithIndex, 8> ArgAttrsVec;
268
269   // Get a new callgraph node for NF.
270   CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
271
272   while (!F->use_empty()) {
273     CallSite CS(*F->use_begin());
274     Instruction *Call = CS.getInstruction();
275
276     const AttrListPtr &PAL = F->getAttributes();
277     // Add any return attributes.
278     if (Attributes attrs = PAL.getRetAttributes())
279       ArgAttrsVec.push_back(AttributeWithIndex::get(0, attrs));
280
281     // Copy arguments, however skip first one.
282     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
283     Value *FirstCArg = *AI;
284     ++AI;
285     // 0th parameter attribute is reserved for return type.
286     // 1th parameter attribute is for first 1st sret argument.
287     unsigned ParamIndex = 2; 
288     while (AI != AE) {
289       Args.push_back(*AI); 
290       if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
291         ArgAttrsVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
292       ++ParamIndex;
293       ++AI;
294     }
295
296     // Add any function attributes.
297     if (Attributes attrs = PAL.getFnAttributes())
298       ArgAttrsVec.push_back(AttributeWithIndex::get(~0, attrs));
299     
300     AttrListPtr NewPAL = AttrListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());
301     
302     // Build new call instruction.
303     Instruction *New;
304     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
305       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
306                                Args.begin(), Args.end(), "", Call);
307       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
308       cast<InvokeInst>(New)->setAttributes(NewPAL);
309     } else {
310       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
311       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
312       cast<CallInst>(New)->setAttributes(NewPAL);
313       if (cast<CallInst>(Call)->isTailCall())
314         cast<CallInst>(New)->setTailCall();
315     }
316     Args.clear();
317     ArgAttrsVec.clear();
318     New->takeName(Call);
319
320     // Update the callgraph to know that the callsite has been transformed.
321     CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
322     CalleeNode->removeCallEdgeFor(Call);
323     CalleeNode->addCalledFunction(New, NF_CGN);
324     
325     // Update all users of sret parameter to extract value using extractvalue.
326     for (Value::use_iterator UI = FirstCArg->use_begin(), 
327            UE = FirstCArg->use_end(); UI != UE; ) {
328       User *U2 = *UI++;
329       CallInst *C2 = dyn_cast<CallInst>(U2);
330       if (C2 && (C2 == Call))
331         continue;
332       
333       GetElementPtrInst *UGEP = cast<GetElementPtrInst>(U2);
334       ConstantInt *Idx = cast<ConstantInt>(UGEP->getOperand(2));
335       Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),
336                                            "evi", UGEP);
337       while(!UGEP->use_empty()) {
338         // isSafeToUpdateAllCallers has checked that all GEP uses are
339         // LoadInsts
340         LoadInst *L = cast<LoadInst>(*UGEP->use_begin());
341         L->replaceAllUsesWith(GR);
342         L->eraseFromParent();
343       }
344       UGEP->eraseFromParent();
345       continue;
346     }
347     Call->eraseFromParent();
348   }
349   
350   return NF_CGN;
351 }
352