Don't use isa when we can reuse a previous dyn_cast.
[oota-llvm.git] / lib / Transforms / IPO / DeadArgumentElimination.cpp
1 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 return values 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 or return values.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "deadargelim"
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constant.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Module.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Support/Compiler.h"
35 #include <map>
36 #include <set>
37 using namespace llvm;
38
39 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
40 STATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
41
42 namespace {
43   /// DAE - The dead argument elimination pass.
44   ///
45   class VISIBILITY_HIDDEN DAE : public ModulePass {
46   public:
47
48     /// Struct that represents (part of) either a return value or a function
49     /// argument.  Used so that arguments and return values can be used
50     /// interchangably. Idx == -1 means the entire return value, while other
51     /// indices mean the corresponding element in the struct return type (if
52     /// any).
53     struct RetOrArg {
54       RetOrArg(const Function* F, signed Idx, bool IsArg) : F(F), Idx(Idx),
55                IsArg(IsArg) {}
56       const Function *F;
57       signed Idx;
58       bool IsArg;
59
60       /// Make RetOrArg comparable, so we can put it into a map.
61       bool operator<(const RetOrArg &O) const {
62         if (F != O.F)
63           return F < O.F;
64         else if (Idx != O.Idx)
65           return Idx < O.Idx;
66         else
67           return IsArg < O.IsArg;
68       }
69
70       /// Make RetOrArg comparable, so we can easily iterate the multimap.
71       bool operator==(const RetOrArg &O) const {
72         return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
73       }
74
75       std::string getDescription() const {
76         return std::string((!IsArg && Idx != -1 ? "partial " : "")) 
77                + (IsArg ? "argument #" : "return value") 
78                + (!IsArg && Idx == -1 ? "" : " #" + utostr(Idx)) 
79                + " of function " + F->getName();
80       }
81     };
82
83     /// Liveness enum - During our initial pass over the program, we determine
84     /// that things are either alive or maybe alive. We don't mark anything
85     /// explicitly dead (even if we know they are), since anything not alive
86     /// with no registered uses (in Uses) will never be marked alive and will
87     /// thus become dead in the end.
88     enum Liveness { Live, MaybeLive };
89
90     /// Convenience wrapper
91     RetOrArg CreateRet(const Function *F, signed Idx) {
92       return RetOrArg(F, Idx, false);
93     }
94     /// Convenience wrapper
95     RetOrArg CreateArg(const Function *F, signed Idx) {
96       return RetOrArg(F, Idx, true);
97     }
98
99     typedef std::multimap<RetOrArg, RetOrArg> UseMap;
100     /// This maps a return value or argument to any MaybeLive return values or
101     /// arguments it uses. This allows the MaybeLive values to be marked live
102     /// when any of its users is marked live.
103     /// For example (indices are left out for clarity):
104     ///  - Uses[ret F] = ret G
105     ///    This means that F calls G, and F returns the value returned by G.
106     ///  - Uses[arg F] = ret G
107     ///    This means that some function calls G and passes its result as an
108     ///    argument to F.
109     ///  - Uses[ret F] = arg F
110     ///    This means that F returns one of its own arguments.
111     ///  - Uses[arg F] = arg G
112     ///    This means that G calls F and passes one of its own (G's) arguments
113     ///    directly to F.
114     UseMap Uses;
115
116     typedef std::set<RetOrArg> LiveSet;
117     typedef std::set<const Function*> LiveFuncSet;
118
119     /// This set contains all values that have been determined to be live.
120     LiveSet LiveValues;
121     /// This set contains all values that are cannot be changed in any way.
122     LiveFuncSet LiveFunctions;
123
124     typedef SmallVector<RetOrArg, 5> UseVector;
125
126   public:
127     static char ID; // Pass identification, replacement for typeid
128     DAE() : ModulePass((intptr_t)&ID) {}
129     bool runOnModule(Module &M);
130
131     virtual bool ShouldHackArguments() const { return false; }
132
133   private:
134     Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
135     Liveness SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
136                        signed RetValNum = -1);
137     Liveness SurveyUses(Value *V, UseVector &MaybeLiveUses);
138
139     void SurveyFunction(Function &F);
140     void MarkValue(const RetOrArg &RA, Liveness L,
141                    const UseVector &MaybeLiveUses);
142     void MarkLive(const RetOrArg &RA);
143     void MarkLive(const Function &F);
144     void PropagateLiveness(const RetOrArg &RA);
145     bool RemoveDeadStuffFromFunction(Function *F);
146     bool DeleteDeadVarargs(Function &Fn);
147   };
148 }
149
150
151 char DAE::ID = 0;
152 static RegisterPass<DAE>
153 X("deadargelim", "Dead Argument Elimination");
154
155 namespace {
156   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
157   /// deletes arguments to functions which are external.  This is only for use
158   /// by bugpoint.
159   struct DAH : public DAE {
160     static char ID;
161     virtual bool ShouldHackArguments() const { return true; }
162   };
163 }
164
165 char DAH::ID = 0;
166 static RegisterPass<DAH>
167 Y("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
168
169 /// createDeadArgEliminationPass - This pass removes arguments from functions
170 /// which are not used by the body of the function.
171 ///
172 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
173 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
174
175 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
176 /// llvm.vastart is never called, the varargs list is dead for the function.
177 bool DAE::DeleteDeadVarargs(Function &Fn) {
178   assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
179   if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
180
181   // Ensure that the function is only directly called.
182   for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
183     // If this use is anything other than a call site, give up.
184     CallSite CS = CallSite::get(*I);
185     Instruction *TheCall = CS.getInstruction();
186     if (!TheCall) return false;   // Not a direct call site?
187
188     // The addr of this function is passed to the call.
189     if (I.getOperandNo() != 0) return false;
190   }
191
192   // Okay, we know we can transform this function if safe.  Scan its body
193   // looking for calls to llvm.vastart.
194   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
195     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
196       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
197         if (II->getIntrinsicID() == Intrinsic::vastart)
198           return false;
199       }
200     }
201   }
202
203   // If we get here, there are no calls to llvm.vastart in the function body,
204   // remove the "..." and adjust all the calls.
205
206   // Start by computing a new prototype for the function, which is the same as
207   // the old function, but doesn't have isVarArg set.
208   const FunctionType *FTy = Fn.getFunctionType();
209   std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
210   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
211   unsigned NumArgs = Params.size();
212
213   // Create the new function body and insert it into the module...
214   Function *NF = Function::Create(NFTy, Fn.getLinkage());
215   NF->copyAttributesFrom(&Fn);
216   Fn.getParent()->getFunctionList().insert(&Fn, NF);
217   NF->takeName(&Fn);
218
219   // Loop over all of the callers of the function, transforming the call sites
220   // to pass in a smaller number of arguments into the new function.
221   //
222   std::vector<Value*> Args;
223   while (!Fn.use_empty()) {
224     CallSite CS = CallSite::get(Fn.use_back());
225     Instruction *Call = CS.getInstruction();
226
227     // Pass all the same arguments.
228     Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
229
230     // Drop any attributes that were on the vararg arguments.
231     PAListPtr PAL = CS.getParamAttrs();
232     if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
233       SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
234       for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
235         ParamAttrsVec.push_back(PAL.getSlot(i));
236       PAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
237     }
238
239     Instruction *New;
240     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
241       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
242                                Args.begin(), Args.end(), "", Call);
243       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
244       cast<InvokeInst>(New)->setParamAttrs(PAL);
245     } else {
246       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
247       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
248       cast<CallInst>(New)->setParamAttrs(PAL);
249       if (cast<CallInst>(Call)->isTailCall())
250         cast<CallInst>(New)->setTailCall();
251     }
252     Args.clear();
253
254     if (!Call->use_empty())
255       Call->replaceAllUsesWith(New);
256
257     New->takeName(Call);
258
259     // Finally, remove the old call from the program, reducing the use-count of
260     // F.
261     Call->eraseFromParent();
262   }
263
264   // Since we have now created the new function, splice the body of the old
265   // function right into the new function, leaving the old rotting hulk of the
266   // function empty.
267   NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
268
269   // Loop over the argument list, transfering uses of the old arguments over to
270   // the new arguments, also transfering over the names as well.  While we're at
271   // it, remove the dead arguments from the DeadArguments list.
272   //
273   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
274        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
275     // Move the name and users over to the new version.
276     I->replaceAllUsesWith(I2);
277     I2->takeName(I);
278   }
279
280   // Finally, nuke the old function.
281   Fn.eraseFromParent();
282   return true;
283 }
284
285 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
286 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
287 /// liveness of Use.
288 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
289   // We're live if our use or its Function is already marked as live.
290   if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
291     return Live;
292
293   // We're maybe live otherwise, but remember that we must become live if
294   // Use becomes live.
295   MaybeLiveUses.push_back(Use);
296   return MaybeLive;
297 }
298
299 /// SurveyUse - This looks at a single use of an argument or return value
300 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
301 /// if it causes the used value to become MaybeAlive.
302 ///
303 /// RetValNum is the return value number to use when this use is used in a
304 /// return instruction. This is used in the recursion, you should always leave
305 /// it at -1.
306 DAE::Liveness DAE::SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
307                              signed RetValNum) {
308     Value *V = *U;
309     if (ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
310       // The value is returned from a function. It's only live when the
311       // function's return value is live. We use RetValNum here, for the case
312       // that U is really a use of an insertvalue instruction that uses the
313       // orginal Use.
314       RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
315       // We might be live, depending on the liveness of Use.
316       return MarkIfNotLive(Use, MaybeLiveUses);
317     }
318     if (InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
319       if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
320           && IV->hasIndices())
321         // The use we are examining is inserted into an aggregate. Our liveness
322         // depends on all uses of that aggregate, but if it is used as a return
323         // value, only index at which we were inserted counts.
324         RetValNum = *IV->idx_begin();
325
326       // Note that if we are used as the aggregate operand to the insertvalue,
327       // we don't change RetValNum, but do survey all our uses.
328
329       Liveness Result = MaybeLive;
330       for (Value::use_iterator I = IV->use_begin(),
331            E = V->use_end(); I != E; ++I) {
332         Result = SurveyUse(I, MaybeLiveUses, RetValNum);
333         if (Result == Live)
334           break;
335       }
336       return Result;
337     }
338     CallSite CS = CallSite::get(V);
339     if (CS.getInstruction()) {
340       Function *F = CS.getCalledFunction();
341       if (F) {
342         // Used in a direct call.
343   
344         // Find the argument number. We know for sure that this use is an
345         // argument, since if it was the function argument this would be an
346         // indirect call and the we know can't be looking at a value of the
347         // label type (for the invoke instruction).
348         unsigned ArgNo = CS.getArgumentNo(U.getOperandNo());
349
350         if (ArgNo >= F->getFunctionType()->getNumParams())
351           // The value is passed in through a vararg! Must be live.
352           return Live;
353
354         assert(CS.getArgument(ArgNo) 
355                == CS.getInstruction()->getOperand(U.getOperandNo()) 
356                && "Argument is not where we expected it");
357
358         // Value passed to a normal call. It's only live when the corresponding
359         // argument to the called function turns out live.
360         RetOrArg Use = CreateArg(F, ArgNo);
361         return MarkIfNotLive(Use, MaybeLiveUses);
362       }
363     }
364     // Used in any other way? Value must be live.
365     return Live;
366 }
367
368 /// SurveyUses - This looks at all the uses of the given value
369 /// Returns the Liveness deduced from the uses of this value.
370 ///
371 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
372 /// the result is Live, MaybeLiveUses might be modified but its content should
373 /// be ignored (since it might not be complete).
374 DAE::Liveness DAE::SurveyUses(Value *V, UseVector &MaybeLiveUses) {
375   // Assume it's dead (which will only hold if there are no uses at all..).
376   Liveness Result = MaybeLive;
377   // Check each use.
378   for (Value::use_iterator I = V->use_begin(),
379        E = V->use_end(); I != E; ++I) {
380     Result = SurveyUse(I, MaybeLiveUses);
381     if (Result == Live)
382       break;
383   }
384   return Result;
385 }
386
387 // SurveyFunction - This performs the initial survey of the specified function,
388 // checking out whether or not it uses any of its incoming arguments or whether
389 // any callers use the return value.  This fills in the LiveValues set and Uses
390 // map.
391 //
392 // We consider arguments of non-internal functions to be intrinsically alive as
393 // well as arguments to functions which have their "address taken".
394 //
395 void DAE::SurveyFunction(Function &F) {
396   const StructType *STy = dyn_cast<StructType>(F.getFunctionType()->getReturnType());
397   // Store the number of partial return values, which we only have if the return
398   // type is a struct.
399   unsigned PartialRetVals = (STy ? STy->getNumElements() : 0);
400   // Assume all return values are dead
401   typedef SmallVector<Liveness, 5> RetVals;
402   // Allocate one slot for the entire return value (index 0) and one for each
403   // partial return value.
404   RetVals RetValLiveness(PartialRetVals + 1, MaybeLive);
405
406   typedef SmallVector<UseVector, 5> RetUses;
407   // These vectors map each return value to the uses that make it MaybeLive, so
408   // we can add those to the Uses map if the return value really turns out to be
409   // MaybeLive. 
410   // Allocate one slot for the entire return value (index 0) and one for each
411   // partial return value.
412   RetUses MaybeLiveRetUses(PartialRetVals + 1);
413
414   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
415     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
416       if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
417           != F.getFunctionType()->getReturnType()) {
418         // We don't support old style multiple return values.
419         MarkLive(F);
420         return;
421       }
422
423   if (!F.hasInternalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
424     MarkLive(F);
425     return;
426   }
427
428   DOUT << "DAE - Inspecting callers for fn: " << F.getName() << "\n";
429   // Loop all uses of the function.
430   for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
431     // If the function is PASSED IN as an argument, its address has been
432     // taken.
433     if (I.getOperandNo() != 0) {
434       MarkLive(F);
435       return;
436     }
437
438     // If this use is anything other than a call site, the function is alive.
439     CallSite CS = CallSite::get(*I);
440     Instruction *TheCall = CS.getInstruction();
441     if (!TheCall) {   // Not a direct call site?
442       MarkLive(F);
443       return;
444     }
445
446     // If we end up here, we are looking at a direct call to our function.
447
448     // Now, check how our return value(s) is/are used in this caller. Don't
449     // bother checking return values if the entire value is live already.
450     if (RetValLiveness[0] != Live) {
451       // Check all uses of the return value.
452       for (Value::use_iterator I = TheCall->use_begin(),
453            E = TheCall->use_end(); I != E; ++I) {
454         ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
455         if (Ext && Ext->hasIndices()) {
456           // This use uses a part of our return value, survey the uses of
457           // that part and store the results for this index only.
458           unsigned Idx = *Ext->idx_begin();
459           // + 1 to skip the "entire retval" index (0)
460           Liveness &IsLive = RetValLiveness[Idx + 1];
461           if (IsLive != Live) {
462             // Don't bother checking if this retval was already live
463             // Survey all uses of the extractvalue
464             // + 1 to skip the "entire retval" index (0)
465             IsLive = SurveyUses(Ext, MaybeLiveRetUses[Idx + 1]);
466           }
467         } else {
468           // Survey this use
469           RetValLiveness[0] = SurveyUse(I, MaybeLiveRetUses[0]);
470           if (RetValLiveness[0] == Live)
471             break;
472         }
473       }
474     }
475   }
476
477   // Now we've inspected all callers, record the liveness of our return values.
478   MarkValue(CreateRet(&F, -1), RetValLiveness[0], MaybeLiveRetUses[0]);
479   if (RetValLiveness[0] != Live)
480     // If the entire retval (0) is Live, MarkValue will have marked all other retvals live
481     // as well, so we can skip this.
482     for (unsigned i = 0; i != PartialRetVals; ++i)
483       // + 1 to skip the "entire retval" index (0)
484       MarkValue(CreateRet(&F, i), RetValLiveness[i + 1], MaybeLiveRetUses[i + 1]);
485
486   DOUT << "DAE - Inspecting args for fn: " << F.getName() << "\n";
487
488   // Now, check all of our arguments.
489   unsigned i = 0;
490   UseVector MaybeLiveArgUses;
491   for (Function::arg_iterator AI = F.arg_begin(),
492        E = F.arg_end(); AI != E; ++AI, ++i) {
493     // See what the effect of this use is (recording any uses that cause
494     // MaybeLive in MaybeLiveArgUses).
495     Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
496     // Mark the result.
497     MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
498     // Clear the vector again for the next iteration.
499     MaybeLiveArgUses.clear();
500   }
501 }
502
503 /// MarkValue - This function marks the liveness of RA depending on L. If L is
504 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
505 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
506 /// live later on.
507 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
508                     const UseVector &MaybeLiveUses) {
509   switch (L) {
510     case Live: MarkLive(RA); break;
511     case MaybeLive:
512     {
513       // Note any uses of this value, so this return value can be
514       // marked live whenever one of the uses becomes live.
515       for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
516            UE = MaybeLiveUses.end(); UI != UE; ++UI)
517         Uses.insert(std::make_pair(*UI, RA));
518       break;
519     }
520   }
521 }
522
523 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
524 /// changed in any way. Additionally,
525 /// mark any values that are used as this function's parameters or by its return
526 /// values (according to Uses) live as well.
527 void DAE::MarkLive(const Function &F) {
528     DOUT << "DAE - Intrinsically live fn: " << F.getName() << "\n";
529     // Mark the function as live.
530     LiveFunctions.insert(&F);
531     // Mark all arguments as live.
532     for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
533       PropagateLiveness(CreateArg(&F, i));
534     // Mark all return values as live.
535     const Type *RTy = F.getFunctionType()->getReturnType();
536     if (const StructType *STy = dyn_cast<StructType>(RTy))
537       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
538         PropagateLiveness(CreateRet(&F, i));
539     PropagateLiveness(CreateRet(&F, -1));
540 }
541
542 /// MarkLive - Mark the given return value or argument as live. Additionally,
543 /// mark any values that are used by this value (according to Uses) live as
544 /// well.
545 void DAE::MarkLive(const RetOrArg &RA) {
546   if (LiveFunctions.count(RA.F))
547     return; // Function was already marked Live.
548
549   if (!LiveValues.insert(RA).second)
550     return; // We were already marked Live.
551
552   DOUT << "DAE - Marking " << RA.getDescription() << " live\n";
553   PropagateLiveness(RA);
554
555   if (!RA.IsArg && RA.Idx == -1) {
556     // Entire return value live? 
557     const Type *RTy = RA.F->getFunctionType()->getReturnType();
558     if (const StructType *STy = dyn_cast<StructType>(RTy))
559       // And the function returns a struct?
560       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
561         // Mark all partial return values live as well then
562         MarkLive(CreateRet(RA.F, i));
563   }
564 }
565
566 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
567 /// to any other values it uses (according to Uses).
568 void DAE::PropagateLiveness(const RetOrArg &RA) {
569   // We don't use upper_bound (or equal_range) here, because our recursive call
570   // to ourselves is likely to cause the upper_bound (which is the first value
571   // not belonging to RA) to become erased and the iterator invalidated.
572   UseMap::iterator Begin = Uses.lower_bound(RA);
573   UseMap::iterator E = Uses.end();
574   UseMap::iterator I;
575   for (I = Begin; I != E && I->first == RA; ++I)
576     MarkLive(I->second);
577
578   // Erase RA from the Uses map (from the lower bound to wherever we ended up
579   // after the loop).
580   Uses.erase(Begin, I);
581 }
582
583 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
584 // that are not in LiveValues. Transform the function and all of the callees of
585 // the function to not have these arguments and return values.
586 //
587 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
588   // Don't modify fully live functions
589   if (LiveFunctions.count(F))
590     return false;
591
592   // Start by computing a new prototype for the function, which is the same as
593   // the old function, but has fewer arguments and a different return type.
594   const FunctionType *FTy = F->getFunctionType();
595   std::vector<const Type*> Params;
596
597   // Set up to build a new list of parameter attributes.
598   SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
599   const PAListPtr &PAL = F->getParamAttrs();
600
601   // The existing function return attributes.
602   ParameterAttributes RAttrs = PAL.getParamAttrs(0);
603
604
605   // Find out the new return value.
606
607   const Type *RetTy = FTy->getReturnType();
608   const StructType *STy = dyn_cast<StructType>(RetTy);
609   const unsigned PartialRetVals = (STy ? STy->getNumElements() : 0);
610   const Type *NRetTy = NULL;
611   // -1 means unused, other numbers are the new index. Initialized to -1 for
612   // every partial return value we have.
613   SmallVector<int, 5> NewRetIdxs(PartialRetVals, -1);
614   std::vector<const Type*> RetTypes;
615   if (LiveValues.count(CreateRet(F, -1))) {
616     // If the entire return value is live, leave it unchanged.
617     NRetTy = RetTy;
618   } else {
619     if (STy) {
620       // Look at each of the partial return values individually.
621       for (unsigned i = 0; i != PartialRetVals; ++i) {
622         RetOrArg Ret = CreateRet(F, i);
623         if (LiveValues.erase(Ret)) {
624           RetTypes.push_back(STy->getElementType(i));
625           NewRetIdxs[i] = RetTypes.size() - 1;
626         } else {
627           ++NumRetValsEliminated;
628           DOUT << "DAE - Removing return value " << i << " from "
629                << F->getNameStart() << "\n";
630           // We remove the value by not adding anything to RetTypes.
631         }
632       }
633     } else if (RetTy != Type::VoidTy) {
634       // We used to return a single value, which is now dead (already checked in
635       // the if above)
636       DOUT << "DAE - Removing return value from " << F->getNameStart()
637            << "\n";
638       ++NumRetValsEliminated;
639       // We remove the value by not adding anything to RetTypes.
640     }
641
642     if (RetTypes.size() > 1)
643       // More than one return type? Return a struct with them. 
644       // Make the new struct packed if we used to return a packed struct
645       // already.
646       NRetTy = StructType::get(RetTypes, STy->isPacked());
647     else if (RetTypes.size() == 1)
648       // One return type? Just a simple value then, but only if we didn't use to
649       // return a struct with that simple value before.
650       NRetTy = RetTypes.front();
651     else if (RetTypes.size() == 0)
652       // No return types? Make it void.
653       NRetTy = Type::VoidTy;
654   }
655
656   assert(NRetTy && "No new return type found?");
657
658   // Remove any incompatible attributes, but only if we removed all return
659   // values. Otherwise, ensure that we don't have any conflicting attributes
660   // here. Currently, this should not be possible, but special handling might be
661   // required when new return value attributes are added.
662   if (NRetTy == Type::VoidTy)
663     RAttrs &= ~ParamAttr::typeIncompatible(NRetTy);
664   else
665     assert((RAttrs & ParamAttr::typeIncompatible(NRetTy)) == 0 
666            && "Return attributes no longer compatible?");
667
668   if (RAttrs)
669     ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
670
671   // Remember which arguments are still alive.
672   SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
673   // Construct the new parameter list from non-dead arguments. Also construct
674   // a new set of parameter attributes to correspond. Skip the first parameter
675   // attribute, since that belongs to the return value.
676   unsigned i = 0;
677   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
678        I != E; ++I, ++i) {
679     RetOrArg Arg = CreateArg(F, i);
680     if (LiveValues.erase(Arg)) {
681       Params.push_back(I->getType());
682       ArgAlive[i] = true;
683
684       // Get the original parameter attributes (skipping the first one, that is
685       // for the return value.
686       if (ParameterAttributes Attrs = PAL.getParamAttrs(i + 1))
687         ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), Attrs));
688     } else {
689       ++NumArgumentsEliminated;
690       DOUT << "DAE - Removing argument " << i << " (" << I->getNameStart()
691            << ") from " << F->getNameStart() << "\n";
692     }
693   }
694
695   // Reconstruct the ParamAttrsList based on the vector we constructed.
696   PAListPtr NewPAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
697
698   // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
699   // have zero fixed arguments.
700   //
701   // Note that we apply this hack for a vararg fuction that does not have any
702   // arguments anymore, but did have them before (so don't bother fixing
703   // functions that were already broken wrt CWriter).
704   bool ExtraArgHack = false;
705   if (Params.empty() && FTy->isVarArg() && FTy->getNumParams() != 0) {
706     ExtraArgHack = true;
707     Params.push_back(Type::Int32Ty);
708   }
709
710   // Create the new function type based on the recomputed parameters.
711   FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
712
713   // No change?
714   if (NFTy == FTy)
715     return false;
716
717   // Create the new function body and insert it into the module...
718   Function *NF = Function::Create(NFTy, F->getLinkage());
719   NF->copyAttributesFrom(F);
720   NF->setParamAttrs(NewPAL);
721   // Insert the new function before the old function, so we won't be processing
722   // it again.
723   F->getParent()->getFunctionList().insert(F, NF);
724   NF->takeName(F);
725
726   // Loop over all of the callers of the function, transforming the call sites
727   // to pass in a smaller number of arguments into the new function.
728   //
729   std::vector<Value*> Args;
730   while (!F->use_empty()) {
731     CallSite CS = CallSite::get(F->use_back());
732     Instruction *Call = CS.getInstruction();
733
734     ParamAttrsVec.clear();
735     const PAListPtr &CallPAL = CS.getParamAttrs();
736
737     // The call return attributes.
738     ParameterAttributes RAttrs = CallPAL.getParamAttrs(0);
739     // Adjust in case the function was changed to return void.
740     RAttrs &= ~ParamAttr::typeIncompatible(NF->getReturnType());
741     if (RAttrs)
742       ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
743
744     // Declare these outside of the loops, so we can reuse them for the second
745     // loop, which loops the varargs.
746     CallSite::arg_iterator I = CS.arg_begin();
747     unsigned i = 0;
748     // Loop over those operands, corresponding to the normal arguments to the
749     // original function, and add those that are still alive.
750     for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
751       if (ArgAlive[i]) {
752         Args.push_back(*I);
753         // Get original parameter attributes, but skip return attributes.
754         if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
755           ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
756       }
757
758     if (ExtraArgHack)
759       Args.push_back(UndefValue::get(Type::Int32Ty));
760
761     // Push any varargs arguments on the list. Don't forget their attributes.
762     for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
763       Args.push_back(*I);
764       if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
765         ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
766     }
767
768     // Reconstruct the ParamAttrsList based on the vector we constructed.
769     PAListPtr NewCallPAL = PAListPtr::get(ParamAttrsVec.begin(),
770                                           ParamAttrsVec.end());
771
772     Instruction *New;
773     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
774       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
775                                Args.begin(), Args.end(), "", Call);
776       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
777       cast<InvokeInst>(New)->setParamAttrs(NewCallPAL);
778     } else {
779       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
780       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
781       cast<CallInst>(New)->setParamAttrs(NewCallPAL);
782       if (cast<CallInst>(Call)->isTailCall())
783         cast<CallInst>(New)->setTailCall();
784     }
785     Args.clear();
786
787     if (!Call->use_empty()) {
788       if (New->getType() == Call->getType()) {
789         // Return type not changed? Just replace users then.
790         Call->replaceAllUsesWith(New);
791         New->takeName(Call);
792       } else if (New->getType() == Type::VoidTy) {
793         // Our return value has uses, but they will get removed later on.
794         // Replace by null for now.
795         Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
796       } else {
797         assert(STy && "Return type changed, but not into a void. The old "
798                       "return type must have been a struct!");
799         // The original return value was a struct, update all uses (which are
800         // all extractvalue instructions, or uses that are unused themselves).
801         for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
802              I != E;) {
803           if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(*I)) {
804             // Increment now, since we're about to throw away this use.
805             ++I;
806             assert(EV->hasIndices() && "Return value used by extractvalue without"
807                                        "indices?");
808             unsigned Idx = *EV->idx_begin();
809             if (NewRetIdxs[Idx] != -1) {
810               if (RetTypes.size() > 1) {
811                 // We're still returning a struct, create a new extractvalue
812                 // instruction with the first index updated
813                 std::vector<unsigned> NewIdxs(EV->idx_begin(), EV->idx_end());
814                 NewIdxs[0] = NewRetIdxs[Idx];
815                 Value *NEV = ExtractValueInst::Create(New, NewIdxs.begin(),
816                                                       NewIdxs.end(), "retval",
817                                                       EV);
818                 EV->replaceAllUsesWith(NEV);
819                 EV->eraseFromParent();
820               } else {
821                 // We are now only returning a simple value, remove the
822                 // extractvalue.
823                 EV->replaceAllUsesWith(New);
824                 EV->eraseFromParent();
825               }
826             } else {
827               // Value unused, replace uses by null for now, they will get removed
828               // later on.
829               EV->replaceAllUsesWith(Constant::getNullValue(EV->getType()));
830               EV->eraseFromParent();
831             }
832           } else {
833             // Not an extractvalue, so this use will become dead soon. Just
834             // replace it with null.
835             I.getUse().set(Constant::getNullValue(I.getUse().get()->getType()));
836           }
837         }
838         New->takeName(Call);
839       }
840     }
841
842     // Finally, remove the old call from the program, reducing the use-count of
843     // F.
844     Call->eraseFromParent();
845   }
846
847   // Since we have now created the new function, splice the body of the old
848   // function right into the new function, leaving the old rotting hulk of the
849   // function empty.
850   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
851
852   // Loop over the argument list, transfering uses of the old arguments over to
853   // the new arguments, also transfering over the names as well.
854   i = 0;
855   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
856        I2 = NF->arg_begin(); I != E; ++I, ++i)
857     if (ArgAlive[i]) {
858       // If this is a live argument, move the name and users over to the new
859       // version.
860       I->replaceAllUsesWith(I2);
861       I2->takeName(I);
862       ++I2;
863     } else {
864       // If this argument is dead, replace any uses of it with null constants
865       // (these are guaranteed to become unused later on).
866       I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
867     }
868
869   // If we change the return value of the function we must rewrite any return
870   // instructions.  Check this now.
871   if (F->getReturnType() != NF->getReturnType())
872     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
873       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
874         Value *RetVal;
875
876         if (NFTy->getReturnType() == Type::VoidTy) {
877           RetVal = 0;
878         } else {
879           assert (isa<StructType>(RetTy));
880           // The original return value was a struct, insert
881           // extractvalue/insertvalue chains to extract only the values we need
882           // to return and insert them into our new result.
883           // This does generate messy code, but we'll let it to instcombine to
884           // clean that up.
885           Value *OldRet = RI->getOperand(0);
886           // Start out building up our return value from undef
887           RetVal = llvm::UndefValue::get(NRetTy);
888           for (unsigned i = 0; i != PartialRetVals; ++i)
889             if (NewRetIdxs[i] != -1) {
890               ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
891                                                               "oldret", RI);
892               if (RetTypes.size() > 1) {
893                 // We're still returning a struct, so reinsert the value into
894                 // our new return value at the new index
895
896                 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
897                                                  "newret", RI);
898               } else {
899                 // We are now only returning a simple value, so just return the
900                 // extracted value.
901                 RetVal = EV;
902               }
903             }
904         }
905         // Replace the return instruction with one returning the new return
906         // value (possibly 0 if we became void).
907         ReturnInst::Create(RetVal, RI);
908         BB->getInstList().erase(RI);
909       }
910
911   // Now that the old function is dead, delete it.
912   F->eraseFromParent();
913
914   return true;
915 }
916
917 bool DAE::runOnModule(Module &M) {
918   bool Changed = false;
919
920   // First pass: Do a simple check to see if any functions can have their "..."
921   // removed.  We can do this if they never call va_start.  This loop cannot be
922   // fused with the next loop, because deleting a function invalidates
923   // information computed while surveying other functions.
924   DOUT << "DAE - Deleting dead varargs\n";
925   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
926     Function &F = *I++;
927     if (F.getFunctionType()->isVarArg())
928       Changed |= DeleteDeadVarargs(F);
929   }
930
931   // Second phase:loop through the module, determining which arguments are live.
932   // We assume all arguments are dead unless proven otherwise (allowing us to
933   // determine that dead arguments passed into recursive functions are dead).
934   //
935   DOUT << "DAE - Determining liveness\n";
936   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
937     SurveyFunction(*I);
938   
939   // Now, remove all dead arguments and return values from each function in
940   // turn
941   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
942     // Increment now, because the function will probably get removed (ie
943     // replaced by a new one).
944     Function *F = I++;
945     Changed |= RemoveDeadStuffFromFunction(F);
946   }
947   return Changed;
948 }