DeadArgumentElimination.cpp revision 208599
1193323Sed//===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This pass deletes dead arguments from internal functions.  Dead argument
11193323Sed// elimination removes arguments which are directly dead, as well as arguments
12193323Sed// only passed into function calls as dead arguments of other functions.  This
13193323Sed// pass also deletes dead return values in a similar way.
14193323Sed//
15193323Sed// This pass is often useful as a cleanup pass to run after aggressive
16193323Sed// interprocedural passes, which add possibly-dead arguments or return values.
17193323Sed//
18193323Sed//===----------------------------------------------------------------------===//
19193323Sed
20193323Sed#define DEBUG_TYPE "deadargelim"
21193323Sed#include "llvm/Transforms/IPO.h"
22193323Sed#include "llvm/CallingConv.h"
23193323Sed#include "llvm/Constant.h"
24193323Sed#include "llvm/DerivedTypes.h"
25193323Sed#include "llvm/Instructions.h"
26193323Sed#include "llvm/IntrinsicInst.h"
27198090Srdivacky#include "llvm/LLVMContext.h"
28193323Sed#include "llvm/Module.h"
29193323Sed#include "llvm/Pass.h"
30193323Sed#include "llvm/Support/CallSite.h"
31193323Sed#include "llvm/Support/Debug.h"
32198090Srdivacky#include "llvm/Support/raw_ostream.h"
33193323Sed#include "llvm/ADT/SmallVector.h"
34193323Sed#include "llvm/ADT/Statistic.h"
35193323Sed#include "llvm/ADT/StringExtras.h"
36193323Sed#include <map>
37193323Sed#include <set>
38193323Sedusing namespace llvm;
39193323Sed
40193323SedSTATISTIC(NumArgumentsEliminated, "Number of unread args removed");
41193323SedSTATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
42193323Sed
43193323Sednamespace {
44193323Sed  /// DAE - The dead argument elimination pass.
45193323Sed  ///
46198892Srdivacky  class DAE : public ModulePass {
47193323Sed  public:
48193323Sed
49193323Sed    /// Struct that represents (part of) either a return value or a function
50193323Sed    /// argument.  Used so that arguments and return values can be used
51193323Sed    /// interchangably.
52193323Sed    struct RetOrArg {
53206083Srdivacky      RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
54193323Sed               IsArg(IsArg) {}
55193323Sed      const Function *F;
56193323Sed      unsigned Idx;
57193323Sed      bool IsArg;
58193323Sed
59193323Sed      /// Make RetOrArg comparable, so we can put it into a map.
60193323Sed      bool operator<(const RetOrArg &O) const {
61193323Sed        if (F != O.F)
62193323Sed          return F < O.F;
63193323Sed        else if (Idx != O.Idx)
64193323Sed          return Idx < O.Idx;
65193323Sed        else
66193323Sed          return IsArg < O.IsArg;
67193323Sed      }
68193323Sed
69193323Sed      /// Make RetOrArg comparable, so we can easily iterate the multimap.
70193323Sed      bool operator==(const RetOrArg &O) const {
71193323Sed        return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
72193323Sed      }
73193323Sed
74193323Sed      std::string getDescription() const {
75206083Srdivacky        return std::string((IsArg ? "Argument #" : "Return value #"))
76198090Srdivacky               + utostr(Idx) + " of function " + F->getNameStr();
77193323Sed      }
78193323Sed    };
79193323Sed
80193323Sed    /// Liveness enum - During our initial pass over the program, we determine
81193323Sed    /// that things are either alive or maybe alive. We don't mark anything
82193323Sed    /// explicitly dead (even if we know they are), since anything not alive
83193323Sed    /// with no registered uses (in Uses) will never be marked alive and will
84193323Sed    /// thus become dead in the end.
85193323Sed    enum Liveness { Live, MaybeLive };
86193323Sed
87193323Sed    /// Convenience wrapper
88193323Sed    RetOrArg CreateRet(const Function *F, unsigned Idx) {
89193323Sed      return RetOrArg(F, Idx, false);
90193323Sed    }
91193323Sed    /// Convenience wrapper
92193323Sed    RetOrArg CreateArg(const Function *F, unsigned Idx) {
93193323Sed      return RetOrArg(F, Idx, true);
94193323Sed    }
95193323Sed
96193323Sed    typedef std::multimap<RetOrArg, RetOrArg> UseMap;
97193323Sed    /// This maps a return value or argument to any MaybeLive return values or
98193323Sed    /// arguments it uses. This allows the MaybeLive values to be marked live
99193323Sed    /// when any of its users is marked live.
100193323Sed    /// For example (indices are left out for clarity):
101193323Sed    ///  - Uses[ret F] = ret G
102193323Sed    ///    This means that F calls G, and F returns the value returned by G.
103193323Sed    ///  - Uses[arg F] = ret G
104193323Sed    ///    This means that some function calls G and passes its result as an
105193323Sed    ///    argument to F.
106193323Sed    ///  - Uses[ret F] = arg F
107193323Sed    ///    This means that F returns one of its own arguments.
108193323Sed    ///  - Uses[arg F] = arg G
109193323Sed    ///    This means that G calls F and passes one of its own (G's) arguments
110193323Sed    ///    directly to F.
111193323Sed    UseMap Uses;
112193323Sed
113193323Sed    typedef std::set<RetOrArg> LiveSet;
114193323Sed    typedef std::set<const Function*> LiveFuncSet;
115193323Sed
116193323Sed    /// This set contains all values that have been determined to be live.
117193323Sed    LiveSet LiveValues;
118193323Sed    /// This set contains all values that are cannot be changed in any way.
119193323Sed    LiveFuncSet LiveFunctions;
120193323Sed
121193323Sed    typedef SmallVector<RetOrArg, 5> UseVector;
122193323Sed
123193323Sed  public:
124193323Sed    static char ID; // Pass identification, replacement for typeid
125193323Sed    DAE() : ModulePass(&ID) {}
126193323Sed    bool runOnModule(Module &M);
127193323Sed
128193323Sed    virtual bool ShouldHackArguments() const { return false; }
129193323Sed
130193323Sed  private:
131193323Sed    Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
132206083Srdivacky    Liveness SurveyUse(Value::const_use_iterator U, UseVector &MaybeLiveUses,
133193323Sed                       unsigned RetValNum = 0);
134206083Srdivacky    Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
135193323Sed
136206083Srdivacky    void SurveyFunction(const Function &F);
137193323Sed    void MarkValue(const RetOrArg &RA, Liveness L,
138193323Sed                   const UseVector &MaybeLiveUses);
139193323Sed    void MarkLive(const RetOrArg &RA);
140193323Sed    void MarkLive(const Function &F);
141193323Sed    void PropagateLiveness(const RetOrArg &RA);
142193323Sed    bool RemoveDeadStuffFromFunction(Function *F);
143193323Sed    bool DeleteDeadVarargs(Function &Fn);
144193323Sed  };
145193323Sed}
146193323Sed
147193323Sed
148193323Sedchar DAE::ID = 0;
149193323Sedstatic RegisterPass<DAE>
150193323SedX("deadargelim", "Dead Argument Elimination");
151193323Sed
152193323Sednamespace {
153193323Sed  /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
154193323Sed  /// deletes arguments to functions which are external.  This is only for use
155193323Sed  /// by bugpoint.
156193323Sed  struct DAH : public DAE {
157193323Sed    static char ID;
158193323Sed    virtual bool ShouldHackArguments() const { return true; }
159193323Sed  };
160193323Sed}
161193323Sed
162193323Sedchar DAH::ID = 0;
163193323Sedstatic RegisterPass<DAH>
164193323SedY("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
165193323Sed
166193323Sed/// createDeadArgEliminationPass - This pass removes arguments from functions
167193323Sed/// which are not used by the body of the function.
168193323Sed///
169193323SedModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
170193323SedModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
171193323Sed
172193323Sed/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
173193323Sed/// llvm.vastart is never called, the varargs list is dead for the function.
174193323Sedbool DAE::DeleteDeadVarargs(Function &Fn) {
175193323Sed  assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
176193323Sed  if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
177193323Sed
178193323Sed  // Ensure that the function is only directly called.
179194178Sed  if (Fn.hasAddressTaken())
180194178Sed    return false;
181193323Sed
182193323Sed  // Okay, we know we can transform this function if safe.  Scan its body
183193323Sed  // looking for calls to llvm.vastart.
184193323Sed  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
185193323Sed    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
186193323Sed      if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
187193323Sed        if (II->getIntrinsicID() == Intrinsic::vastart)
188193323Sed          return false;
189193323Sed      }
190193323Sed    }
191193323Sed  }
192193323Sed
193193323Sed  // If we get here, there are no calls to llvm.vastart in the function body,
194193323Sed  // remove the "..." and adjust all the calls.
195193323Sed
196193323Sed  // Start by computing a new prototype for the function, which is the same as
197193323Sed  // the old function, but doesn't have isVarArg set.
198193323Sed  const FunctionType *FTy = Fn.getFunctionType();
199206083Srdivacky
200193323Sed  std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
201198090Srdivacky  FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
202198090Srdivacky                                                Params, false);
203193323Sed  unsigned NumArgs = Params.size();
204193323Sed
205193323Sed  // Create the new function body and insert it into the module...
206193323Sed  Function *NF = Function::Create(NFTy, Fn.getLinkage());
207193323Sed  NF->copyAttributesFrom(&Fn);
208193323Sed  Fn.getParent()->getFunctionList().insert(&Fn, NF);
209193323Sed  NF->takeName(&Fn);
210193323Sed
211193323Sed  // Loop over all of the callers of the function, transforming the call sites
212193323Sed  // to pass in a smaller number of arguments into the new function.
213193323Sed  //
214193323Sed  std::vector<Value*> Args;
215193323Sed  while (!Fn.use_empty()) {
216193323Sed    CallSite CS = CallSite::get(Fn.use_back());
217193323Sed    Instruction *Call = CS.getInstruction();
218193323Sed
219193323Sed    // Pass all the same arguments.
220193323Sed    Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
221193323Sed
222193323Sed    // Drop any attributes that were on the vararg arguments.
223193323Sed    AttrListPtr PAL = CS.getAttributes();
224193323Sed    if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
225193323Sed      SmallVector<AttributeWithIndex, 8> AttributesVec;
226193323Sed      for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
227193323Sed        AttributesVec.push_back(PAL.getSlot(i));
228206083Srdivacky      if (Attributes FnAttrs = PAL.getFnAttributes())
229193323Sed        AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
230193323Sed      PAL = AttrListPtr::get(AttributesVec.begin(), AttributesVec.end());
231193323Sed    }
232193323Sed
233193323Sed    Instruction *New;
234193323Sed    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
235193323Sed      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
236193323Sed                               Args.begin(), Args.end(), "", Call);
237193323Sed      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
238193323Sed      cast<InvokeInst>(New)->setAttributes(PAL);
239193323Sed    } else {
240193323Sed      New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
241193323Sed      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
242193323Sed      cast<CallInst>(New)->setAttributes(PAL);
243193323Sed      if (cast<CallInst>(Call)->isTailCall())
244193323Sed        cast<CallInst>(New)->setTailCall();
245193323Sed    }
246207618Srdivacky    if (MDNode *N = Call->getDbgMetadata())
247207618Srdivacky      New->setDbgMetadata(N);
248207618Srdivacky
249193323Sed    Args.clear();
250193323Sed
251193323Sed    if (!Call->use_empty())
252193323Sed      Call->replaceAllUsesWith(New);
253193323Sed
254193323Sed    New->takeName(Call);
255193323Sed
256193323Sed    // Finally, remove the old call from the program, reducing the use-count of
257193323Sed    // F.
258193323Sed    Call->eraseFromParent();
259193323Sed  }
260193323Sed
261193323Sed  // Since we have now created the new function, splice the body of the old
262193323Sed  // function right into the new function, leaving the old rotting hulk of the
263193323Sed  // function empty.
264193323Sed  NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
265193323Sed
266193323Sed  // Loop over the argument list, transfering uses of the old arguments over to
267193323Sed  // the new arguments, also transfering over the names as well.  While we're at
268193323Sed  // it, remove the dead arguments from the DeadArguments list.
269193323Sed  //
270193323Sed  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
271193323Sed       I2 = NF->arg_begin(); I != E; ++I, ++I2) {
272193323Sed    // Move the name and users over to the new version.
273193323Sed    I->replaceAllUsesWith(I2);
274193323Sed    I2->takeName(I);
275193323Sed  }
276193323Sed
277193323Sed  // Finally, nuke the old function.
278193323Sed  Fn.eraseFromParent();
279193323Sed  return true;
280193323Sed}
281193323Sed
282193323Sed/// Convenience function that returns the number of return values. It returns 0
283193323Sed/// for void functions and 1 for functions not returning a struct. It returns
284193323Sed/// the number of struct elements for functions returning a struct.
285193323Sedstatic unsigned NumRetVals(const Function *F) {
286206083Srdivacky  if (F->getReturnType()->isVoidTy())
287193323Sed    return 0;
288193323Sed  else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType()))
289193323Sed    return STy->getNumElements();
290193323Sed  else
291193323Sed    return 1;
292193323Sed}
293193323Sed
294193323Sed/// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
295193323Sed/// live, it adds Use to the MaybeLiveUses argument. Returns the determined
296193323Sed/// liveness of Use.
297193323SedDAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
298193323Sed  // We're live if our use or its Function is already marked as live.
299193323Sed  if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
300193323Sed    return Live;
301193323Sed
302193323Sed  // We're maybe live otherwise, but remember that we must become live if
303193323Sed  // Use becomes live.
304193323Sed  MaybeLiveUses.push_back(Use);
305193323Sed  return MaybeLive;
306193323Sed}
307193323Sed
308193323Sed
309193323Sed/// SurveyUse - This looks at a single use of an argument or return value
310193323Sed/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
311206083Srdivacky/// if it causes the used value to become MaybeLive.
312193323Sed///
313193323Sed/// RetValNum is the return value number to use when this use is used in a
314193323Sed/// return instruction. This is used in the recursion, you should always leave
315193323Sed/// it at 0.
316206083SrdivackyDAE::Liveness DAE::SurveyUse(Value::const_use_iterator U,
317206083Srdivacky                             UseVector &MaybeLiveUses, unsigned RetValNum) {
318206083Srdivacky    const User *V = *U;
319206083Srdivacky    if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
320193323Sed      // The value is returned from a function. It's only live when the
321193323Sed      // function's return value is live. We use RetValNum here, for the case
322193323Sed      // that U is really a use of an insertvalue instruction that uses the
323193323Sed      // orginal Use.
324193323Sed      RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
325193323Sed      // We might be live, depending on the liveness of Use.
326193323Sed      return MarkIfNotLive(Use, MaybeLiveUses);
327193323Sed    }
328206083Srdivacky    if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
329193323Sed      if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
330193323Sed          && IV->hasIndices())
331193323Sed        // The use we are examining is inserted into an aggregate. Our liveness
332193323Sed        // depends on all uses of that aggregate, but if it is used as a return
333193323Sed        // value, only index at which we were inserted counts.
334193323Sed        RetValNum = *IV->idx_begin();
335193323Sed
336193323Sed      // Note that if we are used as the aggregate operand to the insertvalue,
337193323Sed      // we don't change RetValNum, but do survey all our uses.
338193323Sed
339193323Sed      Liveness Result = MaybeLive;
340206083Srdivacky      for (Value::const_use_iterator I = IV->use_begin(),
341193323Sed           E = V->use_end(); I != E; ++I) {
342193323Sed        Result = SurveyUse(I, MaybeLiveUses, RetValNum);
343193323Sed        if (Result == Live)
344193323Sed          break;
345193323Sed      }
346193323Sed      return Result;
347193323Sed    }
348206083Srdivacky
349206083Srdivacky    if (ImmutableCallSite CS = V) {
350206083Srdivacky      const Function *F = CS.getCalledFunction();
351193323Sed      if (F) {
352193323Sed        // Used in a direct call.
353206083Srdivacky
354193323Sed        // Find the argument number. We know for sure that this use is an
355193323Sed        // argument, since if it was the function argument this would be an
356193323Sed        // indirect call and the we know can't be looking at a value of the
357193323Sed        // label type (for the invoke instruction).
358206083Srdivacky        unsigned ArgNo = CS.getArgumentNo(U);
359193323Sed
360193323Sed        if (ArgNo >= F->getFunctionType()->getNumParams())
361193323Sed          // The value is passed in through a vararg! Must be live.
362193323Sed          return Live;
363193323Sed
364206083Srdivacky        assert(CS.getArgument(ArgNo)
365206083Srdivacky               == CS->getOperand(U.getOperandNo())
366193323Sed               && "Argument is not where we expected it");
367193323Sed
368193323Sed        // Value passed to a normal call. It's only live when the corresponding
369193323Sed        // argument to the called function turns out live.
370193323Sed        RetOrArg Use = CreateArg(F, ArgNo);
371193323Sed        return MarkIfNotLive(Use, MaybeLiveUses);
372193323Sed      }
373193323Sed    }
374193323Sed    // Used in any other way? Value must be live.
375193323Sed    return Live;
376193323Sed}
377193323Sed
378193323Sed/// SurveyUses - This looks at all the uses of the given value
379193323Sed/// Returns the Liveness deduced from the uses of this value.
380193323Sed///
381193323Sed/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
382193323Sed/// the result is Live, MaybeLiveUses might be modified but its content should
383193323Sed/// be ignored (since it might not be complete).
384206083SrdivackyDAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
385193323Sed  // Assume it's dead (which will only hold if there are no uses at all..).
386193323Sed  Liveness Result = MaybeLive;
387193323Sed  // Check each use.
388206083Srdivacky  for (Value::const_use_iterator I = V->use_begin(),
389193323Sed       E = V->use_end(); I != E; ++I) {
390193323Sed    Result = SurveyUse(I, MaybeLiveUses);
391193323Sed    if (Result == Live)
392193323Sed      break;
393193323Sed  }
394193323Sed  return Result;
395193323Sed}
396193323Sed
397193323Sed// SurveyFunction - This performs the initial survey of the specified function,
398193323Sed// checking out whether or not it uses any of its incoming arguments or whether
399193323Sed// any callers use the return value.  This fills in the LiveValues set and Uses
400193323Sed// map.
401193323Sed//
402193323Sed// We consider arguments of non-internal functions to be intrinsically alive as
403193323Sed// well as arguments to functions which have their "address taken".
404193323Sed//
405206083Srdivackyvoid DAE::SurveyFunction(const Function &F) {
406193323Sed  unsigned RetCount = NumRetVals(&F);
407193323Sed  // Assume all return values are dead
408193323Sed  typedef SmallVector<Liveness, 5> RetVals;
409193323Sed  RetVals RetValLiveness(RetCount, MaybeLive);
410193323Sed
411193323Sed  typedef SmallVector<UseVector, 5> RetUses;
412193323Sed  // These vectors map each return value to the uses that make it MaybeLive, so
413193323Sed  // we can add those to the Uses map if the return value really turns out to be
414193323Sed  // MaybeLive. Initialized to a list of RetCount empty lists.
415193323Sed  RetUses MaybeLiveRetUses(RetCount);
416193323Sed
417206083Srdivacky  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
418206083Srdivacky    if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
419193323Sed      if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
420193323Sed          != F.getFunctionType()->getReturnType()) {
421193323Sed        // We don't support old style multiple return values.
422193323Sed        MarkLive(F);
423193323Sed        return;
424193323Sed      }
425193323Sed
426193323Sed  if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
427193323Sed    MarkLive(F);
428193323Sed    return;
429193323Sed  }
430193323Sed
431202375Srdivacky  DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
432193323Sed  // Keep track of the number of live retvals, so we can skip checks once all
433193323Sed  // of them turn out to be live.
434193323Sed  unsigned NumLiveRetVals = 0;
435193323Sed  const Type *STy = dyn_cast<StructType>(F.getReturnType());
436193323Sed  // Loop all uses of the function.
437206083Srdivacky  for (Value::const_use_iterator I = F.use_begin(), E = F.use_end();
438206083Srdivacky       I != E; ++I) {
439193323Sed    // If the function is PASSED IN as an argument, its address has been
440193323Sed    // taken.
441206083Srdivacky    ImmutableCallSite CS(*I);
442206083Srdivacky    if (!CS || !CS.isCallee(I)) {
443193323Sed      MarkLive(F);
444193323Sed      return;
445193323Sed    }
446193323Sed
447193323Sed    // If this use is anything other than a call site, the function is alive.
448206083Srdivacky    const Instruction *TheCall = CS.getInstruction();
449193323Sed    if (!TheCall) {   // Not a direct call site?
450193323Sed      MarkLive(F);
451193323Sed      return;
452193323Sed    }
453193323Sed
454193323Sed    // If we end up here, we are looking at a direct call to our function.
455193323Sed
456193323Sed    // Now, check how our return value(s) is/are used in this caller. Don't
457193323Sed    // bother checking return values if all of them are live already.
458193323Sed    if (NumLiveRetVals != RetCount) {
459193323Sed      if (STy) {
460193323Sed        // Check all uses of the return value.
461206083Srdivacky        for (Value::const_use_iterator I = TheCall->use_begin(),
462193323Sed             E = TheCall->use_end(); I != E; ++I) {
463206083Srdivacky          const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
464193323Sed          if (Ext && Ext->hasIndices()) {
465193323Sed            // This use uses a part of our return value, survey the uses of
466193323Sed            // that part and store the results for this index only.
467193323Sed            unsigned Idx = *Ext->idx_begin();
468193323Sed            if (RetValLiveness[Idx] != Live) {
469193323Sed              RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
470193323Sed              if (RetValLiveness[Idx] == Live)
471193323Sed                NumLiveRetVals++;
472193323Sed            }
473193323Sed          } else {
474193323Sed            // Used by something else than extractvalue. Mark all return
475193323Sed            // values as live.
476193323Sed            for (unsigned i = 0; i != RetCount; ++i )
477193323Sed              RetValLiveness[i] = Live;
478193323Sed            NumLiveRetVals = RetCount;
479193323Sed            break;
480193323Sed          }
481193323Sed        }
482193323Sed      } else {
483193323Sed        // Single return value
484193323Sed        RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
485193323Sed        if (RetValLiveness[0] == Live)
486193323Sed          NumLiveRetVals = RetCount;
487193323Sed      }
488193323Sed    }
489193323Sed  }
490193323Sed
491193323Sed  // Now we've inspected all callers, record the liveness of our return values.
492193323Sed  for (unsigned i = 0; i != RetCount; ++i)
493193323Sed    MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
494193323Sed
495202375Srdivacky  DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
496193323Sed
497193323Sed  // Now, check all of our arguments.
498193323Sed  unsigned i = 0;
499193323Sed  UseVector MaybeLiveArgUses;
500206083Srdivacky  for (Function::const_arg_iterator AI = F.arg_begin(),
501193323Sed       E = F.arg_end(); AI != E; ++AI, ++i) {
502193323Sed    // See what the effect of this use is (recording any uses that cause
503193323Sed    // MaybeLive in MaybeLiveArgUses).
504193323Sed    Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
505193323Sed    // Mark the result.
506193323Sed    MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
507193323Sed    // Clear the vector again for the next iteration.
508193323Sed    MaybeLiveArgUses.clear();
509193323Sed  }
510193323Sed}
511193323Sed
512193323Sed/// MarkValue - This function marks the liveness of RA depending on L. If L is
513193323Sed/// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
514193323Sed/// such that RA will be marked live if any use in MaybeLiveUses gets marked
515193323Sed/// live later on.
516193323Sedvoid DAE::MarkValue(const RetOrArg &RA, Liveness L,
517193323Sed                    const UseVector &MaybeLiveUses) {
518193323Sed  switch (L) {
519193323Sed    case Live: MarkLive(RA); break;
520193323Sed    case MaybeLive:
521193323Sed    {
522193323Sed      // Note any uses of this value, so this return value can be
523193323Sed      // marked live whenever one of the uses becomes live.
524193323Sed      for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
525193323Sed           UE = MaybeLiveUses.end(); UI != UE; ++UI)
526193323Sed        Uses.insert(std::make_pair(*UI, RA));
527193323Sed      break;
528193323Sed    }
529193323Sed  }
530193323Sed}
531193323Sed
532193323Sed/// MarkLive - Mark the given Function as alive, meaning that it cannot be
533193323Sed/// changed in any way. Additionally,
534193323Sed/// mark any values that are used as this function's parameters or by its return
535193323Sed/// values (according to Uses) live as well.
536193323Sedvoid DAE::MarkLive(const Function &F) {
537202375Srdivacky  DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
538208599Srdivacky  // Mark the function as live.
539208599Srdivacky  LiveFunctions.insert(&F);
540208599Srdivacky  // Mark all arguments as live.
541208599Srdivacky  for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
542208599Srdivacky    PropagateLiveness(CreateArg(&F, i));
543208599Srdivacky  // Mark all return values as live.
544208599Srdivacky  for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
545208599Srdivacky    PropagateLiveness(CreateRet(&F, i));
546193323Sed}
547193323Sed
548193323Sed/// MarkLive - Mark the given return value or argument as live. Additionally,
549193323Sed/// mark any values that are used by this value (according to Uses) live as
550193323Sed/// well.
551193323Sedvoid DAE::MarkLive(const RetOrArg &RA) {
552193323Sed  if (LiveFunctions.count(RA.F))
553193323Sed    return; // Function was already marked Live.
554193323Sed
555193323Sed  if (!LiveValues.insert(RA).second)
556193323Sed    return; // We were already marked Live.
557193323Sed
558202375Srdivacky  DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
559193323Sed  PropagateLiveness(RA);
560193323Sed}
561193323Sed
562193323Sed/// PropagateLiveness - Given that RA is a live value, propagate it's liveness
563193323Sed/// to any other values it uses (according to Uses).
564193323Sedvoid DAE::PropagateLiveness(const RetOrArg &RA) {
565193323Sed  // We don't use upper_bound (or equal_range) here, because our recursive call
566193323Sed  // to ourselves is likely to cause the upper_bound (which is the first value
567193323Sed  // not belonging to RA) to become erased and the iterator invalidated.
568193323Sed  UseMap::iterator Begin = Uses.lower_bound(RA);
569193323Sed  UseMap::iterator E = Uses.end();
570193323Sed  UseMap::iterator I;
571193323Sed  for (I = Begin; I != E && I->first == RA; ++I)
572193323Sed    MarkLive(I->second);
573193323Sed
574193323Sed  // Erase RA from the Uses map (from the lower bound to wherever we ended up
575193323Sed  // after the loop).
576193323Sed  Uses.erase(Begin, I);
577193323Sed}
578193323Sed
579193323Sed// RemoveDeadStuffFromFunction - Remove any arguments and return values from F
580193323Sed// that are not in LiveValues. Transform the function and all of the callees of
581193323Sed// the function to not have these arguments and return values.
582193323Sed//
583193323Sedbool DAE::RemoveDeadStuffFromFunction(Function *F) {
584193323Sed  // Don't modify fully live functions
585193323Sed  if (LiveFunctions.count(F))
586193323Sed    return false;
587193323Sed
588193323Sed  // Start by computing a new prototype for the function, which is the same as
589193323Sed  // the old function, but has fewer arguments and a different return type.
590193323Sed  const FunctionType *FTy = F->getFunctionType();
591193323Sed  std::vector<const Type*> Params;
592193323Sed
593193323Sed  // Set up to build a new list of parameter attributes.
594193323Sed  SmallVector<AttributeWithIndex, 8> AttributesVec;
595193323Sed  const AttrListPtr &PAL = F->getAttributes();
596193323Sed
597193323Sed  // The existing function return attributes.
598193323Sed  Attributes RAttrs = PAL.getRetAttributes();
599193323Sed  Attributes FnAttrs = PAL.getFnAttributes();
600193323Sed
601193323Sed  // Find out the new return value.
602193323Sed
603193323Sed  const Type *RetTy = FTy->getReturnType();
604193323Sed  const Type *NRetTy = NULL;
605193323Sed  unsigned RetCount = NumRetVals(F);
606206083Srdivacky
607193323Sed  // -1 means unused, other numbers are the new index
608193323Sed  SmallVector<int, 5> NewRetIdxs(RetCount, -1);
609193323Sed  std::vector<const Type*> RetTypes;
610206083Srdivacky  if (RetTy->isVoidTy()) {
611206083Srdivacky    NRetTy = RetTy;
612193323Sed  } else {
613193323Sed    const StructType *STy = dyn_cast<StructType>(RetTy);
614193323Sed    if (STy)
615193323Sed      // Look at each of the original return values individually.
616193323Sed      for (unsigned i = 0; i != RetCount; ++i) {
617193323Sed        RetOrArg Ret = CreateRet(F, i);
618193323Sed        if (LiveValues.erase(Ret)) {
619193323Sed          RetTypes.push_back(STy->getElementType(i));
620193323Sed          NewRetIdxs[i] = RetTypes.size() - 1;
621193323Sed        } else {
622193323Sed          ++NumRetValsEliminated;
623202375Srdivacky          DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
624198090Srdivacky                << F->getName() << "\n");
625193323Sed        }
626193323Sed      }
627193323Sed    else
628193323Sed      // We used to return a single value.
629193323Sed      if (LiveValues.erase(CreateRet(F, 0))) {
630193323Sed        RetTypes.push_back(RetTy);
631193323Sed        NewRetIdxs[0] = 0;
632193323Sed      } else {
633202375Srdivacky        DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
634198090Srdivacky              << "\n");
635193323Sed        ++NumRetValsEliminated;
636193323Sed      }
637193323Sed    if (RetTypes.size() > 1)
638193323Sed      // More than one return type? Return a struct with them. Also, if we used
639193323Sed      // to return a struct and didn't change the number of return values,
640193323Sed      // return a struct again. This prevents changing {something} into
641193323Sed      // something and {} into void.
642193323Sed      // Make the new struct packed if we used to return a packed struct
643193323Sed      // already.
644198090Srdivacky      NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
645193323Sed    else if (RetTypes.size() == 1)
646193323Sed      // One return type? Just a simple value then, but only if we didn't use to
647193323Sed      // return a struct with that simple value before.
648193323Sed      NRetTy = RetTypes.front();
649193323Sed    else if (RetTypes.size() == 0)
650193323Sed      // No return types? Make it void, but only if we didn't use to return {}.
651198090Srdivacky      NRetTy = Type::getVoidTy(F->getContext());
652193323Sed  }
653193323Sed
654193323Sed  assert(NRetTy && "No new return type found?");
655193323Sed
656193323Sed  // Remove any incompatible attributes, but only if we removed all return
657193323Sed  // values. Otherwise, ensure that we don't have any conflicting attributes
658193323Sed  // here. Currently, this should not be possible, but special handling might be
659193323Sed  // required when new return value attributes are added.
660206083Srdivacky  if (NRetTy->isVoidTy())
661193323Sed    RAttrs &= ~Attribute::typeIncompatible(NRetTy);
662193323Sed  else
663206083Srdivacky    assert((RAttrs & Attribute::typeIncompatible(NRetTy)) == 0
664193323Sed           && "Return attributes no longer compatible?");
665193323Sed
666193323Sed  if (RAttrs)
667193323Sed    AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
668193323Sed
669193323Sed  // Remember which arguments are still alive.
670193323Sed  SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
671193323Sed  // Construct the new parameter list from non-dead arguments. Also construct
672193323Sed  // a new set of parameter attributes to correspond. Skip the first parameter
673193323Sed  // attribute, since that belongs to the return value.
674193323Sed  unsigned i = 0;
675193323Sed  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
676193323Sed       I != E; ++I, ++i) {
677193323Sed    RetOrArg Arg = CreateArg(F, i);
678193323Sed    if (LiveValues.erase(Arg)) {
679193323Sed      Params.push_back(I->getType());
680193323Sed      ArgAlive[i] = true;
681193323Sed
682193323Sed      // Get the original parameter attributes (skipping the first one, that is
683193323Sed      // for the return value.
684193323Sed      if (Attributes Attrs = PAL.getParamAttributes(i + 1))
685193323Sed        AttributesVec.push_back(AttributeWithIndex::get(Params.size(), Attrs));
686193323Sed    } else {
687193323Sed      ++NumArgumentsEliminated;
688202375Srdivacky      DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
689198090Srdivacky            << ") from " << F->getName() << "\n");
690193323Sed    }
691193323Sed  }
692193323Sed
693206083Srdivacky  if (FnAttrs != Attribute::None)
694193323Sed    AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
695193323Sed
696193323Sed  // Reconstruct the AttributesList based on the vector we constructed.
697206083Srdivacky  AttrListPtr NewPAL = AttrListPtr::get(AttributesVec.begin(),
698206083Srdivacky                                        AttributesVec.end());
699193323Sed
700193323Sed  // Create the new function type based on the recomputed parameters.
701206083Srdivacky  FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
702193323Sed
703193323Sed  // No change?
704193323Sed  if (NFTy == FTy)
705193323Sed    return false;
706193323Sed
707193323Sed  // Create the new function body and insert it into the module...
708193323Sed  Function *NF = Function::Create(NFTy, F->getLinkage());
709193323Sed  NF->copyAttributesFrom(F);
710193323Sed  NF->setAttributes(NewPAL);
711193323Sed  // Insert the new function before the old function, so we won't be processing
712193323Sed  // it again.
713193323Sed  F->getParent()->getFunctionList().insert(F, NF);
714193323Sed  NF->takeName(F);
715193323Sed
716193323Sed  // Loop over all of the callers of the function, transforming the call sites
717193323Sed  // to pass in a smaller number of arguments into the new function.
718193323Sed  //
719193323Sed  std::vector<Value*> Args;
720193323Sed  while (!F->use_empty()) {
721193323Sed    CallSite CS = CallSite::get(F->use_back());
722193323Sed    Instruction *Call = CS.getInstruction();
723193323Sed
724193323Sed    AttributesVec.clear();
725193323Sed    const AttrListPtr &CallPAL = CS.getAttributes();
726193323Sed
727193323Sed    // The call return attributes.
728193323Sed    Attributes RAttrs = CallPAL.getRetAttributes();
729193323Sed    Attributes FnAttrs = CallPAL.getFnAttributes();
730193323Sed    // Adjust in case the function was changed to return void.
731193323Sed    RAttrs &= ~Attribute::typeIncompatible(NF->getReturnType());
732193323Sed    if (RAttrs)
733193323Sed      AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
734193323Sed
735193323Sed    // Declare these outside of the loops, so we can reuse them for the second
736193323Sed    // loop, which loops the varargs.
737193323Sed    CallSite::arg_iterator I = CS.arg_begin();
738193323Sed    unsigned i = 0;
739193323Sed    // Loop over those operands, corresponding to the normal arguments to the
740193323Sed    // original function, and add those that are still alive.
741193323Sed    for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
742193323Sed      if (ArgAlive[i]) {
743193323Sed        Args.push_back(*I);
744193323Sed        // Get original parameter attributes, but skip return attributes.
745193323Sed        if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
746193323Sed          AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
747193323Sed      }
748193323Sed
749193323Sed    // Push any varargs arguments on the list. Don't forget their attributes.
750193323Sed    for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
751193323Sed      Args.push_back(*I);
752193323Sed      if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
753193323Sed        AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
754193323Sed    }
755193323Sed
756193323Sed    if (FnAttrs != Attribute::None)
757193323Sed      AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
758193323Sed
759193323Sed    // Reconstruct the AttributesList based on the vector we constructed.
760193323Sed    AttrListPtr NewCallPAL = AttrListPtr::get(AttributesVec.begin(),
761193323Sed                                              AttributesVec.end());
762193323Sed
763193323Sed    Instruction *New;
764193323Sed    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
765193323Sed      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
766193323Sed                               Args.begin(), Args.end(), "", Call);
767193323Sed      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
768193323Sed      cast<InvokeInst>(New)->setAttributes(NewCallPAL);
769193323Sed    } else {
770193323Sed      New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
771193323Sed      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
772193323Sed      cast<CallInst>(New)->setAttributes(NewCallPAL);
773193323Sed      if (cast<CallInst>(Call)->isTailCall())
774193323Sed        cast<CallInst>(New)->setTailCall();
775193323Sed    }
776207618Srdivacky    if (MDNode *N = Call->getDbgMetadata())
777207618Srdivacky      New->setDbgMetadata(N);
778207618Srdivacky
779193323Sed    Args.clear();
780193323Sed
781193323Sed    if (!Call->use_empty()) {
782193323Sed      if (New->getType() == Call->getType()) {
783193323Sed        // Return type not changed? Just replace users then.
784193323Sed        Call->replaceAllUsesWith(New);
785193323Sed        New->takeName(Call);
786206083Srdivacky      } else if (New->getType()->isVoidTy()) {
787193323Sed        // Our return value has uses, but they will get removed later on.
788193323Sed        // Replace by null for now.
789193323Sed        Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
790193323Sed      } else {
791204642Srdivacky        assert(RetTy->isStructTy() &&
792193323Sed               "Return type changed, but not into a void. The old return type"
793193323Sed               " must have been a struct!");
794193323Sed        Instruction *InsertPt = Call;
795193323Sed        if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
796193323Sed          BasicBlock::iterator IP = II->getNormalDest()->begin();
797193323Sed          while (isa<PHINode>(IP)) ++IP;
798193323Sed          InsertPt = IP;
799193323Sed        }
800206083Srdivacky
801193323Sed        // We used to return a struct. Instead of doing smart stuff with all the
802193323Sed        // uses of this struct, we will just rebuild it using
803193323Sed        // extract/insertvalue chaining and let instcombine clean that up.
804193323Sed        //
805193323Sed        // Start out building up our return value from undef
806198090Srdivacky        Value *RetVal = UndefValue::get(RetTy);
807193323Sed        for (unsigned i = 0; i != RetCount; ++i)
808193323Sed          if (NewRetIdxs[i] != -1) {
809193323Sed            Value *V;
810193323Sed            if (RetTypes.size() > 1)
811193323Sed              // We are still returning a struct, so extract the value from our
812193323Sed              // return value
813193323Sed              V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
814193323Sed                                           InsertPt);
815193323Sed            else
816193323Sed              // We are now returning a single element, so just insert that
817193323Sed              V = New;
818193323Sed            // Insert the value at the old position
819193323Sed            RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
820193323Sed          }
821193323Sed        // Now, replace all uses of the old call instruction with the return
822193323Sed        // struct we built
823193323Sed        Call->replaceAllUsesWith(RetVal);
824193323Sed        New->takeName(Call);
825193323Sed      }
826193323Sed    }
827193323Sed
828193323Sed    // Finally, remove the old call from the program, reducing the use-count of
829193323Sed    // F.
830193323Sed    Call->eraseFromParent();
831193323Sed  }
832193323Sed
833193323Sed  // Since we have now created the new function, splice the body of the old
834193323Sed  // function right into the new function, leaving the old rotting hulk of the
835193323Sed  // function empty.
836193323Sed  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
837193323Sed
838193323Sed  // Loop over the argument list, transfering uses of the old arguments over to
839193323Sed  // the new arguments, also transfering over the names as well.
840193323Sed  i = 0;
841193323Sed  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
842193323Sed       I2 = NF->arg_begin(); I != E; ++I, ++i)
843193323Sed    if (ArgAlive[i]) {
844193323Sed      // If this is a live argument, move the name and users over to the new
845193323Sed      // version.
846193323Sed      I->replaceAllUsesWith(I2);
847193323Sed      I2->takeName(I);
848193323Sed      ++I2;
849193323Sed    } else {
850193323Sed      // If this argument is dead, replace any uses of it with null constants
851193323Sed      // (these are guaranteed to become unused later on).
852193323Sed      I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
853193323Sed    }
854193323Sed
855193323Sed  // If we change the return value of the function we must rewrite any return
856193323Sed  // instructions.  Check this now.
857193323Sed  if (F->getReturnType() != NF->getReturnType())
858193323Sed    for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
859193323Sed      if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
860193323Sed        Value *RetVal;
861193323Sed
862208599Srdivacky        if (NFTy->getReturnType()->isVoidTy()) {
863193323Sed          RetVal = 0;
864193323Sed        } else {
865204642Srdivacky          assert (RetTy->isStructTy());
866193323Sed          // The original return value was a struct, insert
867193323Sed          // extractvalue/insertvalue chains to extract only the values we need
868193323Sed          // to return and insert them into our new result.
869193323Sed          // This does generate messy code, but we'll let it to instcombine to
870193323Sed          // clean that up.
871193323Sed          Value *OldRet = RI->getOperand(0);
872193323Sed          // Start out building up our return value from undef
873198090Srdivacky          RetVal = UndefValue::get(NRetTy);
874193323Sed          for (unsigned i = 0; i != RetCount; ++i)
875193323Sed            if (NewRetIdxs[i] != -1) {
876193323Sed              ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
877193323Sed                                                              "oldret", RI);
878193323Sed              if (RetTypes.size() > 1) {
879193323Sed                // We're still returning a struct, so reinsert the value into
880193323Sed                // our new return value at the new index
881193323Sed
882193323Sed                RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
883193323Sed                                                 "newret", RI);
884193323Sed              } else {
885193323Sed                // We are now only returning a simple value, so just return the
886193323Sed                // extracted value.
887193323Sed                RetVal = EV;
888193323Sed              }
889193323Sed            }
890193323Sed        }
891193323Sed        // Replace the return instruction with one returning the new return
892193323Sed        // value (possibly 0 if we became void).
893198090Srdivacky        ReturnInst::Create(F->getContext(), RetVal, RI);
894193323Sed        BB->getInstList().erase(RI);
895193323Sed      }
896193323Sed
897193323Sed  // Now that the old function is dead, delete it.
898193323Sed  F->eraseFromParent();
899193323Sed
900193323Sed  return true;
901193323Sed}
902193323Sed
903193323Sedbool DAE::runOnModule(Module &M) {
904193323Sed  bool Changed = false;
905193323Sed
906193323Sed  // First pass: Do a simple check to see if any functions can have their "..."
907193323Sed  // removed.  We can do this if they never call va_start.  This loop cannot be
908193323Sed  // fused with the next loop, because deleting a function invalidates
909193323Sed  // information computed while surveying other functions.
910202375Srdivacky  DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
911193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
912193323Sed    Function &F = *I++;
913193323Sed    if (F.getFunctionType()->isVarArg())
914193323Sed      Changed |= DeleteDeadVarargs(F);
915193323Sed  }
916193323Sed
917193323Sed  // Second phase:loop through the module, determining which arguments are live.
918193323Sed  // We assume all arguments are dead unless proven otherwise (allowing us to
919193323Sed  // determine that dead arguments passed into recursive functions are dead).
920193323Sed  //
921202375Srdivacky  DEBUG(dbgs() << "DAE - Determining liveness\n");
922193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
923193323Sed    SurveyFunction(*I);
924206083Srdivacky
925193323Sed  // Now, remove all dead arguments and return values from each function in
926206083Srdivacky  // turn.
927193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
928206083Srdivacky    // Increment now, because the function will probably get removed (ie.
929193323Sed    // replaced by a new one).
930193323Sed    Function *F = I++;
931193323Sed    Changed |= RemoveDeadStuffFromFunction(F);
932193323Sed  }
933193323Sed  return Changed;
934193323Sed}
935