Handle arguments passed in through the va_arg area
[oota-llvm.git] / lib / Transforms / IPO / DeadArgumentElimination.cpp
1 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
2 //
3 // This pass deletes dead arguments from internal functions.  Dead argument
4 // elimination removes arguments which are directly dead, as well as arguments
5 // only passed into function calls as dead arguments of other functions.
6 //
7 // This pass is often useful as a cleanup pass to run after aggressive
8 // interprocedural passes, which add possibly-dead arguments.
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Transforms/IPO.h"
13 #include "llvm/Module.h"
14 #include "llvm/Pass.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constant.h"
17 #include "llvm/iOther.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/Support/CallSite.h"
20 #include "Support/Statistic.h"
21 #include "Support/iterator"
22 #include <set>
23
24 namespace {
25   Statistic<> NumArgumentsEliminated("deadargelim", "Number of args removed");
26
27   struct DAE : public Pass {
28     bool run(Module &M);
29   };
30   RegisterOpt<DAE> X("deadargelim", "Dead Argument Elimination");
31 }
32
33 // createDeadArgEliminationPass - This pass removes arguments from functions
34 // which are not used by the body of the function.
35 //
36 Pass *createDeadArgEliminationPass() { return new DAE(); }
37
38
39 // FunctionArgumentsIntrinsicallyAlive - Return true if the arguments of the
40 // specified function are intrinsically alive.
41 //
42 // We consider arguments of non-internal functions to be intrinsically alive as
43 // well as arguments to functions which have their "address taken".
44 //
45 static bool FunctionArgumentsIntrinsicallyAlive(const Function &F) {
46   if (!F.hasInternalLinkage()) return true;
47
48   for (Value::use_const_iterator I = F.use_begin(), E = F.use_end(); I!=E; ++I){
49     // If this use is anything other than a call site, the function is alive.
50     CallSite CS = CallSite::get(const_cast<User*>(*I));
51     if (!CS.getInstruction()) return true;  // Not a valid call site?
52
53     // If the function is PASSED IN as an argument, its address has been taken
54     for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end(); AI != E;
55          ++AI)
56       if (AI->get() == &F) return true;
57   }
58   return false;
59 }
60
61 namespace {
62   enum ArgumentLiveness { Alive, MaybeLive, Dead };
63 }
64
65 // getArgumentLiveness - Inspect an argument, determining if is known Alive
66 // (used in a computation), MaybeLive (only passed as an argument to a call), or
67 // Dead (not used).
68 static ArgumentLiveness getArgumentLiveness(const Argument &A) {
69   if (A.use_empty()) return Dead;  // First check, directly dead?
70
71   // Scan through all of the uses, looking for non-argument passing uses.
72   for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
73     CallSite CS = CallSite::get(const_cast<User*>(*I));
74     if (!CS.getInstruction()) {
75       // If its used by something that is not a call or invoke, it's alive!
76       return Alive;
77     }
78     // If it's an indirect call, mark it alive...
79     Function *Callee = CS.getCalledFunction();
80     if (!Callee) return Alive;
81
82     // Check to see if it's passed through a va_arg area: if so, we cannot
83     // remove it.
84     unsigned NumFixedArgs = Callee->getFunctionType()->getNumParams();
85     for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
86          AI != CS.arg_end(); ++AI)
87       if (AI->get() == &A) // If passed through va_arg area, we cannot remove it
88         return Alive;
89   }
90
91   return MaybeLive;  // It must be used, but only as argument to a function
92 }
93
94 // isMaybeLiveArgumentNowAlive - Check to see if Arg is alive.  At this point,
95 // we know that the only uses of Arg are to be passed in as an argument to a
96 // function call.  Check to see if the formal argument passed in is in the
97 // LiveArguments set.  If so, return true.
98 //
99 static bool isMaybeLiveArgumentNowAlive(Argument *Arg,
100                                      const std::set<Argument*> &LiveArguments) {
101   for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
102     CallSite CS = CallSite::get(*I);
103
104     // We know that this can only be used for direct calls...
105     Function *Callee = cast<Function>(CS.getCalledValue());
106
107     // Loop over all of the arguments (because Arg may be passed into the call
108     // multiple times) and check to see if any are now alive...
109     CallSite::arg_iterator CSAI = CS.arg_begin();
110     for (Function::aiterator AI = Callee->abegin(), E = Callee->aend();
111          AI != E; ++AI, ++CSAI)
112       // If this is the argument we are looking for, check to see if it's alive
113       if (*CSAI == Arg && LiveArguments.count(AI))
114         return true;
115   }
116   return false;
117 }
118
119 // MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
120 // Mark it live in the specified sets and recursively mark arguments in callers
121 // live that are needed to pass in a value.
122 //
123 static void MarkArgumentLive(Argument *Arg,
124                              std::set<Argument*> &MaybeLiveArguments,
125                              std::set<Argument*> &LiveArguments,
126                           const std::multimap<Function*, CallSite> &CallSites) {
127   DEBUG(std::cerr << "  MaybeLive argument now live: " << Arg->getName()<<"\n");
128   assert(MaybeLiveArguments.count(Arg) && !LiveArguments.count(Arg) &&
129          "Arg not MaybeLive?");
130   MaybeLiveArguments.erase(Arg);
131   LiveArguments.insert(Arg);
132   
133   // Loop over all of the call sites of the function, making any arguments
134   // passed in to provide a value for this argument live as necessary.
135   //
136   Function *Fn = Arg->getParent();
137   unsigned ArgNo = std::distance(Fn->abegin(), Function::aiterator(Arg));
138
139   std::multimap<Function*, CallSite>::const_iterator I =
140     CallSites.lower_bound(Fn);
141   for (; I != CallSites.end() && I->first == Fn; ++I) {
142     const CallSite &CS = I->second;
143     if (Argument *ActualArg = dyn_cast<Argument>(*(CS.arg_begin()+ArgNo)))
144       if (MaybeLiveArguments.count(ActualArg))
145         MarkArgumentLive(ActualArg, MaybeLiveArguments, LiveArguments,
146                          CallSites);
147   }
148 }
149
150 // RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
151 // specified by the DeadArguments list.  Transform the function and all of the
152 // callees of the function to not have these arguments.
153 //
154 static void RemoveDeadArgumentsFromFunction(Function *F,
155                                             std::set<Argument*> &DeadArguments){
156   // Start by computing a new prototype for the function, which is the same as
157   // the old function, but has fewer arguments.
158   const FunctionType *FTy = F->getFunctionType();
159   std::vector<const Type*> Params;
160
161   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
162     if (!DeadArguments.count(I))
163       Params.push_back(I->getType());
164
165   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params,
166                                          FTy->isVarArg());
167   
168   // Create the new function body and insert it into the module...
169   Function *NF = new Function(NFTy, Function::InternalLinkage, F->getName());
170   F->getParent()->getFunctionList().insert(F, NF);
171
172   // Loop over all of the callers of the function, transforming the call sites
173   // to pass in a smaller number of arguments into the new function.
174   //
175   while (!F->use_empty()) {
176     CallSite CS = CallSite::get(F->use_back());
177     Instruction *Call = CS.getInstruction();
178     CS.setCalledFunction(NF);   // Reduce the uses count of F
179     
180     // Loop over the operands, deleting dead ones...
181     CallSite::arg_iterator AI = CS.arg_begin();
182     for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
183       if (DeadArguments.count(I)) {        // Remove operands for dead arguments
184         AI = Call->op_erase(AI);
185       }  else {
186         ++AI;  // Leave live operands alone...
187       }
188   }
189
190   // Since we have now created the new function, splice the body of the old
191   // function right into the new function, leaving the old rotting hulk of the
192   // function empty.
193   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
194
195   // Loop over the argument list, transfering uses of the old arguments over to
196   // the new arguments, also transfering over the names as well.  While we're at
197   // it, remove the dead arguments from the DeadArguments list.
198   //
199   for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
200        I != E; ++I)
201     if (!DeadArguments.count(I)) {
202       // If this is a live argument, move the name and users over to the new
203       // version.
204       I->replaceAllUsesWith(I2);
205       I2->setName(I->getName());
206       ++I2;
207     } else {
208       // If this argument is dead, replace any uses of it with null constants
209       // (these are guaranteed to only be operands to call instructions which
210       // will later be simplified).
211       I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
212       DeadArguments.erase(I);
213     }
214
215   // Now that the old function is dead, delete it.
216   F->getParent()->getFunctionList().erase(F);
217 }
218
219 bool DAE::run(Module &M) {
220   // First phase: loop through the module, determining which arguments are live.
221   // We assume all arguments are dead unless proven otherwise (allowing us to
222   // determing that dead arguments passed into recursive functions are dead).
223   //
224   std::set<Argument*> LiveArguments, MaybeLiveArguments, DeadArguments;
225   std::multimap<Function*, CallSite> CallSites;
226
227   DEBUG(std::cerr << "DAE - Determining liveness\n");
228   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
229     Function &Fn = *I;
230     // If the function is intrinsically alive, just mark the arguments alive.
231     if (FunctionArgumentsIntrinsicallyAlive(Fn)) {
232       for (Function::aiterator AI = Fn.abegin(), E = Fn.aend(); AI != E; ++AI)
233         LiveArguments.insert(AI);
234       DEBUG(std::cerr << "  Args intrinsically live for fn: " << Fn.getName()
235                       << "\n");
236     } else {
237       DEBUG(std::cerr << "  Inspecting args for fn: " << Fn.getName() << "\n");
238
239       // If it is not intrinsically alive, we know that all users of the
240       // function are call sites.  Mark all of the arguments live which are
241       // directly used, and keep track of all of the call sites of this function
242       // if there are any arguments we assume that are dead.
243       //
244       bool AnyMaybeLiveArgs = false;
245       for (Function::aiterator AI = Fn.abegin(), E = Fn.aend(); AI != E; ++AI)
246         switch (getArgumentLiveness(*AI)) {
247         case Alive:
248           DEBUG(std::cerr << "    Arg live by use: " << AI->getName() << "\n");
249           LiveArguments.insert(AI);
250           break;
251         case Dead:
252           DEBUG(std::cerr << "    Arg definately dead: " <<AI->getName()<<"\n");
253           DeadArguments.insert(AI);
254           break;
255         case MaybeLive:
256           DEBUG(std::cerr << "    Arg only passed to calls: "
257                           << AI->getName() << "\n");
258           AnyMaybeLiveArgs = true;
259           MaybeLiveArguments.insert(AI);
260           break;
261         }
262
263       // If there are any "MaybeLive" arguments, we need to check callees of
264       // this function when/if they become alive.  Record which functions are
265       // callees...
266       if (AnyMaybeLiveArgs)
267         for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end();
268              I != E; ++I)
269           CallSites.insert(std::make_pair(&Fn, CallSite::get(*I)));
270     }
271   }
272
273   // Now we loop over all of the MaybeLive arguments, promoting them to be live
274   // arguments if one of the calls that uses the arguments to the calls they are
275   // passed into requires them to be live.  Of course this could make other
276   // arguments live, so process callers recursively.
277   //
278   // Because elements can be removed from the MaybeLiveArguments list, copy it
279   // to a temporary vector.
280   //
281   std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
282                                     MaybeLiveArguments.end());
283   for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
284     Argument *MLA = TmpArgList[i];
285     if (MaybeLiveArguments.count(MLA) &&
286         isMaybeLiveArgumentNowAlive(MLA, LiveArguments)) {
287       MarkArgumentLive(MLA, MaybeLiveArguments, LiveArguments, CallSites);
288     }
289   }
290
291   // Recover memory early...
292   CallSites.clear();
293
294   // At this point, we know that all arguments in DeadArguments and
295   // MaybeLiveArguments are dead.  If the two sets are empty, there is nothing
296   // to do.
297   if (MaybeLiveArguments.empty() && DeadArguments.empty())
298     return false;
299   
300   // Otherwise, compact into one set, and start eliminating the arguments from
301   // the functions.
302   DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
303   MaybeLiveArguments.clear();
304
305   NumArgumentsEliminated += DeadArguments.size();
306   while (!DeadArguments.empty())
307     RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent(),
308                                     DeadArguments);
309   return true;
310 }