DeadArgumentElimination.cpp revision 221345
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");
42218893SdimSTATISTIC(NumArgumentsReplacedWithUndef,
43218893Sdim          "Number of unread args replaced with undef");
44193323Sednamespace {
45193323Sed  /// DAE - The dead argument elimination pass.
46193323Sed  ///
47198892Srdivacky  class DAE : public ModulePass {
48193323Sed  public:
49193323Sed
50193323Sed    /// Struct that represents (part of) either a return value or a function
51193323Sed    /// argument.  Used so that arguments and return values can be used
52221345Sdim    /// interchangeably.
53193323Sed    struct RetOrArg {
54206083Srdivacky      RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
55193323Sed               IsArg(IsArg) {}
56193323Sed      const Function *F;
57193323Sed      unsigned Idx;
58193323Sed      bool IsArg;
59193323Sed
60193323Sed      /// Make RetOrArg comparable, so we can put it into a map.
61193323Sed      bool operator<(const RetOrArg &O) const {
62193323Sed        if (F != O.F)
63193323Sed          return F < O.F;
64193323Sed        else if (Idx != O.Idx)
65193323Sed          return Idx < O.Idx;
66193323Sed        else
67193323Sed          return IsArg < O.IsArg;
68193323Sed      }
69193323Sed
70193323Sed      /// Make RetOrArg comparable, so we can easily iterate the multimap.
71193323Sed      bool operator==(const RetOrArg &O) const {
72193323Sed        return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
73193323Sed      }
74193323Sed
75193323Sed      std::string getDescription() const {
76206083Srdivacky        return std::string((IsArg ? "Argument #" : "Return value #"))
77198090Srdivacky               + utostr(Idx) + " of function " + F->getNameStr();
78193323Sed      }
79193323Sed    };
80193323Sed
81193323Sed    /// Liveness enum - During our initial pass over the program, we determine
82193323Sed    /// that things are either alive or maybe alive. We don't mark anything
83193323Sed    /// explicitly dead (even if we know they are), since anything not alive
84193323Sed    /// with no registered uses (in Uses) will never be marked alive and will
85193323Sed    /// thus become dead in the end.
86193323Sed    enum Liveness { Live, MaybeLive };
87193323Sed
88193323Sed    /// Convenience wrapper
89193323Sed    RetOrArg CreateRet(const Function *F, unsigned Idx) {
90193323Sed      return RetOrArg(F, Idx, false);
91193323Sed    }
92193323Sed    /// Convenience wrapper
93193323Sed    RetOrArg CreateArg(const Function *F, unsigned Idx) {
94193323Sed      return RetOrArg(F, Idx, true);
95193323Sed    }
96193323Sed
97193323Sed    typedef std::multimap<RetOrArg, RetOrArg> UseMap;
98193323Sed    /// This maps a return value or argument to any MaybeLive return values or
99193323Sed    /// arguments it uses. This allows the MaybeLive values to be marked live
100193323Sed    /// when any of its users is marked live.
101193323Sed    /// For example (indices are left out for clarity):
102193323Sed    ///  - Uses[ret F] = ret G
103193323Sed    ///    This means that F calls G, and F returns the value returned by G.
104193323Sed    ///  - Uses[arg F] = ret G
105193323Sed    ///    This means that some function calls G and passes its result as an
106193323Sed    ///    argument to F.
107193323Sed    ///  - Uses[ret F] = arg F
108193323Sed    ///    This means that F returns one of its own arguments.
109193323Sed    ///  - Uses[arg F] = arg G
110193323Sed    ///    This means that G calls F and passes one of its own (G's) arguments
111193323Sed    ///    directly to F.
112193323Sed    UseMap Uses;
113193323Sed
114193323Sed    typedef std::set<RetOrArg> LiveSet;
115193323Sed    typedef std::set<const Function*> LiveFuncSet;
116193323Sed
117193323Sed    /// This set contains all values that have been determined to be live.
118193323Sed    LiveSet LiveValues;
119193323Sed    /// This set contains all values that are cannot be changed in any way.
120193323Sed    LiveFuncSet LiveFunctions;
121193323Sed
122193323Sed    typedef SmallVector<RetOrArg, 5> UseVector;
123193323Sed
124210299Sed  protected:
125210299Sed    // DAH uses this to specify a different ID.
126212904Sdim    explicit DAE(char &ID) : ModulePass(ID) {}
127210299Sed
128193323Sed  public:
129193323Sed    static char ID; // Pass identification, replacement for typeid
130218893Sdim    DAE() : ModulePass(ID) {
131218893Sdim      initializeDAEPass(*PassRegistry::getPassRegistry());
132218893Sdim    }
133210299Sed
134193323Sed    bool runOnModule(Module &M);
135193323Sed
136193323Sed    virtual bool ShouldHackArguments() const { return false; }
137193323Sed
138193323Sed  private:
139193323Sed    Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
140206083Srdivacky    Liveness SurveyUse(Value::const_use_iterator U, UseVector &MaybeLiveUses,
141193323Sed                       unsigned RetValNum = 0);
142206083Srdivacky    Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
143193323Sed
144206083Srdivacky    void SurveyFunction(const Function &F);
145193323Sed    void MarkValue(const RetOrArg &RA, Liveness L,
146193323Sed                   const UseVector &MaybeLiveUses);
147193323Sed    void MarkLive(const RetOrArg &RA);
148193323Sed    void MarkLive(const Function &F);
149193323Sed    void PropagateLiveness(const RetOrArg &RA);
150193323Sed    bool RemoveDeadStuffFromFunction(Function *F);
151193323Sed    bool DeleteDeadVarargs(Function &Fn);
152218893Sdim    bool RemoveDeadArgumentsFromCallers(Function &Fn);
153193323Sed  };
154193323Sed}
155193323Sed
156193323Sed
157193323Sedchar DAE::ID = 0;
158218893SdimINITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
159193323Sed
160193323Sednamespace {
161193323Sed  /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
162193323Sed  /// deletes arguments to functions which are external.  This is only for use
163193323Sed  /// by bugpoint.
164193323Sed  struct DAH : public DAE {
165193323Sed    static char ID;
166212904Sdim    DAH() : DAE(ID) {}
167210299Sed
168193323Sed    virtual bool ShouldHackArguments() const { return true; }
169193323Sed  };
170193323Sed}
171193323Sed
172193323Sedchar DAH::ID = 0;
173212904SdimINITIALIZE_PASS(DAH, "deadarghaX0r",
174212904Sdim                "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
175218893Sdim                false, false)
176193323Sed
177193323Sed/// createDeadArgEliminationPass - This pass removes arguments from functions
178193323Sed/// which are not used by the body of the function.
179193323Sed///
180193323SedModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
181193323SedModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
182193323Sed
183193323Sed/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
184193323Sed/// llvm.vastart is never called, the varargs list is dead for the function.
185193323Sedbool DAE::DeleteDeadVarargs(Function &Fn) {
186193323Sed  assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
187193323Sed  if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
188193323Sed
189193323Sed  // Ensure that the function is only directly called.
190194178Sed  if (Fn.hasAddressTaken())
191194178Sed    return false;
192193323Sed
193193323Sed  // Okay, we know we can transform this function if safe.  Scan its body
194193323Sed  // looking for calls to llvm.vastart.
195193323Sed  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
196193323Sed    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
197193323Sed      if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
198193323Sed        if (II->getIntrinsicID() == Intrinsic::vastart)
199193323Sed          return false;
200193323Sed      }
201193323Sed    }
202193323Sed  }
203193323Sed
204193323Sed  // If we get here, there are no calls to llvm.vastart in the function body,
205193323Sed  // remove the "..." and adjust all the calls.
206193323Sed
207193323Sed  // Start by computing a new prototype for the function, which is the same as
208193323Sed  // the old function, but doesn't have isVarArg set.
209193323Sed  const FunctionType *FTy = Fn.getFunctionType();
210206083Srdivacky
211193323Sed  std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
212198090Srdivacky  FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
213198090Srdivacky                                                Params, false);
214193323Sed  unsigned NumArgs = Params.size();
215193323Sed
216193323Sed  // Create the new function body and insert it into the module...
217193323Sed  Function *NF = Function::Create(NFTy, Fn.getLinkage());
218193323Sed  NF->copyAttributesFrom(&Fn);
219193323Sed  Fn.getParent()->getFunctionList().insert(&Fn, NF);
220193323Sed  NF->takeName(&Fn);
221193323Sed
222193323Sed  // Loop over all of the callers of the function, transforming the call sites
223193323Sed  // to pass in a smaller number of arguments into the new function.
224193323Sed  //
225193323Sed  std::vector<Value*> Args;
226193323Sed  while (!Fn.use_empty()) {
227212904Sdim    CallSite CS(Fn.use_back());
228193323Sed    Instruction *Call = CS.getInstruction();
229193323Sed
230193323Sed    // Pass all the same arguments.
231212904Sdim    Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
232193323Sed
233193323Sed    // Drop any attributes that were on the vararg arguments.
234193323Sed    AttrListPtr PAL = CS.getAttributes();
235193323Sed    if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
236193323Sed      SmallVector<AttributeWithIndex, 8> AttributesVec;
237193323Sed      for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
238193323Sed        AttributesVec.push_back(PAL.getSlot(i));
239206083Srdivacky      if (Attributes FnAttrs = PAL.getFnAttributes())
240193323Sed        AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
241193323Sed      PAL = AttrListPtr::get(AttributesVec.begin(), AttributesVec.end());
242193323Sed    }
243193323Sed
244193323Sed    Instruction *New;
245193323Sed    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
246193323Sed      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
247193323Sed                               Args.begin(), Args.end(), "", Call);
248193323Sed      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
249193323Sed      cast<InvokeInst>(New)->setAttributes(PAL);
250193323Sed    } else {
251193323Sed      New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
252193323Sed      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
253193323Sed      cast<CallInst>(New)->setAttributes(PAL);
254193323Sed      if (cast<CallInst>(Call)->isTailCall())
255193323Sed        cast<CallInst>(New)->setTailCall();
256193323Sed    }
257212904Sdim    New->setDebugLoc(Call->getDebugLoc());
258207618Srdivacky
259193323Sed    Args.clear();
260193323Sed
261193323Sed    if (!Call->use_empty())
262193323Sed      Call->replaceAllUsesWith(New);
263193323Sed
264193323Sed    New->takeName(Call);
265193323Sed
266193323Sed    // Finally, remove the old call from the program, reducing the use-count of
267193323Sed    // F.
268193323Sed    Call->eraseFromParent();
269193323Sed  }
270193323Sed
271193323Sed  // Since we have now created the new function, splice the body of the old
272193323Sed  // function right into the new function, leaving the old rotting hulk of the
273193323Sed  // function empty.
274193323Sed  NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
275193323Sed
276221345Sdim  // Loop over the argument list, transferring uses of the old arguments over to
277221345Sdim  // the new arguments, also transferring over the names as well.  While we're at
278193323Sed  // it, remove the dead arguments from the DeadArguments list.
279193323Sed  //
280193323Sed  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
281193323Sed       I2 = NF->arg_begin(); I != E; ++I, ++I2) {
282193323Sed    // Move the name and users over to the new version.
283193323Sed    I->replaceAllUsesWith(I2);
284193323Sed    I2->takeName(I);
285193323Sed  }
286193323Sed
287193323Sed  // Finally, nuke the old function.
288193323Sed  Fn.eraseFromParent();
289193323Sed  return true;
290193323Sed}
291193323Sed
292218893Sdim/// RemoveDeadArgumentsFromCallers - Checks if the given function has any
293218893Sdim/// arguments that are unused, and changes the caller parameters to be undefined
294218893Sdim/// instead.
295218893Sdimbool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
296218893Sdim{
297221345Sdim  if (Fn.isDeclaration() || Fn.mayBeOverridden())
298218893Sdim    return false;
299218893Sdim
300218893Sdim  // Functions with local linkage should already have been handled.
301218893Sdim  if (Fn.hasLocalLinkage())
302218893Sdim    return false;
303218893Sdim
304218893Sdim  if (Fn.use_empty())
305218893Sdim    return false;
306218893Sdim
307218893Sdim  llvm::SmallVector<unsigned, 8> UnusedArgs;
308218893Sdim  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
309218893Sdim       I != E; ++I) {
310218893Sdim    Argument *Arg = I;
311218893Sdim
312218893Sdim    if (Arg->use_empty() && !Arg->hasByValAttr())
313218893Sdim      UnusedArgs.push_back(Arg->getArgNo());
314218893Sdim  }
315218893Sdim
316218893Sdim  if (UnusedArgs.empty())
317218893Sdim    return false;
318218893Sdim
319218893Sdim  bool Changed = false;
320218893Sdim
321218893Sdim  for (Function::use_iterator I = Fn.use_begin(), E = Fn.use_end();
322218893Sdim       I != E; ++I) {
323218893Sdim    CallSite CS(*I);
324218893Sdim    if (!CS || !CS.isCallee(I))
325218893Sdim      continue;
326218893Sdim
327218893Sdim    // Now go through all unused args and replace them with "undef".
328218893Sdim    for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
329218893Sdim      unsigned ArgNo = UnusedArgs[I];
330218893Sdim
331218893Sdim      Value *Arg = CS.getArgument(ArgNo);
332218893Sdim      CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
333218893Sdim      ++NumArgumentsReplacedWithUndef;
334218893Sdim      Changed = true;
335218893Sdim    }
336218893Sdim  }
337218893Sdim
338218893Sdim  return Changed;
339218893Sdim}
340218893Sdim
341193323Sed/// Convenience function that returns the number of return values. It returns 0
342193323Sed/// for void functions and 1 for functions not returning a struct. It returns
343193323Sed/// the number of struct elements for functions returning a struct.
344193323Sedstatic unsigned NumRetVals(const Function *F) {
345206083Srdivacky  if (F->getReturnType()->isVoidTy())
346193323Sed    return 0;
347193323Sed  else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType()))
348193323Sed    return STy->getNumElements();
349193323Sed  else
350193323Sed    return 1;
351193323Sed}
352193323Sed
353193323Sed/// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
354193323Sed/// live, it adds Use to the MaybeLiveUses argument. Returns the determined
355193323Sed/// liveness of Use.
356193323SedDAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
357193323Sed  // We're live if our use or its Function is already marked as live.
358193323Sed  if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
359193323Sed    return Live;
360193323Sed
361193323Sed  // We're maybe live otherwise, but remember that we must become live if
362193323Sed  // Use becomes live.
363193323Sed  MaybeLiveUses.push_back(Use);
364193323Sed  return MaybeLive;
365193323Sed}
366193323Sed
367193323Sed
368193323Sed/// SurveyUse - This looks at a single use of an argument or return value
369193323Sed/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
370206083Srdivacky/// if it causes the used value to become MaybeLive.
371193323Sed///
372193323Sed/// RetValNum is the return value number to use when this use is used in a
373193323Sed/// return instruction. This is used in the recursion, you should always leave
374193323Sed/// it at 0.
375206083SrdivackyDAE::Liveness DAE::SurveyUse(Value::const_use_iterator U,
376206083Srdivacky                             UseVector &MaybeLiveUses, unsigned RetValNum) {
377206083Srdivacky    const User *V = *U;
378206083Srdivacky    if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
379193323Sed      // The value is returned from a function. It's only live when the
380193323Sed      // function's return value is live. We use RetValNum here, for the case
381193323Sed      // that U is really a use of an insertvalue instruction that uses the
382221345Sdim      // original Use.
383193323Sed      RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
384193323Sed      // We might be live, depending on the liveness of Use.
385193323Sed      return MarkIfNotLive(Use, MaybeLiveUses);
386193323Sed    }
387206083Srdivacky    if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
388193323Sed      if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
389193323Sed          && IV->hasIndices())
390193323Sed        // The use we are examining is inserted into an aggregate. Our liveness
391193323Sed        // depends on all uses of that aggregate, but if it is used as a return
392193323Sed        // value, only index at which we were inserted counts.
393193323Sed        RetValNum = *IV->idx_begin();
394193323Sed
395193323Sed      // Note that if we are used as the aggregate operand to the insertvalue,
396193323Sed      // we don't change RetValNum, but do survey all our uses.
397193323Sed
398193323Sed      Liveness Result = MaybeLive;
399206083Srdivacky      for (Value::const_use_iterator I = IV->use_begin(),
400193323Sed           E = V->use_end(); I != E; ++I) {
401193323Sed        Result = SurveyUse(I, MaybeLiveUses, RetValNum);
402193323Sed        if (Result == Live)
403193323Sed          break;
404193323Sed      }
405193323Sed      return Result;
406193323Sed    }
407206083Srdivacky
408206083Srdivacky    if (ImmutableCallSite CS = V) {
409206083Srdivacky      const Function *F = CS.getCalledFunction();
410193323Sed      if (F) {
411193323Sed        // Used in a direct call.
412206083Srdivacky
413193323Sed        // Find the argument number. We know for sure that this use is an
414193323Sed        // argument, since if it was the function argument this would be an
415193323Sed        // indirect call and the we know can't be looking at a value of the
416193323Sed        // label type (for the invoke instruction).
417206083Srdivacky        unsigned ArgNo = CS.getArgumentNo(U);
418193323Sed
419193323Sed        if (ArgNo >= F->getFunctionType()->getNumParams())
420193323Sed          // The value is passed in through a vararg! Must be live.
421193323Sed          return Live;
422193323Sed
423206083Srdivacky        assert(CS.getArgument(ArgNo)
424206083Srdivacky               == CS->getOperand(U.getOperandNo())
425193323Sed               && "Argument is not where we expected it");
426193323Sed
427193323Sed        // Value passed to a normal call. It's only live when the corresponding
428193323Sed        // argument to the called function turns out live.
429193323Sed        RetOrArg Use = CreateArg(F, ArgNo);
430193323Sed        return MarkIfNotLive(Use, MaybeLiveUses);
431193323Sed      }
432193323Sed    }
433193323Sed    // Used in any other way? Value must be live.
434193323Sed    return Live;
435193323Sed}
436193323Sed
437193323Sed/// SurveyUses - This looks at all the uses of the given value
438193323Sed/// Returns the Liveness deduced from the uses of this value.
439193323Sed///
440193323Sed/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
441193323Sed/// the result is Live, MaybeLiveUses might be modified but its content should
442193323Sed/// be ignored (since it might not be complete).
443206083SrdivackyDAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
444193323Sed  // Assume it's dead (which will only hold if there are no uses at all..).
445193323Sed  Liveness Result = MaybeLive;
446193323Sed  // Check each use.
447206083Srdivacky  for (Value::const_use_iterator I = V->use_begin(),
448193323Sed       E = V->use_end(); I != E; ++I) {
449193323Sed    Result = SurveyUse(I, MaybeLiveUses);
450193323Sed    if (Result == Live)
451193323Sed      break;
452193323Sed  }
453193323Sed  return Result;
454193323Sed}
455193323Sed
456193323Sed// SurveyFunction - This performs the initial survey of the specified function,
457193323Sed// checking out whether or not it uses any of its incoming arguments or whether
458193323Sed// any callers use the return value.  This fills in the LiveValues set and Uses
459193323Sed// map.
460193323Sed//
461193323Sed// We consider arguments of non-internal functions to be intrinsically alive as
462193323Sed// well as arguments to functions which have their "address taken".
463193323Sed//
464206083Srdivackyvoid DAE::SurveyFunction(const Function &F) {
465193323Sed  unsigned RetCount = NumRetVals(&F);
466193323Sed  // Assume all return values are dead
467193323Sed  typedef SmallVector<Liveness, 5> RetVals;
468193323Sed  RetVals RetValLiveness(RetCount, MaybeLive);
469193323Sed
470193323Sed  typedef SmallVector<UseVector, 5> RetUses;
471193323Sed  // These vectors map each return value to the uses that make it MaybeLive, so
472193323Sed  // we can add those to the Uses map if the return value really turns out to be
473193323Sed  // MaybeLive. Initialized to a list of RetCount empty lists.
474193323Sed  RetUses MaybeLiveRetUses(RetCount);
475193323Sed
476206083Srdivacky  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
477206083Srdivacky    if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
478193323Sed      if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
479193323Sed          != F.getFunctionType()->getReturnType()) {
480193323Sed        // We don't support old style multiple return values.
481193323Sed        MarkLive(F);
482193323Sed        return;
483193323Sed      }
484193323Sed
485193323Sed  if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
486193323Sed    MarkLive(F);
487193323Sed    return;
488193323Sed  }
489193323Sed
490202375Srdivacky  DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
491193323Sed  // Keep track of the number of live retvals, so we can skip checks once all
492193323Sed  // of them turn out to be live.
493193323Sed  unsigned NumLiveRetVals = 0;
494193323Sed  const Type *STy = dyn_cast<StructType>(F.getReturnType());
495193323Sed  // Loop all uses of the function.
496206083Srdivacky  for (Value::const_use_iterator I = F.use_begin(), E = F.use_end();
497206083Srdivacky       I != E; ++I) {
498193323Sed    // If the function is PASSED IN as an argument, its address has been
499193323Sed    // taken.
500206083Srdivacky    ImmutableCallSite CS(*I);
501206083Srdivacky    if (!CS || !CS.isCallee(I)) {
502193323Sed      MarkLive(F);
503193323Sed      return;
504193323Sed    }
505193323Sed
506193323Sed    // If this use is anything other than a call site, the function is alive.
507206083Srdivacky    const Instruction *TheCall = CS.getInstruction();
508193323Sed    if (!TheCall) {   // Not a direct call site?
509193323Sed      MarkLive(F);
510193323Sed      return;
511193323Sed    }
512193323Sed
513193323Sed    // If we end up here, we are looking at a direct call to our function.
514193323Sed
515193323Sed    // Now, check how our return value(s) is/are used in this caller. Don't
516193323Sed    // bother checking return values if all of them are live already.
517193323Sed    if (NumLiveRetVals != RetCount) {
518193323Sed      if (STy) {
519193323Sed        // Check all uses of the return value.
520206083Srdivacky        for (Value::const_use_iterator I = TheCall->use_begin(),
521193323Sed             E = TheCall->use_end(); I != E; ++I) {
522206083Srdivacky          const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
523193323Sed          if (Ext && Ext->hasIndices()) {
524193323Sed            // This use uses a part of our return value, survey the uses of
525193323Sed            // that part and store the results for this index only.
526193323Sed            unsigned Idx = *Ext->idx_begin();
527193323Sed            if (RetValLiveness[Idx] != Live) {
528193323Sed              RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
529193323Sed              if (RetValLiveness[Idx] == Live)
530193323Sed                NumLiveRetVals++;
531193323Sed            }
532193323Sed          } else {
533193323Sed            // Used by something else than extractvalue. Mark all return
534193323Sed            // values as live.
535193323Sed            for (unsigned i = 0; i != RetCount; ++i )
536193323Sed              RetValLiveness[i] = Live;
537193323Sed            NumLiveRetVals = RetCount;
538193323Sed            break;
539193323Sed          }
540193323Sed        }
541193323Sed      } else {
542193323Sed        // Single return value
543193323Sed        RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
544193323Sed        if (RetValLiveness[0] == Live)
545193323Sed          NumLiveRetVals = RetCount;
546193323Sed      }
547193323Sed    }
548193323Sed  }
549193323Sed
550193323Sed  // Now we've inspected all callers, record the liveness of our return values.
551193323Sed  for (unsigned i = 0; i != RetCount; ++i)
552193323Sed    MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
553193323Sed
554202375Srdivacky  DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
555193323Sed
556193323Sed  // Now, check all of our arguments.
557193323Sed  unsigned i = 0;
558193323Sed  UseVector MaybeLiveArgUses;
559206083Srdivacky  for (Function::const_arg_iterator AI = F.arg_begin(),
560193323Sed       E = F.arg_end(); AI != E; ++AI, ++i) {
561193323Sed    // See what the effect of this use is (recording any uses that cause
562193323Sed    // MaybeLive in MaybeLiveArgUses).
563193323Sed    Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
564193323Sed    // Mark the result.
565193323Sed    MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
566193323Sed    // Clear the vector again for the next iteration.
567193323Sed    MaybeLiveArgUses.clear();
568193323Sed  }
569193323Sed}
570193323Sed
571193323Sed/// MarkValue - This function marks the liveness of RA depending on L. If L is
572193323Sed/// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
573193323Sed/// such that RA will be marked live if any use in MaybeLiveUses gets marked
574193323Sed/// live later on.
575193323Sedvoid DAE::MarkValue(const RetOrArg &RA, Liveness L,
576193323Sed                    const UseVector &MaybeLiveUses) {
577193323Sed  switch (L) {
578193323Sed    case Live: MarkLive(RA); break;
579193323Sed    case MaybeLive:
580193323Sed    {
581193323Sed      // Note any uses of this value, so this return value can be
582193323Sed      // marked live whenever one of the uses becomes live.
583193323Sed      for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
584193323Sed           UE = MaybeLiveUses.end(); UI != UE; ++UI)
585193323Sed        Uses.insert(std::make_pair(*UI, RA));
586193323Sed      break;
587193323Sed    }
588193323Sed  }
589193323Sed}
590193323Sed
591193323Sed/// MarkLive - Mark the given Function as alive, meaning that it cannot be
592193323Sed/// changed in any way. Additionally,
593193323Sed/// mark any values that are used as this function's parameters or by its return
594193323Sed/// values (according to Uses) live as well.
595193323Sedvoid DAE::MarkLive(const Function &F) {
596202375Srdivacky  DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
597208599Srdivacky  // Mark the function as live.
598208599Srdivacky  LiveFunctions.insert(&F);
599208599Srdivacky  // Mark all arguments as live.
600208599Srdivacky  for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
601208599Srdivacky    PropagateLiveness(CreateArg(&F, i));
602208599Srdivacky  // Mark all return values as live.
603208599Srdivacky  for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
604208599Srdivacky    PropagateLiveness(CreateRet(&F, i));
605193323Sed}
606193323Sed
607193323Sed/// MarkLive - Mark the given return value or argument as live. Additionally,
608193323Sed/// mark any values that are used by this value (according to Uses) live as
609193323Sed/// well.
610193323Sedvoid DAE::MarkLive(const RetOrArg &RA) {
611193323Sed  if (LiveFunctions.count(RA.F))
612193323Sed    return; // Function was already marked Live.
613193323Sed
614193323Sed  if (!LiveValues.insert(RA).second)
615193323Sed    return; // We were already marked Live.
616193323Sed
617202375Srdivacky  DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
618193323Sed  PropagateLiveness(RA);
619193323Sed}
620193323Sed
621193323Sed/// PropagateLiveness - Given that RA is a live value, propagate it's liveness
622193323Sed/// to any other values it uses (according to Uses).
623193323Sedvoid DAE::PropagateLiveness(const RetOrArg &RA) {
624193323Sed  // We don't use upper_bound (or equal_range) here, because our recursive call
625193323Sed  // to ourselves is likely to cause the upper_bound (which is the first value
626193323Sed  // not belonging to RA) to become erased and the iterator invalidated.
627193323Sed  UseMap::iterator Begin = Uses.lower_bound(RA);
628193323Sed  UseMap::iterator E = Uses.end();
629193323Sed  UseMap::iterator I;
630193323Sed  for (I = Begin; I != E && I->first == RA; ++I)
631193323Sed    MarkLive(I->second);
632193323Sed
633193323Sed  // Erase RA from the Uses map (from the lower bound to wherever we ended up
634193323Sed  // after the loop).
635193323Sed  Uses.erase(Begin, I);
636193323Sed}
637193323Sed
638193323Sed// RemoveDeadStuffFromFunction - Remove any arguments and return values from F
639193323Sed// that are not in LiveValues. Transform the function and all of the callees of
640193323Sed// the function to not have these arguments and return values.
641193323Sed//
642193323Sedbool DAE::RemoveDeadStuffFromFunction(Function *F) {
643193323Sed  // Don't modify fully live functions
644193323Sed  if (LiveFunctions.count(F))
645193323Sed    return false;
646193323Sed
647193323Sed  // Start by computing a new prototype for the function, which is the same as
648193323Sed  // the old function, but has fewer arguments and a different return type.
649193323Sed  const FunctionType *FTy = F->getFunctionType();
650193323Sed  std::vector<const Type*> Params;
651193323Sed
652193323Sed  // Set up to build a new list of parameter attributes.
653193323Sed  SmallVector<AttributeWithIndex, 8> AttributesVec;
654193323Sed  const AttrListPtr &PAL = F->getAttributes();
655193323Sed
656193323Sed  // The existing function return attributes.
657193323Sed  Attributes RAttrs = PAL.getRetAttributes();
658193323Sed  Attributes FnAttrs = PAL.getFnAttributes();
659193323Sed
660193323Sed  // Find out the new return value.
661193323Sed
662193323Sed  const Type *RetTy = FTy->getReturnType();
663193323Sed  const Type *NRetTy = NULL;
664193323Sed  unsigned RetCount = NumRetVals(F);
665206083Srdivacky
666193323Sed  // -1 means unused, other numbers are the new index
667193323Sed  SmallVector<int, 5> NewRetIdxs(RetCount, -1);
668193323Sed  std::vector<const Type*> RetTypes;
669206083Srdivacky  if (RetTy->isVoidTy()) {
670206083Srdivacky    NRetTy = RetTy;
671193323Sed  } else {
672193323Sed    const StructType *STy = dyn_cast<StructType>(RetTy);
673193323Sed    if (STy)
674193323Sed      // Look at each of the original return values individually.
675193323Sed      for (unsigned i = 0; i != RetCount; ++i) {
676193323Sed        RetOrArg Ret = CreateRet(F, i);
677193323Sed        if (LiveValues.erase(Ret)) {
678193323Sed          RetTypes.push_back(STy->getElementType(i));
679193323Sed          NewRetIdxs[i] = RetTypes.size() - 1;
680193323Sed        } else {
681193323Sed          ++NumRetValsEliminated;
682202375Srdivacky          DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
683198090Srdivacky                << F->getName() << "\n");
684193323Sed        }
685193323Sed      }
686193323Sed    else
687193323Sed      // We used to return a single value.
688193323Sed      if (LiveValues.erase(CreateRet(F, 0))) {
689193323Sed        RetTypes.push_back(RetTy);
690193323Sed        NewRetIdxs[0] = 0;
691193323Sed      } else {
692202375Srdivacky        DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
693198090Srdivacky              << "\n");
694193323Sed        ++NumRetValsEliminated;
695193323Sed      }
696193323Sed    if (RetTypes.size() > 1)
697193323Sed      // More than one return type? Return a struct with them. Also, if we used
698193323Sed      // to return a struct and didn't change the number of return values,
699193323Sed      // return a struct again. This prevents changing {something} into
700193323Sed      // something and {} into void.
701193323Sed      // Make the new struct packed if we used to return a packed struct
702193323Sed      // already.
703198090Srdivacky      NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
704193323Sed    else if (RetTypes.size() == 1)
705193323Sed      // One return type? Just a simple value then, but only if we didn't use to
706193323Sed      // return a struct with that simple value before.
707193323Sed      NRetTy = RetTypes.front();
708193323Sed    else if (RetTypes.size() == 0)
709193323Sed      // No return types? Make it void, but only if we didn't use to return {}.
710198090Srdivacky      NRetTy = Type::getVoidTy(F->getContext());
711193323Sed  }
712193323Sed
713193323Sed  assert(NRetTy && "No new return type found?");
714193323Sed
715193323Sed  // Remove any incompatible attributes, but only if we removed all return
716193323Sed  // values. Otherwise, ensure that we don't have any conflicting attributes
717193323Sed  // here. Currently, this should not be possible, but special handling might be
718193323Sed  // required when new return value attributes are added.
719206083Srdivacky  if (NRetTy->isVoidTy())
720193323Sed    RAttrs &= ~Attribute::typeIncompatible(NRetTy);
721193323Sed  else
722206083Srdivacky    assert((RAttrs & Attribute::typeIncompatible(NRetTy)) == 0
723193323Sed           && "Return attributes no longer compatible?");
724193323Sed
725193323Sed  if (RAttrs)
726193323Sed    AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
727193323Sed
728193323Sed  // Remember which arguments are still alive.
729193323Sed  SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
730193323Sed  // Construct the new parameter list from non-dead arguments. Also construct
731193323Sed  // a new set of parameter attributes to correspond. Skip the first parameter
732193323Sed  // attribute, since that belongs to the return value.
733193323Sed  unsigned i = 0;
734193323Sed  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
735193323Sed       I != E; ++I, ++i) {
736193323Sed    RetOrArg Arg = CreateArg(F, i);
737193323Sed    if (LiveValues.erase(Arg)) {
738193323Sed      Params.push_back(I->getType());
739193323Sed      ArgAlive[i] = true;
740193323Sed
741193323Sed      // Get the original parameter attributes (skipping the first one, that is
742193323Sed      // for the return value.
743193323Sed      if (Attributes Attrs = PAL.getParamAttributes(i + 1))
744193323Sed        AttributesVec.push_back(AttributeWithIndex::get(Params.size(), Attrs));
745193323Sed    } else {
746193323Sed      ++NumArgumentsEliminated;
747202375Srdivacky      DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
748198090Srdivacky            << ") from " << F->getName() << "\n");
749193323Sed    }
750193323Sed  }
751193323Sed
752206083Srdivacky  if (FnAttrs != Attribute::None)
753193323Sed    AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
754193323Sed
755193323Sed  // Reconstruct the AttributesList based on the vector we constructed.
756206083Srdivacky  AttrListPtr NewPAL = AttrListPtr::get(AttributesVec.begin(),
757206083Srdivacky                                        AttributesVec.end());
758193323Sed
759193323Sed  // Create the new function type based on the recomputed parameters.
760206083Srdivacky  FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
761193323Sed
762193323Sed  // No change?
763193323Sed  if (NFTy == FTy)
764193323Sed    return false;
765193323Sed
766193323Sed  // Create the new function body and insert it into the module...
767193323Sed  Function *NF = Function::Create(NFTy, F->getLinkage());
768193323Sed  NF->copyAttributesFrom(F);
769193323Sed  NF->setAttributes(NewPAL);
770193323Sed  // Insert the new function before the old function, so we won't be processing
771193323Sed  // it again.
772193323Sed  F->getParent()->getFunctionList().insert(F, NF);
773193323Sed  NF->takeName(F);
774193323Sed
775193323Sed  // Loop over all of the callers of the function, transforming the call sites
776193323Sed  // to pass in a smaller number of arguments into the new function.
777193323Sed  //
778193323Sed  std::vector<Value*> Args;
779193323Sed  while (!F->use_empty()) {
780212904Sdim    CallSite CS(F->use_back());
781193323Sed    Instruction *Call = CS.getInstruction();
782193323Sed
783193323Sed    AttributesVec.clear();
784193323Sed    const AttrListPtr &CallPAL = CS.getAttributes();
785193323Sed
786193323Sed    // The call return attributes.
787193323Sed    Attributes RAttrs = CallPAL.getRetAttributes();
788193323Sed    Attributes FnAttrs = CallPAL.getFnAttributes();
789193323Sed    // Adjust in case the function was changed to return void.
790193323Sed    RAttrs &= ~Attribute::typeIncompatible(NF->getReturnType());
791193323Sed    if (RAttrs)
792193323Sed      AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
793193323Sed
794193323Sed    // Declare these outside of the loops, so we can reuse them for the second
795193323Sed    // loop, which loops the varargs.
796193323Sed    CallSite::arg_iterator I = CS.arg_begin();
797193323Sed    unsigned i = 0;
798193323Sed    // Loop over those operands, corresponding to the normal arguments to the
799193323Sed    // original function, and add those that are still alive.
800193323Sed    for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
801193323Sed      if (ArgAlive[i]) {
802193323Sed        Args.push_back(*I);
803193323Sed        // Get original parameter attributes, but skip return attributes.
804193323Sed        if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
805193323Sed          AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
806193323Sed      }
807193323Sed
808193323Sed    // Push any varargs arguments on the list. Don't forget their attributes.
809193323Sed    for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
810193323Sed      Args.push_back(*I);
811193323Sed      if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
812193323Sed        AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
813193323Sed    }
814193323Sed
815193323Sed    if (FnAttrs != Attribute::None)
816193323Sed      AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
817193323Sed
818193323Sed    // Reconstruct the AttributesList based on the vector we constructed.
819193323Sed    AttrListPtr NewCallPAL = AttrListPtr::get(AttributesVec.begin(),
820193323Sed                                              AttributesVec.end());
821193323Sed
822193323Sed    Instruction *New;
823193323Sed    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
824193323Sed      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
825193323Sed                               Args.begin(), Args.end(), "", Call);
826193323Sed      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
827193323Sed      cast<InvokeInst>(New)->setAttributes(NewCallPAL);
828193323Sed    } else {
829193323Sed      New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
830193323Sed      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
831193323Sed      cast<CallInst>(New)->setAttributes(NewCallPAL);
832193323Sed      if (cast<CallInst>(Call)->isTailCall())
833193323Sed        cast<CallInst>(New)->setTailCall();
834193323Sed    }
835212904Sdim    New->setDebugLoc(Call->getDebugLoc());
836207618Srdivacky
837193323Sed    Args.clear();
838193323Sed
839193323Sed    if (!Call->use_empty()) {
840193323Sed      if (New->getType() == Call->getType()) {
841193323Sed        // Return type not changed? Just replace users then.
842193323Sed        Call->replaceAllUsesWith(New);
843193323Sed        New->takeName(Call);
844206083Srdivacky      } else if (New->getType()->isVoidTy()) {
845193323Sed        // Our return value has uses, but they will get removed later on.
846193323Sed        // Replace by null for now.
847218893Sdim        if (!Call->getType()->isX86_MMXTy())
848218893Sdim          Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
849193323Sed      } else {
850204642Srdivacky        assert(RetTy->isStructTy() &&
851193323Sed               "Return type changed, but not into a void. The old return type"
852193323Sed               " must have been a struct!");
853193323Sed        Instruction *InsertPt = Call;
854193323Sed        if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
855193323Sed          BasicBlock::iterator IP = II->getNormalDest()->begin();
856193323Sed          while (isa<PHINode>(IP)) ++IP;
857193323Sed          InsertPt = IP;
858193323Sed        }
859206083Srdivacky
860193323Sed        // We used to return a struct. Instead of doing smart stuff with all the
861193323Sed        // uses of this struct, we will just rebuild it using
862193323Sed        // extract/insertvalue chaining and let instcombine clean that up.
863193323Sed        //
864193323Sed        // Start out building up our return value from undef
865198090Srdivacky        Value *RetVal = UndefValue::get(RetTy);
866193323Sed        for (unsigned i = 0; i != RetCount; ++i)
867193323Sed          if (NewRetIdxs[i] != -1) {
868193323Sed            Value *V;
869193323Sed            if (RetTypes.size() > 1)
870193323Sed              // We are still returning a struct, so extract the value from our
871193323Sed              // return value
872193323Sed              V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
873193323Sed                                           InsertPt);
874193323Sed            else
875193323Sed              // We are now returning a single element, so just insert that
876193323Sed              V = New;
877193323Sed            // Insert the value at the old position
878193323Sed            RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
879193323Sed          }
880193323Sed        // Now, replace all uses of the old call instruction with the return
881193323Sed        // struct we built
882193323Sed        Call->replaceAllUsesWith(RetVal);
883193323Sed        New->takeName(Call);
884193323Sed      }
885193323Sed    }
886193323Sed
887193323Sed    // Finally, remove the old call from the program, reducing the use-count of
888193323Sed    // F.
889193323Sed    Call->eraseFromParent();
890193323Sed  }
891193323Sed
892193323Sed  // Since we have now created the new function, splice the body of the old
893193323Sed  // function right into the new function, leaving the old rotting hulk of the
894193323Sed  // function empty.
895193323Sed  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
896193323Sed
897221345Sdim  // Loop over the argument list, transferring uses of the old arguments over to
898221345Sdim  // the new arguments, also transferring over the names as well.
899193323Sed  i = 0;
900193323Sed  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
901193323Sed       I2 = NF->arg_begin(); I != E; ++I, ++i)
902193323Sed    if (ArgAlive[i]) {
903193323Sed      // If this is a live argument, move the name and users over to the new
904193323Sed      // version.
905193323Sed      I->replaceAllUsesWith(I2);
906193323Sed      I2->takeName(I);
907193323Sed      ++I2;
908193323Sed    } else {
909193323Sed      // If this argument is dead, replace any uses of it with null constants
910193323Sed      // (these are guaranteed to become unused later on).
911218893Sdim      if (!I->getType()->isX86_MMXTy())
912218893Sdim        I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
913193323Sed    }
914193323Sed
915193323Sed  // If we change the return value of the function we must rewrite any return
916193323Sed  // instructions.  Check this now.
917193323Sed  if (F->getReturnType() != NF->getReturnType())
918193323Sed    for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
919193323Sed      if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
920193323Sed        Value *RetVal;
921193323Sed
922208599Srdivacky        if (NFTy->getReturnType()->isVoidTy()) {
923193323Sed          RetVal = 0;
924193323Sed        } else {
925204642Srdivacky          assert (RetTy->isStructTy());
926193323Sed          // The original return value was a struct, insert
927193323Sed          // extractvalue/insertvalue chains to extract only the values we need
928193323Sed          // to return and insert them into our new result.
929193323Sed          // This does generate messy code, but we'll let it to instcombine to
930193323Sed          // clean that up.
931193323Sed          Value *OldRet = RI->getOperand(0);
932193323Sed          // Start out building up our return value from undef
933198090Srdivacky          RetVal = UndefValue::get(NRetTy);
934193323Sed          for (unsigned i = 0; i != RetCount; ++i)
935193323Sed            if (NewRetIdxs[i] != -1) {
936193323Sed              ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
937193323Sed                                                              "oldret", RI);
938193323Sed              if (RetTypes.size() > 1) {
939193323Sed                // We're still returning a struct, so reinsert the value into
940193323Sed                // our new return value at the new index
941193323Sed
942193323Sed                RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
943193323Sed                                                 "newret", RI);
944193323Sed              } else {
945193323Sed                // We are now only returning a simple value, so just return the
946193323Sed                // extracted value.
947193323Sed                RetVal = EV;
948193323Sed              }
949193323Sed            }
950193323Sed        }
951193323Sed        // Replace the return instruction with one returning the new return
952193323Sed        // value (possibly 0 if we became void).
953198090Srdivacky        ReturnInst::Create(F->getContext(), RetVal, RI);
954193323Sed        BB->getInstList().erase(RI);
955193323Sed      }
956193323Sed
957193323Sed  // Now that the old function is dead, delete it.
958193323Sed  F->eraseFromParent();
959193323Sed
960193323Sed  return true;
961193323Sed}
962193323Sed
963193323Sedbool DAE::runOnModule(Module &M) {
964193323Sed  bool Changed = false;
965193323Sed
966193323Sed  // First pass: Do a simple check to see if any functions can have their "..."
967193323Sed  // removed.  We can do this if they never call va_start.  This loop cannot be
968193323Sed  // fused with the next loop, because deleting a function invalidates
969193323Sed  // information computed while surveying other functions.
970202375Srdivacky  DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
971193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
972193323Sed    Function &F = *I++;
973193323Sed    if (F.getFunctionType()->isVarArg())
974193323Sed      Changed |= DeleteDeadVarargs(F);
975193323Sed  }
976193323Sed
977193323Sed  // Second phase:loop through the module, determining which arguments are live.
978193323Sed  // We assume all arguments are dead unless proven otherwise (allowing us to
979193323Sed  // determine that dead arguments passed into recursive functions are dead).
980193323Sed  //
981202375Srdivacky  DEBUG(dbgs() << "DAE - Determining liveness\n");
982193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
983193323Sed    SurveyFunction(*I);
984206083Srdivacky
985193323Sed  // Now, remove all dead arguments and return values from each function in
986206083Srdivacky  // turn.
987193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
988206083Srdivacky    // Increment now, because the function will probably get removed (ie.
989193323Sed    // replaced by a new one).
990193323Sed    Function *F = I++;
991193323Sed    Changed |= RemoveDeadStuffFromFunction(F);
992193323Sed  }
993218893Sdim
994218893Sdim  // Finally, look for any unused parameters in functions with non-local
995218893Sdim  // linkage and replace the passed in parameters with undef.
996218893Sdim  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
997218893Sdim    Function& F = *I;
998218893Sdim
999218893Sdim    Changed |= RemoveDeadArgumentsFromCallers(F);
1000218893Sdim  }
1001218893Sdim
1002193323Sed  return Changed;
1003193323Sed}
1004