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