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