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"
22252723Sdim#include "llvm/ADT/DenseMap.h"
23252723Sdim#include "llvm/ADT/SmallVector.h"
24252723Sdim#include "llvm/ADT/Statistic.h"
25252723Sdim#include "llvm/ADT/StringExtras.h"
26252723Sdim#include "llvm/DIBuilder.h"
27245431Sdim#include "llvm/DebugInfo.h"
28252723Sdim#include "llvm/IR/CallingConv.h"
29252723Sdim#include "llvm/IR/Constant.h"
30252723Sdim#include "llvm/IR/DerivedTypes.h"
31252723Sdim#include "llvm/IR/Instructions.h"
32252723Sdim#include "llvm/IR/IntrinsicInst.h"
33252723Sdim#include "llvm/IR/LLVMContext.h"
34252723Sdim#include "llvm/IR/Module.h"
35193323Sed#include "llvm/Pass.h"
36193323Sed#include "llvm/Support/CallSite.h"
37193323Sed#include "llvm/Support/Debug.h"
38198090Srdivacky#include "llvm/Support/raw_ostream.h"
39193323Sed#include <map>
40193323Sed#include <set>
41193323Sedusing namespace llvm;
42193323Sed
43193323SedSTATISTIC(NumArgumentsEliminated, "Number of unread args removed");
44193323SedSTATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
45218893SdimSTATISTIC(NumArgumentsReplacedWithUndef,
46218893Sdim          "Number of unread args replaced with undef");
47193323Sednamespace {
48193323Sed  /// DAE - The dead argument elimination pass.
49193323Sed  ///
50198892Srdivacky  class DAE : public ModulePass {
51193323Sed  public:
52193323Sed
53193323Sed    /// Struct that represents (part of) either a return value or a function
54193323Sed    /// argument.  Used so that arguments and return values can be used
55221345Sdim    /// interchangeably.
56193323Sed    struct RetOrArg {
57206083Srdivacky      RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
58193323Sed               IsArg(IsArg) {}
59193323Sed      const Function *F;
60193323Sed      unsigned Idx;
61193323Sed      bool IsArg;
62193323Sed
63193323Sed      /// Make RetOrArg comparable, so we can put it into a map.
64193323Sed      bool operator<(const RetOrArg &O) const {
65193323Sed        if (F != O.F)
66193323Sed          return F < O.F;
67193323Sed        else if (Idx != O.Idx)
68193323Sed          return Idx < O.Idx;
69193323Sed        else
70193323Sed          return IsArg < O.IsArg;
71193323Sed      }
72193323Sed
73193323Sed      /// Make RetOrArg comparable, so we can easily iterate the multimap.
74193323Sed      bool operator==(const RetOrArg &O) const {
75193323Sed        return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
76193323Sed      }
77193323Sed
78193323Sed      std::string getDescription() const {
79206083Srdivacky        return std::string((IsArg ? "Argument #" : "Return value #"))
80235633Sdim               + utostr(Idx) + " of function " + F->getName().str();
81193323Sed      }
82193323Sed    };
83193323Sed
84193323Sed    /// Liveness enum - During our initial pass over the program, we determine
85193323Sed    /// that things are either alive or maybe alive. We don't mark anything
86193323Sed    /// explicitly dead (even if we know they are), since anything not alive
87193323Sed    /// with no registered uses (in Uses) will never be marked alive and will
88193323Sed    /// thus become dead in the end.
89193323Sed    enum Liveness { Live, MaybeLive };
90193323Sed
91193323Sed    /// Convenience wrapper
92193323Sed    RetOrArg CreateRet(const Function *F, unsigned Idx) {
93193323Sed      return RetOrArg(F, Idx, false);
94193323Sed    }
95193323Sed    /// Convenience wrapper
96193323Sed    RetOrArg CreateArg(const Function *F, unsigned Idx) {
97193323Sed      return RetOrArg(F, Idx, true);
98193323Sed    }
99193323Sed
100193323Sed    typedef std::multimap<RetOrArg, RetOrArg> UseMap;
101193323Sed    /// This maps a return value or argument to any MaybeLive return values or
102193323Sed    /// arguments it uses. This allows the MaybeLive values to be marked live
103193323Sed    /// when any of its users is marked live.
104193323Sed    /// For example (indices are left out for clarity):
105193323Sed    ///  - Uses[ret F] = ret G
106193323Sed    ///    This means that F calls G, and F returns the value returned by G.
107193323Sed    ///  - Uses[arg F] = ret G
108193323Sed    ///    This means that some function calls G and passes its result as an
109193323Sed    ///    argument to F.
110193323Sed    ///  - Uses[ret F] = arg F
111193323Sed    ///    This means that F returns one of its own arguments.
112193323Sed    ///  - Uses[arg F] = arg G
113193323Sed    ///    This means that G calls F and passes one of its own (G's) arguments
114193323Sed    ///    directly to F.
115193323Sed    UseMap Uses;
116193323Sed
117193323Sed    typedef std::set<RetOrArg> LiveSet;
118193323Sed    typedef std::set<const Function*> LiveFuncSet;
119193323Sed
120193323Sed    /// This set contains all values that have been determined to be live.
121193323Sed    LiveSet LiveValues;
122193323Sed    /// This set contains all values that are cannot be changed in any way.
123193323Sed    LiveFuncSet LiveFunctions;
124193323Sed
125193323Sed    typedef SmallVector<RetOrArg, 5> UseVector;
126193323Sed
127245431Sdim    // Map each LLVM function to corresponding metadata with debug info. If
128245431Sdim    // the function is replaced with another one, we should patch the pointer
129245431Sdim    // to LLVM function in metadata.
130245431Sdim    // As the code generation for module is finished (and DIBuilder is
131245431Sdim    // finalized) we assume that subprogram descriptors won't be changed, and
132245431Sdim    // they are stored in map for short duration anyway.
133245431Sdim    typedef DenseMap<Function*, DISubprogram> FunctionDIMap;
134245431Sdim    FunctionDIMap FunctionDIs;
135245431Sdim
136210299Sed  protected:
137210299Sed    // DAH uses this to specify a different ID.
138212904Sdim    explicit DAE(char &ID) : ModulePass(ID) {}
139210299Sed
140193323Sed  public:
141193323Sed    static char ID; // Pass identification, replacement for typeid
142218893Sdim    DAE() : ModulePass(ID) {
143218893Sdim      initializeDAEPass(*PassRegistry::getPassRegistry());
144218893Sdim    }
145210299Sed
146193323Sed    bool runOnModule(Module &M);
147193323Sed
148193323Sed    virtual bool ShouldHackArguments() const { return false; }
149193323Sed
150193323Sed  private:
151193323Sed    Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
152206083Srdivacky    Liveness SurveyUse(Value::const_use_iterator U, UseVector &MaybeLiveUses,
153193323Sed                       unsigned RetValNum = 0);
154206083Srdivacky    Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
155193323Sed
156245431Sdim    void CollectFunctionDIs(Module &M);
157206083Srdivacky    void SurveyFunction(const Function &F);
158193323Sed    void MarkValue(const RetOrArg &RA, Liveness L,
159193323Sed                   const UseVector &MaybeLiveUses);
160193323Sed    void MarkLive(const RetOrArg &RA);
161193323Sed    void MarkLive(const Function &F);
162193323Sed    void PropagateLiveness(const RetOrArg &RA);
163193323Sed    bool RemoveDeadStuffFromFunction(Function *F);
164193323Sed    bool DeleteDeadVarargs(Function &Fn);
165218893Sdim    bool RemoveDeadArgumentsFromCallers(Function &Fn);
166193323Sed  };
167193323Sed}
168193323Sed
169193323Sed
170193323Sedchar DAE::ID = 0;
171218893SdimINITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
172193323Sed
173193323Sednamespace {
174193323Sed  /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
175193323Sed  /// deletes arguments to functions which are external.  This is only for use
176193323Sed  /// by bugpoint.
177193323Sed  struct DAH : public DAE {
178193323Sed    static char ID;
179212904Sdim    DAH() : DAE(ID) {}
180210299Sed
181193323Sed    virtual bool ShouldHackArguments() const { return true; }
182193323Sed  };
183193323Sed}
184193323Sed
185193323Sedchar DAH::ID = 0;
186212904SdimINITIALIZE_PASS(DAH, "deadarghaX0r",
187212904Sdim                "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
188218893Sdim                false, false)
189193323Sed
190193323Sed/// createDeadArgEliminationPass - This pass removes arguments from functions
191193323Sed/// which are not used by the body of the function.
192193323Sed///
193193323SedModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
194193323SedModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
195193323Sed
196245431Sdim/// CollectFunctionDIs - Map each function in the module to its debug info
197245431Sdim/// descriptor.
198245431Sdimvoid DAE::CollectFunctionDIs(Module &M) {
199245431Sdim  FunctionDIs.clear();
200245431Sdim
201245431Sdim  for (Module::named_metadata_iterator I = M.named_metadata_begin(),
202245431Sdim       E = M.named_metadata_end(); I != E; ++I) {
203245431Sdim    NamedMDNode &NMD = *I;
204245431Sdim    for (unsigned MDIndex = 0, MDNum = NMD.getNumOperands();
205245431Sdim         MDIndex < MDNum; ++MDIndex) {
206245431Sdim      MDNode *Node = NMD.getOperand(MDIndex);
207245431Sdim      if (!DIDescriptor(Node).isCompileUnit())
208245431Sdim        continue;
209245431Sdim      DICompileUnit CU(Node);
210245431Sdim      const DIArray &SPs = CU.getSubprograms();
211245431Sdim      for (unsigned SPIndex = 0, SPNum = SPs.getNumElements();
212245431Sdim           SPIndex < SPNum; ++SPIndex) {
213245431Sdim        DISubprogram SP(SPs.getElement(SPIndex));
214263509Sdim        assert((!SP || SP.isSubprogram()) &&
215263509Sdim          "A MDNode in subprograms of a CU should be null or a DISubprogram.");
216263509Sdim        if (!SP)
217245431Sdim          continue;
218245431Sdim        if (Function *F = SP.getFunction())
219245431Sdim          FunctionDIs[F] = SP;
220245431Sdim      }
221245431Sdim    }
222245431Sdim  }
223245431Sdim}
224245431Sdim
225193323Sed/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
226193323Sed/// llvm.vastart is never called, the varargs list is dead for the function.
227193323Sedbool DAE::DeleteDeadVarargs(Function &Fn) {
228193323Sed  assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
229193323Sed  if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
230193323Sed
231193323Sed  // Ensure that the function is only directly called.
232194178Sed  if (Fn.hasAddressTaken())
233194178Sed    return false;
234193323Sed
235193323Sed  // Okay, we know we can transform this function if safe.  Scan its body
236193323Sed  // looking for calls to llvm.vastart.
237193323Sed  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
238193323Sed    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
239193323Sed      if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
240193323Sed        if (II->getIntrinsicID() == Intrinsic::vastart)
241193323Sed          return false;
242193323Sed      }
243193323Sed    }
244193323Sed  }
245193323Sed
246193323Sed  // If we get here, there are no calls to llvm.vastart in the function body,
247193323Sed  // remove the "..." and adjust all the calls.
248193323Sed
249193323Sed  // Start by computing a new prototype for the function, which is the same as
250193323Sed  // the old function, but doesn't have isVarArg set.
251226890Sdim  FunctionType *FTy = Fn.getFunctionType();
252206083Srdivacky
253224145Sdim  std::vector<Type*> Params(FTy->param_begin(), FTy->param_end());
254198090Srdivacky  FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
255198090Srdivacky                                                Params, false);
256193323Sed  unsigned NumArgs = Params.size();
257193323Sed
258193323Sed  // Create the new function body and insert it into the module...
259193323Sed  Function *NF = Function::Create(NFTy, Fn.getLinkage());
260193323Sed  NF->copyAttributesFrom(&Fn);
261193323Sed  Fn.getParent()->getFunctionList().insert(&Fn, NF);
262193323Sed  NF->takeName(&Fn);
263193323Sed
264193323Sed  // Loop over all of the callers of the function, transforming the call sites
265193323Sed  // to pass in a smaller number of arguments into the new function.
266193323Sed  //
267193323Sed  std::vector<Value*> Args;
268263509Sdim  for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ) {
269263509Sdim    CallSite CS(*I++);
270263509Sdim    if (!CS)
271263509Sdim      continue;
272193323Sed    Instruction *Call = CS.getInstruction();
273193323Sed
274193323Sed    // Pass all the same arguments.
275212904Sdim    Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
276193323Sed
277193323Sed    // Drop any attributes that were on the vararg arguments.
278252723Sdim    AttributeSet PAL = CS.getAttributes();
279252723Sdim    if (!PAL.isEmpty() && PAL.getSlotIndex(PAL.getNumSlots() - 1) > NumArgs) {
280252723Sdim      SmallVector<AttributeSet, 8> AttributesVec;
281252723Sdim      for (unsigned i = 0; PAL.getSlotIndex(i) <= NumArgs; ++i)
282252723Sdim        AttributesVec.push_back(PAL.getSlotAttributes(i));
283252723Sdim      if (PAL.hasAttributes(AttributeSet::FunctionIndex))
284252723Sdim        AttributesVec.push_back(AttributeSet::get(Fn.getContext(),
285252723Sdim                                                  PAL.getFnAttributes()));
286252723Sdim      PAL = AttributeSet::get(Fn.getContext(), AttributesVec);
287193323Sed    }
288193323Sed
289193323Sed    Instruction *New;
290193323Sed    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
291193323Sed      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
292224145Sdim                               Args, "", Call);
293193323Sed      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
294193323Sed      cast<InvokeInst>(New)->setAttributes(PAL);
295193323Sed    } else {
296224145Sdim      New = CallInst::Create(NF, Args, "", Call);
297193323Sed      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
298193323Sed      cast<CallInst>(New)->setAttributes(PAL);
299193323Sed      if (cast<CallInst>(Call)->isTailCall())
300193323Sed        cast<CallInst>(New)->setTailCall();
301193323Sed    }
302212904Sdim    New->setDebugLoc(Call->getDebugLoc());
303207618Srdivacky
304193323Sed    Args.clear();
305193323Sed
306193323Sed    if (!Call->use_empty())
307193323Sed      Call->replaceAllUsesWith(New);
308193323Sed
309193323Sed    New->takeName(Call);
310193323Sed
311193323Sed    // Finally, remove the old call from the program, reducing the use-count of
312193323Sed    // F.
313193323Sed    Call->eraseFromParent();
314193323Sed  }
315193323Sed
316193323Sed  // Since we have now created the new function, splice the body of the old
317193323Sed  // function right into the new function, leaving the old rotting hulk of the
318193323Sed  // function empty.
319193323Sed  NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
320193323Sed
321221345Sdim  // Loop over the argument list, transferring uses of the old arguments over to
322221345Sdim  // the new arguments, also transferring over the names as well.  While we're at
323193323Sed  // it, remove the dead arguments from the DeadArguments list.
324193323Sed  //
325193323Sed  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
326193323Sed       I2 = NF->arg_begin(); I != E; ++I, ++I2) {
327193323Sed    // Move the name and users over to the new version.
328193323Sed    I->replaceAllUsesWith(I2);
329193323Sed    I2->takeName(I);
330193323Sed  }
331193323Sed
332245431Sdim  // Patch the pointer to LLVM function in debug info descriptor.
333245431Sdim  FunctionDIMap::iterator DI = FunctionDIs.find(&Fn);
334245431Sdim  if (DI != FunctionDIs.end())
335245431Sdim    DI->second.replaceFunction(NF);
336245431Sdim
337263509Sdim  // Fix up any BlockAddresses that refer to the function.
338263509Sdim  Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType()));
339263509Sdim  // Delete the bitcast that we just created, so that NF does not
340263509Sdim  // appear to be address-taken.
341263509Sdim  NF->removeDeadConstantUsers();
342193323Sed  // Finally, nuke the old function.
343193323Sed  Fn.eraseFromParent();
344193323Sed  return true;
345193323Sed}
346193323Sed
347218893Sdim/// RemoveDeadArgumentsFromCallers - Checks if the given function has any
348218893Sdim/// arguments that are unused, and changes the caller parameters to be undefined
349218893Sdim/// instead.
350218893Sdimbool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
351218893Sdim{
352221345Sdim  if (Fn.isDeclaration() || Fn.mayBeOverridden())
353218893Sdim    return false;
354218893Sdim
355263509Sdim  // Functions with local linkage should already have been handled, except the
356263509Sdim  // fragile (variadic) ones which we can improve here.
357263509Sdim  if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg())
358218893Sdim    return false;
359218893Sdim
360263509Sdim  // If a function seen at compile time is not necessarily the one linked to
361263509Sdim  // the binary being built, it is illegal to change the actual arguments
362263509Sdim  // passed to it. These functions can be captured by isWeakForLinker().
363263509Sdim  // *NOTE* that mayBeOverridden() is insufficient for this purpose as it
364263509Sdim  // doesn't include linkage types like AvailableExternallyLinkage and
365263509Sdim  // LinkOnceODRLinkage. Take link_odr* as an example, it indicates a set of
366263509Sdim  // *EQUIVALENT* globals that can be merged at link-time. However, the
367263509Sdim  // semantic of *EQUIVALENT*-functions includes parameters. Changing
368263509Sdim  // parameters breaks this assumption.
369263509Sdim  //
370263509Sdim  if (Fn.isWeakForLinker())
371263509Sdim    return false;
372263509Sdim
373218893Sdim  if (Fn.use_empty())
374218893Sdim    return false;
375218893Sdim
376252723Sdim  SmallVector<unsigned, 8> UnusedArgs;
377218893Sdim  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
378218893Sdim       I != E; ++I) {
379218893Sdim    Argument *Arg = I;
380218893Sdim
381218893Sdim    if (Arg->use_empty() && !Arg->hasByValAttr())
382218893Sdim      UnusedArgs.push_back(Arg->getArgNo());
383218893Sdim  }
384218893Sdim
385218893Sdim  if (UnusedArgs.empty())
386218893Sdim    return false;
387218893Sdim
388218893Sdim  bool Changed = false;
389218893Sdim
390218893Sdim  for (Function::use_iterator I = Fn.use_begin(), E = Fn.use_end();
391218893Sdim       I != E; ++I) {
392218893Sdim    CallSite CS(*I);
393218893Sdim    if (!CS || !CS.isCallee(I))
394218893Sdim      continue;
395218893Sdim
396218893Sdim    // Now go through all unused args and replace them with "undef".
397218893Sdim    for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
398218893Sdim      unsigned ArgNo = UnusedArgs[I];
399218893Sdim
400218893Sdim      Value *Arg = CS.getArgument(ArgNo);
401218893Sdim      CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
402218893Sdim      ++NumArgumentsReplacedWithUndef;
403218893Sdim      Changed = true;
404218893Sdim    }
405218893Sdim  }
406218893Sdim
407218893Sdim  return Changed;
408218893Sdim}
409218893Sdim
410193323Sed/// Convenience function that returns the number of return values. It returns 0
411193323Sed/// for void functions and 1 for functions not returning a struct. It returns
412193323Sed/// the number of struct elements for functions returning a struct.
413193323Sedstatic unsigned NumRetVals(const Function *F) {
414206083Srdivacky  if (F->getReturnType()->isVoidTy())
415193323Sed    return 0;
416226890Sdim  else if (StructType *STy = dyn_cast<StructType>(F->getReturnType()))
417193323Sed    return STy->getNumElements();
418193323Sed  else
419193323Sed    return 1;
420193323Sed}
421193323Sed
422193323Sed/// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
423193323Sed/// live, it adds Use to the MaybeLiveUses argument. Returns the determined
424193323Sed/// liveness of Use.
425193323SedDAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
426193323Sed  // We're live if our use or its Function is already marked as live.
427193323Sed  if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
428193323Sed    return Live;
429193323Sed
430193323Sed  // We're maybe live otherwise, but remember that we must become live if
431193323Sed  // Use becomes live.
432193323Sed  MaybeLiveUses.push_back(Use);
433193323Sed  return MaybeLive;
434193323Sed}
435193323Sed
436193323Sed
437193323Sed/// SurveyUse - This looks at a single use of an argument or return value
438193323Sed/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
439206083Srdivacky/// if it causes the used value to become MaybeLive.
440193323Sed///
441193323Sed/// RetValNum is the return value number to use when this use is used in a
442193323Sed/// return instruction. This is used in the recursion, you should always leave
443193323Sed/// it at 0.
444206083SrdivackyDAE::Liveness DAE::SurveyUse(Value::const_use_iterator U,
445206083Srdivacky                             UseVector &MaybeLiveUses, unsigned RetValNum) {
446206083Srdivacky    const User *V = *U;
447206083Srdivacky    if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
448193323Sed      // The value is returned from a function. It's only live when the
449193323Sed      // function's return value is live. We use RetValNum here, for the case
450193323Sed      // that U is really a use of an insertvalue instruction that uses the
451221345Sdim      // original Use.
452193323Sed      RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
453193323Sed      // We might be live, depending on the liveness of Use.
454193323Sed      return MarkIfNotLive(Use, MaybeLiveUses);
455193323Sed    }
456206083Srdivacky    if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
457193323Sed      if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
458193323Sed          && IV->hasIndices())
459193323Sed        // The use we are examining is inserted into an aggregate. Our liveness
460193323Sed        // depends on all uses of that aggregate, but if it is used as a return
461193323Sed        // value, only index at which we were inserted counts.
462193323Sed        RetValNum = *IV->idx_begin();
463193323Sed
464193323Sed      // Note that if we are used as the aggregate operand to the insertvalue,
465193323Sed      // we don't change RetValNum, but do survey all our uses.
466193323Sed
467193323Sed      Liveness Result = MaybeLive;
468206083Srdivacky      for (Value::const_use_iterator I = IV->use_begin(),
469193323Sed           E = V->use_end(); I != E; ++I) {
470193323Sed        Result = SurveyUse(I, MaybeLiveUses, RetValNum);
471193323Sed        if (Result == Live)
472193323Sed          break;
473193323Sed      }
474193323Sed      return Result;
475193323Sed    }
476206083Srdivacky
477206083Srdivacky    if (ImmutableCallSite CS = V) {
478206083Srdivacky      const Function *F = CS.getCalledFunction();
479193323Sed      if (F) {
480193323Sed        // Used in a direct call.
481206083Srdivacky
482193323Sed        // Find the argument number. We know for sure that this use is an
483193323Sed        // argument, since if it was the function argument this would be an
484193323Sed        // indirect call and the we know can't be looking at a value of the
485193323Sed        // label type (for the invoke instruction).
486206083Srdivacky        unsigned ArgNo = CS.getArgumentNo(U);
487193323Sed
488193323Sed        if (ArgNo >= F->getFunctionType()->getNumParams())
489193323Sed          // The value is passed in through a vararg! Must be live.
490193323Sed          return Live;
491193323Sed
492206083Srdivacky        assert(CS.getArgument(ArgNo)
493206083Srdivacky               == CS->getOperand(U.getOperandNo())
494193323Sed               && "Argument is not where we expected it");
495193323Sed
496193323Sed        // Value passed to a normal call. It's only live when the corresponding
497193323Sed        // argument to the called function turns out live.
498193323Sed        RetOrArg Use = CreateArg(F, ArgNo);
499193323Sed        return MarkIfNotLive(Use, MaybeLiveUses);
500193323Sed      }
501193323Sed    }
502193323Sed    // Used in any other way? Value must be live.
503193323Sed    return Live;
504193323Sed}
505193323Sed
506193323Sed/// SurveyUses - This looks at all the uses of the given value
507193323Sed/// Returns the Liveness deduced from the uses of this value.
508193323Sed///
509193323Sed/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
510193323Sed/// the result is Live, MaybeLiveUses might be modified but its content should
511193323Sed/// be ignored (since it might not be complete).
512206083SrdivackyDAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
513193323Sed  // Assume it's dead (which will only hold if there are no uses at all..).
514193323Sed  Liveness Result = MaybeLive;
515193323Sed  // Check each use.
516206083Srdivacky  for (Value::const_use_iterator I = V->use_begin(),
517193323Sed       E = V->use_end(); I != E; ++I) {
518193323Sed    Result = SurveyUse(I, MaybeLiveUses);
519193323Sed    if (Result == Live)
520193323Sed      break;
521193323Sed  }
522193323Sed  return Result;
523193323Sed}
524193323Sed
525193323Sed// SurveyFunction - This performs the initial survey of the specified function,
526193323Sed// checking out whether or not it uses any of its incoming arguments or whether
527193323Sed// any callers use the return value.  This fills in the LiveValues set and Uses
528193323Sed// map.
529193323Sed//
530193323Sed// We consider arguments of non-internal functions to be intrinsically alive as
531193323Sed// well as arguments to functions which have their "address taken".
532193323Sed//
533206083Srdivackyvoid DAE::SurveyFunction(const Function &F) {
534193323Sed  unsigned RetCount = NumRetVals(&F);
535193323Sed  // Assume all return values are dead
536193323Sed  typedef SmallVector<Liveness, 5> RetVals;
537193323Sed  RetVals RetValLiveness(RetCount, MaybeLive);
538193323Sed
539193323Sed  typedef SmallVector<UseVector, 5> RetUses;
540193323Sed  // These vectors map each return value to the uses that make it MaybeLive, so
541193323Sed  // we can add those to the Uses map if the return value really turns out to be
542193323Sed  // MaybeLive. Initialized to a list of RetCount empty lists.
543193323Sed  RetUses MaybeLiveRetUses(RetCount);
544193323Sed
545206083Srdivacky  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
546206083Srdivacky    if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
547193323Sed      if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
548193323Sed          != F.getFunctionType()->getReturnType()) {
549193323Sed        // We don't support old style multiple return values.
550193323Sed        MarkLive(F);
551193323Sed        return;
552193323Sed      }
553193323Sed
554193323Sed  if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
555193323Sed    MarkLive(F);
556193323Sed    return;
557193323Sed  }
558193323Sed
559202375Srdivacky  DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
560193323Sed  // Keep track of the number of live retvals, so we can skip checks once all
561193323Sed  // of them turn out to be live.
562193323Sed  unsigned NumLiveRetVals = 0;
563226890Sdim  Type *STy = dyn_cast<StructType>(F.getReturnType());
564193323Sed  // Loop all uses of the function.
565206083Srdivacky  for (Value::const_use_iterator I = F.use_begin(), E = F.use_end();
566206083Srdivacky       I != E; ++I) {
567193323Sed    // If the function is PASSED IN as an argument, its address has been
568193323Sed    // taken.
569206083Srdivacky    ImmutableCallSite CS(*I);
570206083Srdivacky    if (!CS || !CS.isCallee(I)) {
571193323Sed      MarkLive(F);
572193323Sed      return;
573193323Sed    }
574193323Sed
575193323Sed    // If this use is anything other than a call site, the function is alive.
576206083Srdivacky    const Instruction *TheCall = CS.getInstruction();
577193323Sed    if (!TheCall) {   // Not a direct call site?
578193323Sed      MarkLive(F);
579193323Sed      return;
580193323Sed    }
581193323Sed
582193323Sed    // If we end up here, we are looking at a direct call to our function.
583193323Sed
584193323Sed    // Now, check how our return value(s) is/are used in this caller. Don't
585193323Sed    // bother checking return values if all of them are live already.
586193323Sed    if (NumLiveRetVals != RetCount) {
587193323Sed      if (STy) {
588193323Sed        // Check all uses of the return value.
589206083Srdivacky        for (Value::const_use_iterator I = TheCall->use_begin(),
590193323Sed             E = TheCall->use_end(); I != E; ++I) {
591206083Srdivacky          const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
592193323Sed          if (Ext && Ext->hasIndices()) {
593193323Sed            // This use uses a part of our return value, survey the uses of
594193323Sed            // that part and store the results for this index only.
595193323Sed            unsigned Idx = *Ext->idx_begin();
596193323Sed            if (RetValLiveness[Idx] != Live) {
597193323Sed              RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
598193323Sed              if (RetValLiveness[Idx] == Live)
599193323Sed                NumLiveRetVals++;
600193323Sed            }
601193323Sed          } else {
602193323Sed            // Used by something else than extractvalue. Mark all return
603193323Sed            // values as live.
604193323Sed            for (unsigned i = 0; i != RetCount; ++i )
605193323Sed              RetValLiveness[i] = Live;
606193323Sed            NumLiveRetVals = RetCount;
607193323Sed            break;
608193323Sed          }
609193323Sed        }
610193323Sed      } else {
611193323Sed        // Single return value
612193323Sed        RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
613193323Sed        if (RetValLiveness[0] == Live)
614193323Sed          NumLiveRetVals = RetCount;
615193323Sed      }
616193323Sed    }
617193323Sed  }
618193323Sed
619193323Sed  // Now we've inspected all callers, record the liveness of our return values.
620193323Sed  for (unsigned i = 0; i != RetCount; ++i)
621193323Sed    MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
622193323Sed
623202375Srdivacky  DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
624193323Sed
625193323Sed  // Now, check all of our arguments.
626193323Sed  unsigned i = 0;
627193323Sed  UseVector MaybeLiveArgUses;
628206083Srdivacky  for (Function::const_arg_iterator AI = F.arg_begin(),
629193323Sed       E = F.arg_end(); AI != E; ++AI, ++i) {
630263509Sdim    Liveness Result;
631263509Sdim    if (F.getFunctionType()->isVarArg()) {
632263509Sdim      // Variadic functions will already have a va_arg function expanded inside
633263509Sdim      // them, making them potentially very sensitive to ABI changes resulting
634263509Sdim      // from removing arguments entirely, so don't. For example AArch64 handles
635263509Sdim      // register and stack HFAs very differently, and this is reflected in the
636263509Sdim      // IR which has already been generated.
637263509Sdim      Result = Live;
638263509Sdim    } else {
639263509Sdim      // See what the effect of this use is (recording any uses that cause
640263509Sdim      // MaybeLive in MaybeLiveArgUses).
641263509Sdim      Result = SurveyUses(AI, MaybeLiveArgUses);
642263509Sdim    }
643263509Sdim
644193323Sed    // Mark the result.
645193323Sed    MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
646193323Sed    // Clear the vector again for the next iteration.
647193323Sed    MaybeLiveArgUses.clear();
648193323Sed  }
649193323Sed}
650193323Sed
651193323Sed/// MarkValue - This function marks the liveness of RA depending on L. If L is
652193323Sed/// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
653193323Sed/// such that RA will be marked live if any use in MaybeLiveUses gets marked
654193323Sed/// live later on.
655193323Sedvoid DAE::MarkValue(const RetOrArg &RA, Liveness L,
656193323Sed                    const UseVector &MaybeLiveUses) {
657193323Sed  switch (L) {
658193323Sed    case Live: MarkLive(RA); break;
659193323Sed    case MaybeLive:
660193323Sed    {
661193323Sed      // Note any uses of this value, so this return value can be
662193323Sed      // marked live whenever one of the uses becomes live.
663193323Sed      for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
664193323Sed           UE = MaybeLiveUses.end(); UI != UE; ++UI)
665193323Sed        Uses.insert(std::make_pair(*UI, RA));
666193323Sed      break;
667193323Sed    }
668193323Sed  }
669193323Sed}
670193323Sed
671193323Sed/// MarkLive - Mark the given Function as alive, meaning that it cannot be
672193323Sed/// changed in any way. Additionally,
673193323Sed/// mark any values that are used as this function's parameters or by its return
674193323Sed/// values (according to Uses) live as well.
675193323Sedvoid DAE::MarkLive(const Function &F) {
676202375Srdivacky  DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
677208599Srdivacky  // Mark the function as live.
678208599Srdivacky  LiveFunctions.insert(&F);
679208599Srdivacky  // Mark all arguments as live.
680208599Srdivacky  for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
681208599Srdivacky    PropagateLiveness(CreateArg(&F, i));
682208599Srdivacky  // Mark all return values as live.
683208599Srdivacky  for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
684208599Srdivacky    PropagateLiveness(CreateRet(&F, i));
685193323Sed}
686193323Sed
687193323Sed/// MarkLive - Mark the given return value or argument as live. Additionally,
688193323Sed/// mark any values that are used by this value (according to Uses) live as
689193323Sed/// well.
690193323Sedvoid DAE::MarkLive(const RetOrArg &RA) {
691193323Sed  if (LiveFunctions.count(RA.F))
692193323Sed    return; // Function was already marked Live.
693193323Sed
694193323Sed  if (!LiveValues.insert(RA).second)
695193323Sed    return; // We were already marked Live.
696193323Sed
697202375Srdivacky  DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
698193323Sed  PropagateLiveness(RA);
699193323Sed}
700193323Sed
701193323Sed/// PropagateLiveness - Given that RA is a live value, propagate it's liveness
702193323Sed/// to any other values it uses (according to Uses).
703193323Sedvoid DAE::PropagateLiveness(const RetOrArg &RA) {
704193323Sed  // We don't use upper_bound (or equal_range) here, because our recursive call
705193323Sed  // to ourselves is likely to cause the upper_bound (which is the first value
706193323Sed  // not belonging to RA) to become erased and the iterator invalidated.
707193323Sed  UseMap::iterator Begin = Uses.lower_bound(RA);
708193323Sed  UseMap::iterator E = Uses.end();
709193323Sed  UseMap::iterator I;
710193323Sed  for (I = Begin; I != E && I->first == RA; ++I)
711193323Sed    MarkLive(I->second);
712193323Sed
713193323Sed  // Erase RA from the Uses map (from the lower bound to wherever we ended up
714193323Sed  // after the loop).
715193323Sed  Uses.erase(Begin, I);
716193323Sed}
717193323Sed
718193323Sed// RemoveDeadStuffFromFunction - Remove any arguments and return values from F
719193323Sed// that are not in LiveValues. Transform the function and all of the callees of
720193323Sed// the function to not have these arguments and return values.
721193323Sed//
722193323Sedbool DAE::RemoveDeadStuffFromFunction(Function *F) {
723193323Sed  // Don't modify fully live functions
724193323Sed  if (LiveFunctions.count(F))
725193323Sed    return false;
726193323Sed
727193323Sed  // Start by computing a new prototype for the function, which is the same as
728193323Sed  // the old function, but has fewer arguments and a different return type.
729226890Sdim  FunctionType *FTy = F->getFunctionType();
730224145Sdim  std::vector<Type*> Params;
731193323Sed
732263509Sdim  // Keep track of if we have a live 'returned' argument
733263509Sdim  bool HasLiveReturnedArg = false;
734263509Sdim
735193323Sed  // Set up to build a new list of parameter attributes.
736252723Sdim  SmallVector<AttributeSet, 8> AttributesVec;
737252723Sdim  const AttributeSet &PAL = F->getAttributes();
738193323Sed
739263509Sdim  // Remember which arguments are still alive.
740263509Sdim  SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
741263509Sdim  // Construct the new parameter list from non-dead arguments. Also construct
742263509Sdim  // a new set of parameter attributes to correspond. Skip the first parameter
743263509Sdim  // attribute, since that belongs to the return value.
744263509Sdim  unsigned i = 0;
745263509Sdim  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
746263509Sdim       I != E; ++I, ++i) {
747263509Sdim    RetOrArg Arg = CreateArg(F, i);
748263509Sdim    if (LiveValues.erase(Arg)) {
749263509Sdim      Params.push_back(I->getType());
750263509Sdim      ArgAlive[i] = true;
751263509Sdim
752263509Sdim      // Get the original parameter attributes (skipping the first one, that is
753263509Sdim      // for the return value.
754263509Sdim      if (PAL.hasAttributes(i + 1)) {
755263509Sdim        AttrBuilder B(PAL, i + 1);
756263509Sdim        if (B.contains(Attribute::Returned))
757263509Sdim          HasLiveReturnedArg = true;
758263509Sdim        AttributesVec.
759263509Sdim          push_back(AttributeSet::get(F->getContext(), Params.size(), B));
760263509Sdim      }
761263509Sdim    } else {
762263509Sdim      ++NumArgumentsEliminated;
763263509Sdim      DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
764263509Sdim            << ") from " << F->getName() << "\n");
765263509Sdim    }
766263509Sdim  }
767263509Sdim
768193323Sed  // Find out the new return value.
769224145Sdim  Type *RetTy = FTy->getReturnType();
770226890Sdim  Type *NRetTy = NULL;
771193323Sed  unsigned RetCount = NumRetVals(F);
772206083Srdivacky
773193323Sed  // -1 means unused, other numbers are the new index
774193323Sed  SmallVector<int, 5> NewRetIdxs(RetCount, -1);
775224145Sdim  std::vector<Type*> RetTypes;
776263509Sdim
777263509Sdim  // If there is a function with a live 'returned' argument but a dead return
778263509Sdim  // value, then there are two possible actions:
779263509Sdim  // 1) Eliminate the return value and take off the 'returned' attribute on the
780263509Sdim  //    argument.
781263509Sdim  // 2) Retain the 'returned' attribute and treat the return value (but not the
782263509Sdim  //    entire function) as live so that it is not eliminated.
783263509Sdim  //
784263509Sdim  // It's not clear in the general case which option is more profitable because,
785263509Sdim  // even in the absence of explicit uses of the return value, code generation
786263509Sdim  // is free to use the 'returned' attribute to do things like eliding
787263509Sdim  // save/restores of registers across calls. Whether or not this happens is
788263509Sdim  // target and ABI-specific as well as depending on the amount of register
789263509Sdim  // pressure, so there's no good way for an IR-level pass to figure this out.
790263509Sdim  //
791263509Sdim  // Fortunately, the only places where 'returned' is currently generated by
792263509Sdim  // the FE are places where 'returned' is basically free and almost always a
793263509Sdim  // performance win, so the second option can just be used always for now.
794263509Sdim  //
795263509Sdim  // This should be revisited if 'returned' is ever applied more liberally.
796263509Sdim  if (RetTy->isVoidTy() || HasLiveReturnedArg) {
797206083Srdivacky    NRetTy = RetTy;
798193323Sed  } else {
799226890Sdim    StructType *STy = dyn_cast<StructType>(RetTy);
800193323Sed    if (STy)
801193323Sed      // Look at each of the original return values individually.
802193323Sed      for (unsigned i = 0; i != RetCount; ++i) {
803193323Sed        RetOrArg Ret = CreateRet(F, i);
804193323Sed        if (LiveValues.erase(Ret)) {
805193323Sed          RetTypes.push_back(STy->getElementType(i));
806193323Sed          NewRetIdxs[i] = RetTypes.size() - 1;
807193323Sed        } else {
808193323Sed          ++NumRetValsEliminated;
809202375Srdivacky          DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
810198090Srdivacky                << F->getName() << "\n");
811193323Sed        }
812193323Sed      }
813193323Sed    else
814193323Sed      // We used to return a single value.
815193323Sed      if (LiveValues.erase(CreateRet(F, 0))) {
816193323Sed        RetTypes.push_back(RetTy);
817193323Sed        NewRetIdxs[0] = 0;
818193323Sed      } else {
819202375Srdivacky        DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
820198090Srdivacky              << "\n");
821193323Sed        ++NumRetValsEliminated;
822193323Sed      }
823193323Sed    if (RetTypes.size() > 1)
824193323Sed      // More than one return type? Return a struct with them. Also, if we used
825193323Sed      // to return a struct and didn't change the number of return values,
826193323Sed      // return a struct again. This prevents changing {something} into
827193323Sed      // something and {} into void.
828193323Sed      // Make the new struct packed if we used to return a packed struct
829193323Sed      // already.
830198090Srdivacky      NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
831193323Sed    else if (RetTypes.size() == 1)
832193323Sed      // One return type? Just a simple value then, but only if we didn't use to
833193323Sed      // return a struct with that simple value before.
834193323Sed      NRetTy = RetTypes.front();
835193323Sed    else if (RetTypes.size() == 0)
836193323Sed      // No return types? Make it void, but only if we didn't use to return {}.
837198090Srdivacky      NRetTy = Type::getVoidTy(F->getContext());
838193323Sed  }
839193323Sed
840193323Sed  assert(NRetTy && "No new return type found?");
841193323Sed
842252723Sdim  // The existing function return attributes.
843252723Sdim  AttributeSet RAttrs = PAL.getRetAttributes();
844252723Sdim
845193323Sed  // Remove any incompatible attributes, but only if we removed all return
846193323Sed  // values. Otherwise, ensure that we don't have any conflicting attributes
847193323Sed  // here. Currently, this should not be possible, but special handling might be
848193323Sed  // required when new return value attributes are added.
849206083Srdivacky  if (NRetTy->isVoidTy())
850245431Sdim    RAttrs =
851252723Sdim      AttributeSet::get(NRetTy->getContext(), AttributeSet::ReturnIndex,
852252723Sdim                        AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
853252723Sdim         removeAttributes(AttributeFuncs::
854252723Sdim                          typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
855252723Sdim                          AttributeSet::ReturnIndex));
856193323Sed  else
857252723Sdim    assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
858252723Sdim             hasAttributes(AttributeFuncs::
859252723Sdim                           typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
860252723Sdim                           AttributeSet::ReturnIndex) &&
861245431Sdim           "Return attributes no longer compatible?");
862193323Sed
863252723Sdim  if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
864252723Sdim    AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs));
865193323Sed
866252723Sdim  if (PAL.hasAttributes(AttributeSet::FunctionIndex))
867252723Sdim    AttributesVec.push_back(AttributeSet::get(F->getContext(),
868252723Sdim                                              PAL.getFnAttributes()));
869193323Sed
870193323Sed  // Reconstruct the AttributesList based on the vector we constructed.
871252723Sdim  AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec);
872193323Sed
873193323Sed  // Create the new function type based on the recomputed parameters.
874206083Srdivacky  FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
875193323Sed
876193323Sed  // No change?
877193323Sed  if (NFTy == FTy)
878193323Sed    return false;
879193323Sed
880193323Sed  // Create the new function body and insert it into the module...
881193323Sed  Function *NF = Function::Create(NFTy, F->getLinkage());
882193323Sed  NF->copyAttributesFrom(F);
883193323Sed  NF->setAttributes(NewPAL);
884193323Sed  // Insert the new function before the old function, so we won't be processing
885193323Sed  // it again.
886193323Sed  F->getParent()->getFunctionList().insert(F, NF);
887193323Sed  NF->takeName(F);
888193323Sed
889193323Sed  // Loop over all of the callers of the function, transforming the call sites
890193323Sed  // to pass in a smaller number of arguments into the new function.
891193323Sed  //
892193323Sed  std::vector<Value*> Args;
893193323Sed  while (!F->use_empty()) {
894212904Sdim    CallSite CS(F->use_back());
895193323Sed    Instruction *Call = CS.getInstruction();
896193323Sed
897193323Sed    AttributesVec.clear();
898252723Sdim    const AttributeSet &CallPAL = CS.getAttributes();
899193323Sed
900193323Sed    // The call return attributes.
901252723Sdim    AttributeSet RAttrs = CallPAL.getRetAttributes();
902252723Sdim
903193323Sed    // Adjust in case the function was changed to return void.
904245431Sdim    RAttrs =
905252723Sdim      AttributeSet::get(NF->getContext(), AttributeSet::ReturnIndex,
906252723Sdim                        AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
907252723Sdim        removeAttributes(AttributeFuncs::
908252723Sdim                         typeIncompatible(NF->getReturnType(),
909252723Sdim                                          AttributeSet::ReturnIndex),
910252723Sdim                         AttributeSet::ReturnIndex));
911252723Sdim    if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
912252723Sdim      AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs));
913193323Sed
914193323Sed    // Declare these outside of the loops, so we can reuse them for the second
915193323Sed    // loop, which loops the varargs.
916193323Sed    CallSite::arg_iterator I = CS.arg_begin();
917193323Sed    unsigned i = 0;
918193323Sed    // Loop over those operands, corresponding to the normal arguments to the
919193323Sed    // original function, and add those that are still alive.
920193323Sed    for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
921193323Sed      if (ArgAlive[i]) {
922193323Sed        Args.push_back(*I);
923193323Sed        // Get original parameter attributes, but skip return attributes.
924252723Sdim        if (CallPAL.hasAttributes(i + 1)) {
925252723Sdim          AttrBuilder B(CallPAL, i + 1);
926263509Sdim          // If the return type has changed, then get rid of 'returned' on the
927263509Sdim          // call site. The alternative is to make all 'returned' attributes on
928263509Sdim          // call sites keep the return value alive just like 'returned'
929263509Sdim          // attributes on function declaration but it's less clearly a win
930263509Sdim          // and this is not an expected case anyway
931263509Sdim          if (NRetTy != RetTy && B.contains(Attribute::Returned))
932263509Sdim            B.removeAttribute(Attribute::Returned);
933252723Sdim          AttributesVec.
934252723Sdim            push_back(AttributeSet::get(F->getContext(), Args.size(), B));
935252723Sdim        }
936193323Sed      }
937193323Sed
938193323Sed    // Push any varargs arguments on the list. Don't forget their attributes.
939193323Sed    for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
940193323Sed      Args.push_back(*I);
941252723Sdim      if (CallPAL.hasAttributes(i + 1)) {
942252723Sdim        AttrBuilder B(CallPAL, i + 1);
943252723Sdim        AttributesVec.
944252723Sdim          push_back(AttributeSet::get(F->getContext(), Args.size(), B));
945252723Sdim      }
946193323Sed    }
947193323Sed
948252723Sdim    if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
949252723Sdim      AttributesVec.push_back(AttributeSet::get(Call->getContext(),
950252723Sdim                                                CallPAL.getFnAttributes()));
951193323Sed
952193323Sed    // Reconstruct the AttributesList based on the vector we constructed.
953252723Sdim    AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec);
954193323Sed
955193323Sed    Instruction *New;
956193323Sed    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
957193323Sed      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
958224145Sdim                               Args, "", Call);
959193323Sed      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
960193323Sed      cast<InvokeInst>(New)->setAttributes(NewCallPAL);
961193323Sed    } else {
962224145Sdim      New = CallInst::Create(NF, Args, "", Call);
963193323Sed      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
964193323Sed      cast<CallInst>(New)->setAttributes(NewCallPAL);
965193323Sed      if (cast<CallInst>(Call)->isTailCall())
966193323Sed        cast<CallInst>(New)->setTailCall();
967193323Sed    }
968212904Sdim    New->setDebugLoc(Call->getDebugLoc());
969207618Srdivacky
970193323Sed    Args.clear();
971193323Sed
972193323Sed    if (!Call->use_empty()) {
973193323Sed      if (New->getType() == Call->getType()) {
974193323Sed        // Return type not changed? Just replace users then.
975193323Sed        Call->replaceAllUsesWith(New);
976193323Sed        New->takeName(Call);
977206083Srdivacky      } else if (New->getType()->isVoidTy()) {
978193323Sed        // Our return value has uses, but they will get removed later on.
979193323Sed        // Replace by null for now.
980218893Sdim        if (!Call->getType()->isX86_MMXTy())
981218893Sdim          Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
982193323Sed      } else {
983204642Srdivacky        assert(RetTy->isStructTy() &&
984193323Sed               "Return type changed, but not into a void. The old return type"
985193323Sed               " must have been a struct!");
986193323Sed        Instruction *InsertPt = Call;
987193323Sed        if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
988193323Sed          BasicBlock::iterator IP = II->getNormalDest()->begin();
989193323Sed          while (isa<PHINode>(IP)) ++IP;
990193323Sed          InsertPt = IP;
991193323Sed        }
992206083Srdivacky
993193323Sed        // We used to return a struct. Instead of doing smart stuff with all the
994193323Sed        // uses of this struct, we will just rebuild it using
995193323Sed        // extract/insertvalue chaining and let instcombine clean that up.
996193323Sed        //
997193323Sed        // Start out building up our return value from undef
998198090Srdivacky        Value *RetVal = UndefValue::get(RetTy);
999193323Sed        for (unsigned i = 0; i != RetCount; ++i)
1000193323Sed          if (NewRetIdxs[i] != -1) {
1001193323Sed            Value *V;
1002193323Sed            if (RetTypes.size() > 1)
1003193323Sed              // We are still returning a struct, so extract the value from our
1004193323Sed              // return value
1005193323Sed              V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
1006193323Sed                                           InsertPt);
1007193323Sed            else
1008193323Sed              // We are now returning a single element, so just insert that
1009193323Sed              V = New;
1010193323Sed            // Insert the value at the old position
1011193323Sed            RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
1012193323Sed          }
1013193323Sed        // Now, replace all uses of the old call instruction with the return
1014193323Sed        // struct we built
1015193323Sed        Call->replaceAllUsesWith(RetVal);
1016193323Sed        New->takeName(Call);
1017193323Sed      }
1018193323Sed    }
1019193323Sed
1020193323Sed    // Finally, remove the old call from the program, reducing the use-count of
1021193323Sed    // F.
1022193323Sed    Call->eraseFromParent();
1023193323Sed  }
1024193323Sed
1025193323Sed  // Since we have now created the new function, splice the body of the old
1026193323Sed  // function right into the new function, leaving the old rotting hulk of the
1027193323Sed  // function empty.
1028193323Sed  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
1029193323Sed
1030221345Sdim  // Loop over the argument list, transferring uses of the old arguments over to
1031221345Sdim  // the new arguments, also transferring over the names as well.
1032193323Sed  i = 0;
1033193323Sed  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
1034193323Sed       I2 = NF->arg_begin(); I != E; ++I, ++i)
1035193323Sed    if (ArgAlive[i]) {
1036193323Sed      // If this is a live argument, move the name and users over to the new
1037193323Sed      // version.
1038193323Sed      I->replaceAllUsesWith(I2);
1039193323Sed      I2->takeName(I);
1040193323Sed      ++I2;
1041193323Sed    } else {
1042193323Sed      // If this argument is dead, replace any uses of it with null constants
1043193323Sed      // (these are guaranteed to become unused later on).
1044218893Sdim      if (!I->getType()->isX86_MMXTy())
1045218893Sdim        I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
1046193323Sed    }
1047193323Sed
1048193323Sed  // If we change the return value of the function we must rewrite any return
1049193323Sed  // instructions.  Check this now.
1050193323Sed  if (F->getReturnType() != NF->getReturnType())
1051193323Sed    for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
1052193323Sed      if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1053193323Sed        Value *RetVal;
1054193323Sed
1055208599Srdivacky        if (NFTy->getReturnType()->isVoidTy()) {
1056193323Sed          RetVal = 0;
1057193323Sed        } else {
1058204642Srdivacky          assert (RetTy->isStructTy());
1059193323Sed          // The original return value was a struct, insert
1060193323Sed          // extractvalue/insertvalue chains to extract only the values we need
1061193323Sed          // to return and insert them into our new result.
1062193323Sed          // This does generate messy code, but we'll let it to instcombine to
1063193323Sed          // clean that up.
1064193323Sed          Value *OldRet = RI->getOperand(0);
1065193323Sed          // Start out building up our return value from undef
1066198090Srdivacky          RetVal = UndefValue::get(NRetTy);
1067193323Sed          for (unsigned i = 0; i != RetCount; ++i)
1068193323Sed            if (NewRetIdxs[i] != -1) {
1069193323Sed              ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
1070193323Sed                                                              "oldret", RI);
1071193323Sed              if (RetTypes.size() > 1) {
1072193323Sed                // We're still returning a struct, so reinsert the value into
1073193323Sed                // our new return value at the new index
1074193323Sed
1075193323Sed                RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
1076193323Sed                                                 "newret", RI);
1077193323Sed              } else {
1078193323Sed                // We are now only returning a simple value, so just return the
1079193323Sed                // extracted value.
1080193323Sed                RetVal = EV;
1081193323Sed              }
1082193323Sed            }
1083193323Sed        }
1084193323Sed        // Replace the return instruction with one returning the new return
1085193323Sed        // value (possibly 0 if we became void).
1086198090Srdivacky        ReturnInst::Create(F->getContext(), RetVal, RI);
1087193323Sed        BB->getInstList().erase(RI);
1088193323Sed      }
1089193323Sed
1090245431Sdim  // Patch the pointer to LLVM function in debug info descriptor.
1091245431Sdim  FunctionDIMap::iterator DI = FunctionDIs.find(F);
1092245431Sdim  if (DI != FunctionDIs.end())
1093245431Sdim    DI->second.replaceFunction(NF);
1094245431Sdim
1095193323Sed  // Now that the old function is dead, delete it.
1096193323Sed  F->eraseFromParent();
1097193323Sed
1098193323Sed  return true;
1099193323Sed}
1100193323Sed
1101193323Sedbool DAE::runOnModule(Module &M) {
1102193323Sed  bool Changed = false;
1103193323Sed
1104245431Sdim  // Collect debug info descriptors for functions.
1105245431Sdim  CollectFunctionDIs(M);
1106245431Sdim
1107193323Sed  // First pass: Do a simple check to see if any functions can have their "..."
1108193323Sed  // removed.  We can do this if they never call va_start.  This loop cannot be
1109193323Sed  // fused with the next loop, because deleting a function invalidates
1110193323Sed  // information computed while surveying other functions.
1111202375Srdivacky  DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
1112193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1113193323Sed    Function &F = *I++;
1114193323Sed    if (F.getFunctionType()->isVarArg())
1115193323Sed      Changed |= DeleteDeadVarargs(F);
1116193323Sed  }
1117193323Sed
1118193323Sed  // Second phase:loop through the module, determining which arguments are live.
1119193323Sed  // We assume all arguments are dead unless proven otherwise (allowing us to
1120193323Sed  // determine that dead arguments passed into recursive functions are dead).
1121193323Sed  //
1122202375Srdivacky  DEBUG(dbgs() << "DAE - Determining liveness\n");
1123193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1124193323Sed    SurveyFunction(*I);
1125206083Srdivacky
1126193323Sed  // Now, remove all dead arguments and return values from each function in
1127206083Srdivacky  // turn.
1128193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1129206083Srdivacky    // Increment now, because the function will probably get removed (ie.
1130193323Sed    // replaced by a new one).
1131193323Sed    Function *F = I++;
1132193323Sed    Changed |= RemoveDeadStuffFromFunction(F);
1133193323Sed  }
1134218893Sdim
1135218893Sdim  // Finally, look for any unused parameters in functions with non-local
1136218893Sdim  // linkage and replace the passed in parameters with undef.
1137218893Sdim  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1138218893Sdim    Function& F = *I;
1139218893Sdim
1140218893Sdim    Changed |= RemoveDeadArgumentsFromCallers(F);
1141218893Sdim  }
1142218893Sdim
1143193323Sed  return Changed;
1144193323Sed}
1145