Changes For Bug 352
[oota-llvm.git] / lib / Transforms / IPO / ArgumentPromotion.cpp
1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass promotes "by reference" arguments to be "by value" arguments.  In
11 // practice, this means looking for internal functions that have pointer
12 // arguments.  If we can prove, through the use of alias analysis, that that an
13 // argument is *only* loaded, then we can pass the value into the function
14 // instead of the address of the value.  This can cause recursive simplification
15 // of code and lead to the elimination of allocas (especially in C++ template
16 // code like the STL).
17 //
18 // This pass also handles aggregate arguments that are passed into a function,
19 // scalarizing them if the elements of the aggregate are only loaded.  Note that
20 // we refuse to scalarize aggregates which would require passing in more than
21 // three operands to the function, because we don't want to pass thousands of
22 // operands for a large array or structure!
23 //
24 // Note that this transformation could also be done for arguments that are only
25 // stored to (returning the value instead), but we do not currently handle that
26 // case.  This case would be best handled when and if we start supporting
27 // multiple return values from functions.
28 //
29 //===----------------------------------------------------------------------===//
30
31 #define DEBUG_TYPE "argpromotion"
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/Constants.h"
34 #include "llvm/DerivedTypes.h"
35 #include "llvm/Module.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Support/CallSite.h"
41 #include "llvm/Support/CFG.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/ADT/DepthFirstIterator.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include <set>
47 using namespace llvm;
48
49 namespace {
50   Statistic<> NumArgumentsPromoted("argpromotion",
51                                    "Number of pointer arguments promoted");
52   Statistic<> NumAggregatesPromoted("argpromotion",
53                                     "Number of aggregate arguments promoted");
54   Statistic<> NumArgumentsDead("argpromotion",
55                                "Number of dead pointer args eliminated");
56
57   /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
58   ///
59   class ArgPromotion : public Pass {
60     // WorkList - The set of internal functions that we have yet to process.  As
61     // we eliminate arguments from a function, we push all callers into this set
62     // so that the by-reference argument can be bubbled out as far as possible.
63     // This set contains only internal functions.
64     std::set<Function*> WorkList;
65   public:
66     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67       AU.addRequired<AliasAnalysis>();
68       AU.addRequired<TargetData>();
69     }
70
71     virtual bool run(Module &M);
72   private:
73     bool PromoteArguments(Function *F);
74     bool isSafeToPromoteArgument(Argument *Arg) const;  
75     void DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
76   };
77
78   RegisterOpt<ArgPromotion> X("argpromotion",
79                               "Promote 'by reference' arguments to scalars");
80 }
81
82 Pass *llvm::createArgumentPromotionPass() {
83   return new ArgPromotion();
84 }
85
86 bool ArgPromotion::run(Module &M) {
87   bool Changed = false;
88   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
89     if (I->hasInternalLinkage())
90       WorkList.insert(I);
91   
92   while (!WorkList.empty()) {
93     Function *F = *WorkList.begin();
94     WorkList.erase(WorkList.begin());
95
96     if (PromoteArguments(F))    // Attempt to promote an argument.
97       Changed = true;           // Remember that we changed something.
98   }
99   
100   return Changed;
101 }
102
103 /// PromoteArguments - This method checks the specified function to see if there
104 /// are any promotable arguments and if it is safe to promote the function (for
105 /// example, all callers are direct).  If safe to promote some arguments, it
106 /// calls the DoPromotion method.
107 ///
108 bool ArgPromotion::PromoteArguments(Function *F) {
109   assert(F->hasInternalLinkage() && "We can only process internal functions!");
110
111   // First check: see if there are any pointer arguments!  If not, quick exit.
112   std::vector<Argument*> PointerArgs;
113   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
114     if (isa<PointerType>(I->getType()))
115       PointerArgs.push_back(I);
116   if (PointerArgs.empty()) return false;
117
118   // Second check: make sure that all callers are direct callers.  We can't
119   // transform functions that have indirect callers.
120   for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
121        UI != E; ++UI) {
122     CallSite CS = CallSite::get(*UI);
123     if (!CS.getInstruction())       // "Taking the address" of the function
124       return false;
125
126     // Ensure that this call site is CALLING the function, not passing it as
127     // an argument.
128     for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
129          AI != E; ++AI)
130       if (*AI == F) return false;   // Passing the function address in!
131   }
132
133   // Check to see which arguments are promotable.  If an argument is not
134   // promotable, remove it from the PointerArgs vector.
135   for (unsigned i = 0; i != PointerArgs.size(); ++i)
136     if (!isSafeToPromoteArgument(PointerArgs[i])) {
137       std::swap(PointerArgs[i--], PointerArgs.back());
138       PointerArgs.pop_back();
139     }
140
141   // No promotable pointer arguments.
142   if (PointerArgs.empty()) return false;
143
144   // Okay, promote all of the arguments are rewrite the callees!
145   DoPromotion(F, PointerArgs);
146   return true;
147 }
148
149
150 /// isSafeToPromoteArgument - As you might guess from the name of this method,
151 /// it checks to see if it is both safe and useful to promote the argument.
152 /// This method limits promotion of aggregates to only promote up to three
153 /// elements of the aggregate in order to avoid exploding the number of
154 /// arguments passed in.
155 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
156   // We can only promote this argument if all of the uses are loads, or are GEP
157   // instructions (with constant indices) that are subsequently loaded.
158   std::vector<LoadInst*> Loads;
159   std::vector<std::vector<ConstantInt*> > GEPIndices;
160   for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
161        UI != E; ++UI)
162     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
163       if (LI->isVolatile()) return false;  // Don't hack volatile loads
164       Loads.push_back(LI);
165     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
166       if (GEP->use_empty()) {
167         // Dead GEP's cause trouble later.  Just remove them if we run into
168         // them.
169         getAnalysis<AliasAnalysis>().deleteValue(GEP);
170         GEP->getParent()->getInstList().erase(GEP);
171         return isSafeToPromoteArgument(Arg);
172       }
173       // Ensure that all of the indices are constants.
174       std::vector<ConstantInt*> Operands;
175       for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
176         if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
177           Operands.push_back(C);
178         else
179           return false;  // Not a constant operand GEP!
180
181       // Ensure that the only users of the GEP are load instructions.
182       for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
183            UI != E; ++UI)
184         if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
185           if (LI->isVolatile()) return false;  // Don't hack volatile loads
186           Loads.push_back(LI);
187         } else {
188           return false;
189         }
190
191       // See if there is already a GEP with these indices.  If not, check to
192       // make sure that we aren't promoting too many elements.  If so, nothing
193       // to do.
194       if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
195           GEPIndices.end()) {
196         if (GEPIndices.size() == 3) {
197           DEBUG(std::cerr << "argpromotion disable promoting argument '"
198                 << Arg->getName() << "' because it would require adding more "
199                 << "than 3 arguments to the function.\n");
200           // We limit aggregate promotion to only promoting up to three elements
201           // of the aggregate.
202           return false;
203         }
204         GEPIndices.push_back(Operands);
205       }
206     } else {
207       return false;  // Not a load or a GEP.
208     }
209
210   if (Loads.empty()) return true;  // No users, this is a dead argument.
211
212   // Okay, now we know that the argument is only used by load instructions.  Use
213   // alias analysis to check to see if the pointer is guaranteed to not be
214   // modified from entry of the function to each of the load instructions.
215   Function &F = *Arg->getParent();
216
217   // Because there could be several/many load instructions, remember which
218   // blocks we know to be transparent to the load.
219   std::set<BasicBlock*> TranspBlocks;
220
221   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
222   TargetData &TD = getAnalysis<TargetData>();
223
224   for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
225     // Check to see if the load is invalidated from the start of the block to
226     // the load itself.
227     LoadInst *Load = Loads[i];
228     BasicBlock *BB = Load->getParent();
229
230     const PointerType *LoadTy =
231       cast<PointerType>(Load->getOperand(0)->getType());
232     unsigned LoadSize = TD.getTypeSize(LoadTy->getElementType());
233
234     if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
235       return false;  // Pointer is invalidated!
236
237     // Now check every path from the entry block to the load for transparency.
238     // To do this, we perform a depth first search on the inverse CFG from the
239     // loading block.
240     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
241       for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
242              E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
243         if (AA.canBasicBlockModify(**I, Arg, LoadSize))
244           return false;
245   }
246
247   // If the path from the entry of the function to each load is free of
248   // instructions that potentially invalidate the load, we can make the
249   // transformation!
250   return true;
251 }
252
253 namespace {
254   /// GEPIdxComparator - Provide a strong ordering for GEP indices.  All Value*
255   /// elements are instances of ConstantInt.
256   ///
257   struct GEPIdxComparator {
258     bool operator()(const std::vector<Value*> &LHS,
259                     const std::vector<Value*> &RHS) const {
260       unsigned idx = 0;
261       for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
262         if (LHS[idx] != RHS[idx]) {
263           return cast<ConstantInt>(LHS[idx])->getRawValue() < 
264                  cast<ConstantInt>(RHS[idx])->getRawValue();
265         }
266       }
267
268       // Return less than if we ran out of stuff in LHS and we didn't run out of
269       // stuff in RHS.
270       return idx == LHS.size() && idx != RHS.size();
271     }
272   };
273 }
274
275
276 /// DoPromotion - This method actually performs the promotion of the specified
277 /// arguments.  At this point, we know that it's safe to do so.
278 void ArgPromotion::DoPromotion(Function *F, std::vector<Argument*> &Args2Prom) {
279   std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
280   
281   // Start by computing a new prototype for the function, which is the same as
282   // the old function, but has modified arguments.
283   const FunctionType *FTy = F->getFunctionType();
284   std::vector<const Type*> Params;
285
286   typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
287
288   // ScalarizedElements - If we are promoting a pointer that has elements
289   // accessed out of it, keep track of which elements are accessed so that we
290   // can add one argument for each.
291   //
292   // Arguments that are directly loaded will have a zero element value here, to
293   // handle cases where there are both a direct load and GEP accesses.
294   //
295   std::map<Argument*, ScalarizeTable> ScalarizedElements;
296
297   // OriginalLoads - Keep track of a representative load instruction from the
298   // original function so that we can tell the alias analysis implementation
299   // what the new GEP/Load instructions we are inserting look like.
300   std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
301
302   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
303     if (!ArgsToPromote.count(I)) {
304       Params.push_back(I->getType());
305     } else if (I->use_empty()) {
306       ++NumArgumentsDead;
307     } else {
308       // Okay, this is being promoted.  Check to see if there are any GEP uses
309       // of the argument.
310       ScalarizeTable &ArgIndices = ScalarizedElements[I];
311       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
312            ++UI) {
313         Instruction *User = cast<Instruction>(*UI);
314         assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
315         std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
316         ArgIndices.insert(Indices);
317         LoadInst *OrigLoad;
318         if (LoadInst *L = dyn_cast<LoadInst>(User))
319           OrigLoad = L;
320         else
321           OrigLoad = cast<LoadInst>(User->use_back());
322         OriginalLoads[Indices] = OrigLoad;
323       }
324
325       // Add a parameter to the function for each element passed in.
326       for (ScalarizeTable::iterator SI = ArgIndices.begin(),
327              E = ArgIndices.end(); SI != E; ++SI)
328         Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
329
330       if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
331         ++NumArgumentsPromoted;
332       else
333         ++NumAggregatesPromoted;
334     }
335
336   const Type *RetTy = FTy->getReturnType();
337
338   // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
339   // have zero fixed arguments.
340   bool ExtraArgHack = false;
341   if (Params.empty() && FTy->isVarArg()) {
342     ExtraArgHack = true;
343     Params.push_back(Type::IntTy);
344   }
345   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
346   
347    // Create the new function body and insert it into the module...
348   Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
349   F->getParent()->getFunctionList().insert(F, NF);
350
351   // Get the alias analysis information that we need to update to reflect our
352   // changes.
353   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
354
355   // Loop over all of the callers of the function, transforming the call sites
356   // to pass in the loaded pointers.
357   //
358   std::vector<Value*> Args;
359   while (!F->use_empty()) {
360     CallSite CS = CallSite::get(F->use_back());
361     Instruction *Call = CS.getInstruction();
362
363     // Make sure the caller of this function is revisited now that we promoted
364     // arguments in a callee of it.
365     if (Call->getParent()->getParent()->hasInternalLinkage())
366       WorkList.insert(Call->getParent()->getParent());
367     
368     // Loop over the operands, inserting GEP and loads in the caller as
369     // appropriate.
370     CallSite::arg_iterator AI = CS.arg_begin();
371     for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)
372       if (!ArgsToPromote.count(I))
373         Args.push_back(*AI);          // Unmodified argument
374       else if (!I->use_empty()) {
375         // Non-dead argument: insert GEPs and loads as appropriate.
376         ScalarizeTable &ArgIndices = ScalarizedElements[I];
377         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
378                E = ArgIndices.end(); SI != E; ++SI) {
379           Value *V = *AI;
380           LoadInst *OrigLoad = OriginalLoads[*SI];
381           if (!SI->empty()) {
382             V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
383             AA.copyValue(OrigLoad->getOperand(0), V);
384           }
385           Args.push_back(new LoadInst(V, V->getName()+".val", Call));
386           AA.copyValue(OrigLoad, Args.back());
387         }
388       }
389
390     if (ExtraArgHack)
391       Args.push_back(Constant::getNullValue(Type::IntTy));
392
393     // Push any varargs arguments on the list
394     for (; AI != CS.arg_end(); ++AI)
395       Args.push_back(*AI);
396
397     Instruction *New;
398     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
399       New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
400                            Args, "", Call);
401     } else {
402       New = new CallInst(NF, Args, "", Call);
403     }
404     Args.clear();
405
406     // Update the alias analysis implementation to know that we are replacing
407     // the old call with a new one.
408     AA.replaceWithNewValue(Call, New);
409
410     if (!Call->use_empty()) {
411       Call->replaceAllUsesWith(New);
412       std::string Name = Call->getName();
413       Call->setName("");
414       New->setName(Name);
415     }
416     
417     // Finally, remove the old call from the program, reducing the use-count of
418     // F.
419     Call->getParent()->getInstList().erase(Call);
420   }
421
422   // Since we have now created the new function, splice the body of the old
423   // function right into the new function, leaving the old rotting hulk of the
424   // function empty.
425   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
426
427   // Loop over the argument list, transfering uses of the old arguments over to
428   // the new arguments, also transfering over the names as well.
429   //
430   for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
431        I != E; ++I)
432     if (!ArgsToPromote.count(I)) {
433       // If this is an unmodified argument, move the name and users over to the
434       // new version.
435       I->replaceAllUsesWith(I2);
436       I2->setName(I->getName());
437       AA.replaceWithNewValue(I, I2);
438       ++I2;
439     } else if (I->use_empty()) {
440       AA.deleteValue(I);
441     } else {
442       // Otherwise, if we promoted this argument, then all users are load
443       // instructions, and all loads should be using the new argument that we
444       // added.
445       ScalarizeTable &ArgIndices = ScalarizedElements[I];
446
447       while (!I->use_empty()) {
448         if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
449           assert(ArgIndices.begin()->empty() &&
450                  "Load element should sort to front!");
451           I2->setName(I->getName()+".val");
452           LI->replaceAllUsesWith(I2);
453           AA.replaceWithNewValue(LI, I2);
454           LI->getParent()->getInstList().erase(LI);
455           DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
456                           << "' in function '" << F->getName() << "'\n");
457         } else {
458           GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
459           std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
460
461           unsigned ArgNo = 0;
462           Function::aiterator TheArg = I2;
463           for (ScalarizeTable::iterator It = ArgIndices.begin();
464                *It != Operands; ++It, ++TheArg) {
465             assert(It != ArgIndices.end() && "GEP not handled??");
466           }
467
468           std::string NewName = I->getName();
469           for (unsigned i = 0, e = Operands.size(); i != e; ++i)
470             if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
471               NewName += "."+itostr((int64_t)CI->getRawValue());
472             else
473               NewName += ".x";
474           TheArg->setName(NewName+".val");
475
476           DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
477                           << "' of function '" << F->getName() << "'\n");
478
479           // All of the uses must be load instructions.  Replace them all with
480           // the argument specified by ArgNo.
481           while (!GEP->use_empty()) {
482             LoadInst *L = cast<LoadInst>(GEP->use_back());
483             L->replaceAllUsesWith(TheArg);
484             AA.replaceWithNewValue(L, TheArg);
485             L->getParent()->getInstList().erase(L);
486           }
487           AA.deleteValue(GEP);
488           GEP->getParent()->getInstList().erase(GEP);
489         }
490       }
491
492       // If we inserted a new pointer type, it's possible that IT could be
493       // promoted too.  Also, increment I2 past all of the arguments added for
494       // this promoted pointer.
495       for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i, ++I2)
496         if (isa<PointerType>(I2->getType()))
497           WorkList.insert(NF);
498     }
499
500   // Notify the alias analysis implementation that we inserted a new argument.
501   if (ExtraArgHack)
502     AA.copyValue(Constant::getNullValue(Type::IntTy), NF->abegin());
503
504
505   // Tell the alias analysis that the old function is about to disappear.
506   AA.replaceWithNewValue(F, NF);
507
508   // Now that the old function is dead, delete it.
509   F->getParent()->getFunctionList().erase(F);
510 }