Put all LLVM code into the llvm namespace, as per bug 109.
[oota-llvm.git] / lib / Transforms / IPO / DeadArgumentElimination.cpp
1 //===-- DeadArgumentElimination.cpp - Eliminate dead 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 deletes dead arguments from internal functions.  Dead argument
11 // elimination removes arguments which are directly dead, as well as arguments
12 // only passed into function calls as dead arguments of other functions.  This
13 // pass also deletes dead arguments in a similar way.
14 //
15 // This pass is often useful as a cleanup pass to run after aggressive
16 // interprocedural passes, which add possibly-dead arguments.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "llvm/Transforms/IPO.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Constant.h"
25 #include "llvm/iOther.h"
26 #include "llvm/iTerminators.h"
27 #include "llvm/Support/CallSite.h"
28 #include "Support/Debug.h"
29 #include "Support/Statistic.h"
30 #include "Support/iterator"
31 #include <set>
32
33 namespace llvm {
34
35 namespace {
36   Statistic<> NumArgumentsEliminated("deadargelim",
37                                      "Number of unread args removed");
38   Statistic<> NumRetValsEliminated("deadargelim",
39                                    "Number of unused return values removed");
40
41   /// DAE - The dead argument elimination pass.
42   ///
43   class DAE : public Pass {
44     /// Liveness enum - During our initial pass over the program, we determine
45     /// that things are either definately alive, definately dead, or in need of
46     /// interprocedural analysis (MaybeLive).
47     ///
48     enum Liveness { Live, MaybeLive, Dead };
49
50     /// LiveArguments, MaybeLiveArguments, DeadArguments - These sets contain
51     /// all of the arguments in the program.  The Dead set contains arguments
52     /// which are completely dead (never used in the function).  The MaybeLive
53     /// set contains arguments which are only passed into other function calls,
54     /// thus may be live and may be dead.  The Live set contains arguments which
55     /// are known to be alive.
56     ///
57     std::set<Argument*> DeadArguments, MaybeLiveArguments, LiveArguments;
58
59     /// DeadRetVal, MaybeLiveRetVal, LifeRetVal - These sets contain all of the
60     /// functions in the program.  The Dead set contains functions whose return
61     /// value is known to be dead.  The MaybeLive set contains functions whose
62     /// return values are only used by return instructions, and the Live set
63     /// contains functions whose return values are used, functions that are
64     /// external, and functions that already return void.
65     ///
66     std::set<Function*> DeadRetVal, MaybeLiveRetVal, LiveRetVal;
67
68     /// InstructionsToInspect - As we mark arguments and return values
69     /// MaybeLive, we keep track of which instructions could make the values
70     /// live here.  Once the entire program has had the return value and
71     /// arguments analyzed, this set is scanned to promote the MaybeLive objects
72     /// to be Live if they really are used.
73     std::vector<Instruction*> InstructionsToInspect;
74
75     /// CallSites - Keep track of the call sites of functions that have
76     /// MaybeLive arguments or return values.
77     std::multimap<Function*, CallSite> CallSites;
78
79   public:
80     bool run(Module &M);
81
82     virtual bool ShouldHackArguments() const { return false; }
83
84   private:
85     Liveness getArgumentLiveness(const Argument &A);
86     bool isMaybeLiveArgumentNowLive(Argument *Arg);
87
88     void SurveyFunction(Function &Fn);
89
90     void MarkArgumentLive(Argument *Arg);
91     void MarkRetValLive(Function *F);
92     void MarkReturnInstArgumentLive(ReturnInst *RI);
93   
94     void RemoveDeadArgumentsFromFunction(Function *F);
95   };
96   RegisterOpt<DAE> X("deadargelim", "Dead Argument Elimination");
97
98   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
99   /// deletes arguments to functions which are external.  This is only for use
100   /// by bugpoint.
101   struct DAH : public DAE {
102     virtual bool ShouldHackArguments() const { return true; }
103   };
104   RegisterPass<DAH> Y("deadarghaX0r",
105                       "Dead Argument Hacking (bugpoint usage only)");
106 }
107
108 /// createDeadArgEliminationPass - This pass removes arguments from functions
109 /// which are not used by the body of the function.
110 ///
111 Pass *createDeadArgEliminationPass() { return new DAE(); }
112 Pass *createDeadArgHackingPass() { return new DAH(); }
113
114 static inline bool CallPassesValueThoughVararg(Instruction *Call,
115                                                const Value *Arg) {
116   CallSite CS = CallSite::get(Call);
117   const Type *CalledValueTy = CS.getCalledValue()->getType();
118   const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
119   unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
120   for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
121        AI != CS.arg_end(); ++AI)
122     if (AI->get() == Arg)
123       return true;
124   return false;
125 }
126
127 // getArgumentLiveness - Inspect an argument, determining if is known Live
128 // (used in a computation), MaybeLive (only passed as an argument to a call), or
129 // Dead (not used).
130 DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
131   if (A.use_empty()) return Dead;  // First check, directly dead?
132
133   // Scan through all of the uses, looking for non-argument passing uses.
134   for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
135     // Return instructions do not immediately effect liveness.
136     if (isa<ReturnInst>(*I))
137       continue;
138
139     CallSite CS = CallSite::get(const_cast<User*>(*I));
140     if (!CS.getInstruction()) {
141       // If its used by something that is not a call or invoke, it's alive!
142       return Live;
143     }
144     // If it's an indirect call, mark it alive...
145     Function *Callee = CS.getCalledFunction();
146     if (!Callee) return Live;
147
148     // Check to see if it's passed through a va_arg area: if so, we cannot
149     // remove it.
150     if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
151       return Live;   // If passed through va_arg area, we cannot remove it
152   }
153
154   return MaybeLive;  // It must be used, but only as argument to a function
155 }
156
157
158 // SurveyFunction - This performs the initial survey of the specified function,
159 // checking out whether or not it uses any of its incoming arguments or whether
160 // any callers use the return value.  This fills in the
161 // (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
162 //
163 // We consider arguments of non-internal functions to be intrinsically alive as
164 // well as arguments to functions which have their "address taken".
165 //
166 void DAE::SurveyFunction(Function &F) {
167   bool FunctionIntrinsicallyLive = false;
168   Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
169
170   if (!F.hasInternalLinkage() &&
171       (!ShouldHackArguments() || F.getIntrinsicID()))
172     FunctionIntrinsicallyLive = true;
173   else 
174     for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
175       // If this use is anything other than a call site, the function is alive.
176       CallSite CS = CallSite::get(*I);
177       Instruction *TheCall = CS.getInstruction();
178       if (!TheCall) {   // Not a direct call site?
179         FunctionIntrinsicallyLive = true;
180         break;
181       }
182
183       // Check to see if the return value is used...
184       if (RetValLiveness != Live)
185         for (Value::use_iterator I = TheCall->use_begin(),
186                E = TheCall->use_end(); I != E; ++I)
187           if (isa<ReturnInst>(cast<Instruction>(*I))) {
188             RetValLiveness = MaybeLive;
189           } else if (isa<CallInst>(cast<Instruction>(*I)) ||
190                      isa<InvokeInst>(cast<Instruction>(*I))) {
191             if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
192                 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
193               RetValLiveness = Live;
194               break;
195             } else {
196               RetValLiveness = MaybeLive;
197             }
198           } else {
199             RetValLiveness = Live;
200             break;
201           }
202       
203       // If the function is PASSED IN as an argument, its address has been taken
204       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
205            AI != E; ++AI)
206         if (AI->get() == &F) {
207           FunctionIntrinsicallyLive = true;
208           break;
209         }
210       if (FunctionIntrinsicallyLive) break;
211     }
212
213   if (FunctionIntrinsicallyLive) {
214     DEBUG(std::cerr << "  Intrinsically live fn: " << F.getName() << "\n");
215     for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
216       LiveArguments.insert(AI);
217     LiveRetVal.insert(&F);
218     return;
219   }
220
221   switch (RetValLiveness) {
222   case Live:      LiveRetVal.insert(&F); break;
223   case MaybeLive: MaybeLiveRetVal.insert(&F); break;
224   case Dead:      DeadRetVal.insert(&F); break;
225   }
226
227   DEBUG(std::cerr << "  Inspecting args for fn: " << F.getName() << "\n");
228
229   // If it is not intrinsically alive, we know that all users of the
230   // function are call sites.  Mark all of the arguments live which are
231   // directly used, and keep track of all of the call sites of this function
232   // if there are any arguments we assume that are dead.
233   //
234   bool AnyMaybeLiveArgs = false;
235   for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
236     switch (getArgumentLiveness(*AI)) {
237     case Live:
238       DEBUG(std::cerr << "    Arg live by use: " << AI->getName() << "\n");
239       LiveArguments.insert(AI);
240       break;
241     case Dead:
242       DEBUG(std::cerr << "    Arg definitely dead: " <<AI->getName()<<"\n");
243       DeadArguments.insert(AI);
244       break;
245     case MaybeLive:
246       DEBUG(std::cerr << "    Arg only passed to calls: "
247             << AI->getName() << "\n");
248       AnyMaybeLiveArgs = true;
249       MaybeLiveArguments.insert(AI);
250       break;
251     }
252
253   // If there are any "MaybeLive" arguments, we need to check callees of
254   // this function when/if they become alive.  Record which functions are
255   // callees...
256   if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
257     for (Value::use_iterator I = F.use_begin(), E = F.use_end();
258          I != E; ++I) {
259       if (AnyMaybeLiveArgs)
260         CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
261
262       if (RetValLiveness == MaybeLive)
263         for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
264              UI != E; ++UI)
265           InstructionsToInspect.push_back(cast<Instruction>(*UI));
266     }
267 }
268
269 // isMaybeLiveArgumentNowLive - Check to see if Arg is alive.  At this point, we
270 // know that the only uses of Arg are to be passed in as an argument to a
271 // function call or return.  Check to see if the formal argument passed in is in
272 // the LiveArguments set.  If so, return true.
273 //
274 bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
275   for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
276     if (isa<ReturnInst>(*I)) {
277       if (LiveRetVal.count(Arg->getParent())) return true;
278       continue;
279     }
280
281     CallSite CS = CallSite::get(*I);
282
283     // We know that this can only be used for direct calls...
284     Function *Callee = CS.getCalledFunction();
285
286     // Loop over all of the arguments (because Arg may be passed into the call
287     // multiple times) and check to see if any are now alive...
288     CallSite::arg_iterator CSAI = CS.arg_begin();
289     for (Function::aiterator AI = Callee->abegin(), E = Callee->aend();
290          AI != E; ++AI, ++CSAI)
291       // If this is the argument we are looking for, check to see if it's alive
292       if (*CSAI == Arg && LiveArguments.count(AI))
293         return true;
294   }
295   return false;
296 }
297
298 /// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
299 /// Mark it live in the specified sets and recursively mark arguments in callers
300 /// live that are needed to pass in a value.
301 ///
302 void DAE::MarkArgumentLive(Argument *Arg) {
303   std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
304   if (It == MaybeLiveArguments.end() || *It != Arg) return;
305  
306   DEBUG(std::cerr << "  MaybeLive argument now live: " << Arg->getName()<<"\n");
307   MaybeLiveArguments.erase(It);
308   LiveArguments.insert(Arg);
309   
310   // Loop over all of the call sites of the function, making any arguments
311   // passed in to provide a value for this argument live as necessary.
312   //
313   Function *Fn = Arg->getParent();
314   unsigned ArgNo = std::distance(Fn->abegin(), Function::aiterator(Arg));
315
316   std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
317   for (; I != CallSites.end() && I->first == Fn; ++I) {
318     CallSite CS = I->second;
319     Value *ArgVal = *(CS.arg_begin()+ArgNo);
320     if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
321       MarkArgumentLive(ActualArg);
322     } else {
323       // If the value passed in at this call site is a return value computed by
324       // some other call site, make sure to mark the return value at the other
325       // call site as being needed.
326       CallSite ArgCS = CallSite::get(ArgVal);
327       if (ArgCS.getInstruction())
328         if (Function *Fn = ArgCS.getCalledFunction())
329           MarkRetValLive(Fn);
330     }
331   }
332 }
333
334 /// MarkArgumentLive - The MaybeLive return value for the specified function is
335 /// now known to be alive.  Propagate this fact to the return instructions which
336 /// produce it.
337 void DAE::MarkRetValLive(Function *F) {
338   assert(F && "Shame shame, we can't have null pointers here!");
339
340   // Check to see if we already knew it was live
341   std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
342   if (I == MaybeLiveRetVal.end() || *I != F) return;  // It's already alive!
343
344   DEBUG(std::cerr << "  MaybeLive retval now live: " << F->getName() << "\n");
345
346   MaybeLiveRetVal.erase(I);
347   LiveRetVal.insert(F);        // It is now known to be live!
348
349   // Loop over all of the functions, noticing that the return value is now live.
350   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
351     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
352       MarkReturnInstArgumentLive(RI);
353 }
354
355 void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
356   Value *Op = RI->getOperand(0);
357   if (Argument *A = dyn_cast<Argument>(Op)) {
358     MarkArgumentLive(A);
359   } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
360     if (Function *F = CI->getCalledFunction())
361       MarkRetValLive(F);
362   } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
363     if (Function *F = II->getCalledFunction())
364       MarkRetValLive(F);
365   }
366 }
367
368 // RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
369 // specified by the DeadArguments list.  Transform the function and all of the
370 // callees of the function to not have these arguments.
371 //
372 void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
373   // Start by computing a new prototype for the function, which is the same as
374   // the old function, but has fewer arguments.
375   const FunctionType *FTy = F->getFunctionType();
376   std::vector<const Type*> Params;
377
378   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
379     if (!DeadArguments.count(I))
380       Params.push_back(I->getType());
381
382   const Type *RetTy = FTy->getReturnType();
383   if (DeadRetVal.count(F)) {
384     RetTy = Type::VoidTy;
385     DeadRetVal.erase(F);
386   }
387
388   // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
389   // have zero fixed arguments.
390   //
391   // FIXME: once this bug is fixed in the CWriter, this hack should be removed.
392   //
393   bool ExtraArgHack = false;
394   if (Params.empty() && FTy->isVarArg()) {
395     ExtraArgHack = true;
396     Params.push_back(Type::IntTy);
397   }
398
399   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
400
401   // Create the new function body and insert it into the module...
402   Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
403   F->getParent()->getFunctionList().insert(F, NF);
404
405   // Loop over all of the callers of the function, transforming the call sites
406   // to pass in a smaller number of arguments into the new function.
407   //
408   std::vector<Value*> Args;
409   while (!F->use_empty()) {
410     CallSite CS = CallSite::get(F->use_back());
411     Instruction *Call = CS.getInstruction();
412
413     // Loop over the operands, deleting dead ones...
414     CallSite::arg_iterator AI = CS.arg_begin();
415     for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)
416       if (!DeadArguments.count(I))      // Remove operands for dead arguments
417         Args.push_back(*AI);
418
419     if (ExtraArgHack)
420       Args.push_back(Constant::getNullValue(Type::IntTy));
421
422     // Push any varargs arguments on the list
423     for (; AI != CS.arg_end(); ++AI)
424       Args.push_back(*AI);
425
426     Instruction *New;
427     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
428       New = new InvokeInst(NF, II->getNormalDest(), II->getExceptionalDest(),
429                            Args, "", Call);
430     } else {
431       New = new CallInst(NF, Args, "", Call);
432     }
433     Args.clear();
434
435     if (!Call->use_empty()) {
436       if (New->getType() == Type::VoidTy)
437         Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
438       else {
439         Call->replaceAllUsesWith(New);
440         std::string Name = Call->getName();
441         Call->setName("");
442         New->setName(Name);
443       }
444     }
445     
446     // Finally, remove the old call from the program, reducing the use-count of
447     // F.
448     Call->getParent()->getInstList().erase(Call);
449   }
450
451   // Since we have now created the new function, splice the body of the old
452   // function right into the new function, leaving the old rotting hulk of the
453   // function empty.
454   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
455
456   // Loop over the argument list, transfering uses of the old arguments over to
457   // the new arguments, also transfering over the names as well.  While we're at
458   // it, remove the dead arguments from the DeadArguments list.
459   //
460   for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
461        I != E; ++I)
462     if (!DeadArguments.count(I)) {
463       // If this is a live argument, move the name and users over to the new
464       // version.
465       I->replaceAllUsesWith(I2);
466       I2->setName(I->getName());
467       ++I2;
468     } else {
469       // If this argument is dead, replace any uses of it with null constants
470       // (these are guaranteed to only be operands to call instructions which
471       // will later be simplified).
472       I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
473       DeadArguments.erase(I);
474     }
475
476   // If we change the return value of the function we must rewrite any return
477   // instructions.  Check this now.
478   if (F->getReturnType() != NF->getReturnType())
479     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
480       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
481         new ReturnInst(0, RI);
482         BB->getInstList().erase(RI);
483       }
484
485   // Now that the old function is dead, delete it.
486   F->getParent()->getFunctionList().erase(F);
487 }
488
489 bool DAE::run(Module &M) {
490   // First phase: loop through the module, determining which arguments are live.
491   // We assume all arguments are dead unless proven otherwise (allowing us to
492   // determine that dead arguments passed into recursive functions are dead).
493   //
494   DEBUG(std::cerr << "DAE - Determining liveness\n");
495   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
496     SurveyFunction(*I);
497
498   // Loop over the instructions to inspect, propagating liveness among arguments
499   // and return values which are MaybeLive.
500
501   while (!InstructionsToInspect.empty()) {
502     Instruction *I = InstructionsToInspect.back();
503     InstructionsToInspect.pop_back();
504     
505     if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
506       // For return instructions, we just have to check to see if the return
507       // value for the current function is known now to be alive.  If so, any
508       // arguments used by it are now alive, and any call instruction return
509       // value is alive as well.
510       if (LiveRetVal.count(RI->getParent()->getParent()))
511         MarkReturnInstArgumentLive(RI);
512
513     } else {
514       CallSite CS = CallSite::get(I);
515       assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
516
517       Function *Callee = CS.getCalledFunction();
518       
519       // If we found a call or invoke instruction on this list, that means that
520       // an argument of the function is a call instruction.  If the argument is
521       // live, then the return value of the called instruction is now live.
522       //
523       CallSite::arg_iterator AI = CS.arg_begin();  // ActualIterator
524       for (Function::aiterator FI = Callee->abegin(), E = Callee->aend();
525            FI != E; ++AI, ++FI) {
526         // If this argument is another call...
527         CallSite ArgCS = CallSite::get(*AI);
528         if (ArgCS.getInstruction() && LiveArguments.count(FI))
529           if (Function *Callee = ArgCS.getCalledFunction())
530             MarkRetValLive(Callee);
531       }
532     }
533   }
534
535   // Now we loop over all of the MaybeLive arguments, promoting them to be live
536   // arguments if one of the calls that uses the arguments to the calls they are
537   // passed into requires them to be live.  Of course this could make other
538   // arguments live, so process callers recursively.
539   //
540   // Because elements can be removed from the MaybeLiveArguments set, copy it to
541   // a temporary vector.
542   //
543   std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
544                                     MaybeLiveArguments.end());
545   for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
546     Argument *MLA = TmpArgList[i];
547     if (MaybeLiveArguments.count(MLA) &&
548         isMaybeLiveArgumentNowLive(MLA))
549       MarkArgumentLive(MLA);
550   }
551
552   // Recover memory early...
553   CallSites.clear();
554
555   // At this point, we know that all arguments in DeadArguments and
556   // MaybeLiveArguments are dead.  If the two sets are empty, there is nothing
557   // to do.
558   if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
559       MaybeLiveRetVal.empty() && DeadRetVal.empty())
560     return false;
561   
562   // Otherwise, compact into one set, and start eliminating the arguments from
563   // the functions.
564   DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
565   MaybeLiveArguments.clear();
566   DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
567   MaybeLiveRetVal.clear();
568
569   LiveArguments.clear();
570   LiveRetVal.clear();
571
572   NumArgumentsEliminated += DeadArguments.size();
573   NumRetValsEliminated   += DeadRetVal.size();
574   while (!DeadArguments.empty())
575     RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
576
577   while (!DeadRetVal.empty())
578     RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());
579   return true;
580 }
581
582 } // End llvm namespace
583