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