LLVM API Documentation

DeadArgumentElimination.cpp
Go to the documentation of this file.
00001 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass deletes dead arguments from internal functions.  Dead argument
00011 // elimination removes arguments which are directly dead, as well as arguments
00012 // only passed into function calls as dead arguments of other functions.  This
00013 // pass also deletes dead return values in a similar way.
00014 //
00015 // This pass is often useful as a cleanup pass to run after aggressive
00016 // interprocedural passes, which add possibly-dead arguments or return values.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #define DEBUG_TYPE "deadargelim"
00021 #include "llvm/Transforms/IPO.h"
00022 #include "llvm/ADT/DenseMap.h"
00023 #include "llvm/ADT/SmallVector.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/IR/CallSite.h"
00027 #include "llvm/IR/CallingConv.h"
00028 #include "llvm/IR/Constant.h"
00029 #include "llvm/IR/DIBuilder.h"
00030 #include "llvm/IR/DebugInfo.h"
00031 #include "llvm/IR/DerivedTypes.h"
00032 #include "llvm/IR/Instructions.h"
00033 #include "llvm/IR/IntrinsicInst.h"
00034 #include "llvm/IR/LLVMContext.h"
00035 #include "llvm/IR/Module.h"
00036 #include "llvm/Pass.h"
00037 #include "llvm/Support/Debug.h"
00038 #include "llvm/Support/raw_ostream.h"
00039 #include <map>
00040 #include <set>
00041 using namespace llvm;
00042 
00043 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
00044 STATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
00045 STATISTIC(NumArgumentsReplacedWithUndef, 
00046           "Number of unread args replaced with undef");
00047 namespace {
00048   /// DAE - The dead argument elimination pass.
00049   ///
00050   class DAE : public ModulePass {
00051   public:
00052 
00053     /// Struct that represents (part of) either a return value or a function
00054     /// argument.  Used so that arguments and return values can be used
00055     /// interchangeably.
00056     struct RetOrArg {
00057       RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
00058                IsArg(IsArg) {}
00059       const Function *F;
00060       unsigned Idx;
00061       bool IsArg;
00062 
00063       /// Make RetOrArg comparable, so we can put it into a map.
00064       bool operator<(const RetOrArg &O) const {
00065         return std::tie(F, Idx, IsArg) < std::tie(O.F, O.Idx, O.IsArg);
00066       }
00067 
00068       /// Make RetOrArg comparable, so we can easily iterate the multimap.
00069       bool operator==(const RetOrArg &O) const {
00070         return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
00071       }
00072 
00073       std::string getDescription() const {
00074         return std::string((IsArg ? "Argument #" : "Return value #"))
00075                + utostr(Idx) + " of function " + F->getName().str();
00076       }
00077     };
00078 
00079     /// Liveness enum - During our initial pass over the program, we determine
00080     /// that things are either alive or maybe alive. We don't mark anything
00081     /// explicitly dead (even if we know they are), since anything not alive
00082     /// with no registered uses (in Uses) will never be marked alive and will
00083     /// thus become dead in the end.
00084     enum Liveness { Live, MaybeLive };
00085 
00086     /// Convenience wrapper
00087     RetOrArg CreateRet(const Function *F, unsigned Idx) {
00088       return RetOrArg(F, Idx, false);
00089     }
00090     /// Convenience wrapper
00091     RetOrArg CreateArg(const Function *F, unsigned Idx) {
00092       return RetOrArg(F, Idx, true);
00093     }
00094 
00095     typedef std::multimap<RetOrArg, RetOrArg> UseMap;
00096     /// This maps a return value or argument to any MaybeLive return values or
00097     /// arguments it uses. This allows the MaybeLive values to be marked live
00098     /// when any of its users is marked live.
00099     /// For example (indices are left out for clarity):
00100     ///  - Uses[ret F] = ret G
00101     ///    This means that F calls G, and F returns the value returned by G.
00102     ///  - Uses[arg F] = ret G
00103     ///    This means that some function calls G and passes its result as an
00104     ///    argument to F.
00105     ///  - Uses[ret F] = arg F
00106     ///    This means that F returns one of its own arguments.
00107     ///  - Uses[arg F] = arg G
00108     ///    This means that G calls F and passes one of its own (G's) arguments
00109     ///    directly to F.
00110     UseMap Uses;
00111 
00112     typedef std::set<RetOrArg> LiveSet;
00113     typedef std::set<const Function*> LiveFuncSet;
00114 
00115     /// This set contains all values that have been determined to be live.
00116     LiveSet LiveValues;
00117     /// This set contains all values that are cannot be changed in any way.
00118     LiveFuncSet LiveFunctions;
00119 
00120     typedef SmallVector<RetOrArg, 5> UseVector;
00121 
00122     // Map each LLVM function to corresponding metadata with debug info. If
00123     // the function is replaced with another one, we should patch the pointer
00124     // to LLVM function in metadata.
00125     // As the code generation for module is finished (and DIBuilder is
00126     // finalized) we assume that subprogram descriptors won't be changed, and
00127     // they are stored in map for short duration anyway.
00128     typedef DenseMap<Function*, DISubprogram> FunctionDIMap;
00129     FunctionDIMap FunctionDIs;
00130 
00131   protected:
00132     // DAH uses this to specify a different ID.
00133     explicit DAE(char &ID) : ModulePass(ID) {}
00134 
00135   public:
00136     static char ID; // Pass identification, replacement for typeid
00137     DAE() : ModulePass(ID) {
00138       initializeDAEPass(*PassRegistry::getPassRegistry());
00139     }
00140 
00141     bool runOnModule(Module &M) override;
00142 
00143     virtual bool ShouldHackArguments() const { return false; }
00144 
00145   private:
00146     Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
00147     Liveness SurveyUse(const Use *U, UseVector &MaybeLiveUses,
00148                        unsigned RetValNum = 0);
00149     Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
00150 
00151     void CollectFunctionDIs(Module &M);
00152     void SurveyFunction(const Function &F);
00153     void MarkValue(const RetOrArg &RA, Liveness L,
00154                    const UseVector &MaybeLiveUses);
00155     void MarkLive(const RetOrArg &RA);
00156     void MarkLive(const Function &F);
00157     void PropagateLiveness(const RetOrArg &RA);
00158     bool RemoveDeadStuffFromFunction(Function *F);
00159     bool DeleteDeadVarargs(Function &Fn);
00160     bool RemoveDeadArgumentsFromCallers(Function &Fn);
00161   };
00162 }
00163 
00164 
00165 char DAE::ID = 0;
00166 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
00167 
00168 namespace {
00169   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
00170   /// deletes arguments to functions which are external.  This is only for use
00171   /// by bugpoint.
00172   struct DAH : public DAE {
00173     static char ID;
00174     DAH() : DAE(ID) {}
00175 
00176     bool ShouldHackArguments() const override { return true; }
00177   };
00178 }
00179 
00180 char DAH::ID = 0;
00181 INITIALIZE_PASS(DAH, "deadarghaX0r", 
00182                 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
00183                 false, false)
00184 
00185 /// createDeadArgEliminationPass - This pass removes arguments from functions
00186 /// which are not used by the body of the function.
00187 ///
00188 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
00189 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
00190 
00191 /// CollectFunctionDIs - Map each function in the module to its debug info
00192 /// descriptor.
00193 void DAE::CollectFunctionDIs(Module &M) {
00194   FunctionDIs.clear();
00195 
00196   for (Module::named_metadata_iterator I = M.named_metadata_begin(),
00197        E = M.named_metadata_end(); I != E; ++I) {
00198     NamedMDNode &NMD = *I;
00199     for (unsigned MDIndex = 0, MDNum = NMD.getNumOperands();
00200          MDIndex < MDNum; ++MDIndex) {
00201       MDNode *Node = NMD.getOperand(MDIndex);
00202       if (!DIDescriptor(Node).isCompileUnit())
00203         continue;
00204       DICompileUnit CU(Node);
00205       const DIArray &SPs = CU.getSubprograms();
00206       for (unsigned SPIndex = 0, SPNum = SPs.getNumElements();
00207            SPIndex < SPNum; ++SPIndex) {
00208         DISubprogram SP(SPs.getElement(SPIndex));
00209         assert((!SP || SP.isSubprogram()) &&
00210           "A MDNode in subprograms of a CU should be null or a DISubprogram.");
00211         if (!SP)
00212           continue;
00213         if (Function *F = SP.getFunction())
00214           FunctionDIs[F] = SP;
00215       }
00216     }
00217   }
00218 }
00219 
00220 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
00221 /// llvm.vastart is never called, the varargs list is dead for the function.
00222 bool DAE::DeleteDeadVarargs(Function &Fn) {
00223   assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
00224   if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
00225 
00226   // Ensure that the function is only directly called.
00227   if (Fn.hasAddressTaken())
00228     return false;
00229 
00230   // Okay, we know we can transform this function if safe.  Scan its body
00231   // looking for calls to llvm.vastart.
00232   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
00233     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00234       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00235         if (II->getIntrinsicID() == Intrinsic::vastart)
00236           return false;
00237       }
00238     }
00239   }
00240 
00241   // If we get here, there are no calls to llvm.vastart in the function body,
00242   // remove the "..." and adjust all the calls.
00243 
00244   // Start by computing a new prototype for the function, which is the same as
00245   // the old function, but doesn't have isVarArg set.
00246   FunctionType *FTy = Fn.getFunctionType();
00247 
00248   std::vector<Type*> Params(FTy->param_begin(), FTy->param_end());
00249   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
00250                                                 Params, false);
00251   unsigned NumArgs = Params.size();
00252 
00253   // Create the new function body and insert it into the module...
00254   Function *NF = Function::Create(NFTy, Fn.getLinkage());
00255   NF->copyAttributesFrom(&Fn);
00256   Fn.getParent()->getFunctionList().insert(&Fn, NF);
00257   NF->takeName(&Fn);
00258 
00259   // Loop over all of the callers of the function, transforming the call sites
00260   // to pass in a smaller number of arguments into the new function.
00261   //
00262   std::vector<Value*> Args;
00263   for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) {
00264     CallSite CS(*I++);
00265     if (!CS)
00266       continue;
00267     Instruction *Call = CS.getInstruction();
00268 
00269     // Pass all the same arguments.
00270     Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
00271 
00272     // Drop any attributes that were on the vararg arguments.
00273     AttributeSet PAL = CS.getAttributes();
00274     if (!PAL.isEmpty() && PAL.getSlotIndex(PAL.getNumSlots() - 1) > NumArgs) {
00275       SmallVector<AttributeSet, 8> AttributesVec;
00276       for (unsigned i = 0; PAL.getSlotIndex(i) <= NumArgs; ++i)
00277         AttributesVec.push_back(PAL.getSlotAttributes(i));
00278       if (PAL.hasAttributes(AttributeSet::FunctionIndex))
00279         AttributesVec.push_back(AttributeSet::get(Fn.getContext(),
00280                                                   PAL.getFnAttributes()));
00281       PAL = AttributeSet::get(Fn.getContext(), AttributesVec);
00282     }
00283 
00284     Instruction *New;
00285     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00286       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00287                                Args, "", Call);
00288       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00289       cast<InvokeInst>(New)->setAttributes(PAL);
00290     } else {
00291       New = CallInst::Create(NF, Args, "", Call);
00292       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00293       cast<CallInst>(New)->setAttributes(PAL);
00294       if (cast<CallInst>(Call)->isTailCall())
00295         cast<CallInst>(New)->setTailCall();
00296     }
00297     New->setDebugLoc(Call->getDebugLoc());
00298 
00299     Args.clear();
00300 
00301     if (!Call->use_empty())
00302       Call->replaceAllUsesWith(New);
00303 
00304     New->takeName(Call);
00305 
00306     // Finally, remove the old call from the program, reducing the use-count of
00307     // F.
00308     Call->eraseFromParent();
00309   }
00310 
00311   // Since we have now created the new function, splice the body of the old
00312   // function right into the new function, leaving the old rotting hulk of the
00313   // function empty.
00314   NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
00315 
00316   // Loop over the argument list, transferring uses of the old arguments over to
00317   // the new arguments, also transferring over the names as well.  While we're at
00318   // it, remove the dead arguments from the DeadArguments list.
00319   //
00320   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
00321        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
00322     // Move the name and users over to the new version.
00323     I->replaceAllUsesWith(I2);
00324     I2->takeName(I);
00325   }
00326 
00327   // Patch the pointer to LLVM function in debug info descriptor.
00328   FunctionDIMap::iterator DI = FunctionDIs.find(&Fn);
00329   if (DI != FunctionDIs.end())
00330     DI->second.replaceFunction(NF);
00331 
00332   // Fix up any BlockAddresses that refer to the function.
00333   Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType()));
00334   // Delete the bitcast that we just created, so that NF does not
00335   // appear to be address-taken.
00336   NF->removeDeadConstantUsers();
00337   // Finally, nuke the old function.
00338   Fn.eraseFromParent();
00339   return true;
00340 }
00341 
00342 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any 
00343 /// arguments that are unused, and changes the caller parameters to be undefined
00344 /// instead.
00345 bool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
00346 {
00347   if (Fn.isDeclaration() || Fn.mayBeOverridden())
00348     return false;
00349 
00350   // Functions with local linkage should already have been handled, except the
00351   // fragile (variadic) ones which we can improve here.
00352   if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg())
00353     return false;
00354 
00355   // If a function seen at compile time is not necessarily the one linked to
00356   // the binary being built, it is illegal to change the actual arguments
00357   // passed to it. These functions can be captured by isWeakForLinker().
00358   // *NOTE* that mayBeOverridden() is insufficient for this purpose as it
00359   // doesn't include linkage types like AvailableExternallyLinkage and
00360   // LinkOnceODRLinkage. Take link_odr* as an example, it indicates a set of
00361   // *EQUIVALENT* globals that can be merged at link-time. However, the
00362   // semantic of *EQUIVALENT*-functions includes parameters. Changing
00363   // parameters breaks this assumption.
00364   //
00365   if (Fn.isWeakForLinker())
00366     return false;
00367 
00368   if (Fn.use_empty())
00369     return false;
00370 
00371   SmallVector<unsigned, 8> UnusedArgs;
00372   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 
00373        I != E; ++I) {
00374     Argument *Arg = I;
00375 
00376     if (Arg->use_empty() && !Arg->hasByValOrInAllocaAttr())
00377       UnusedArgs.push_back(Arg->getArgNo());
00378   }
00379 
00380   if (UnusedArgs.empty())
00381     return false;
00382 
00383   bool Changed = false;
00384 
00385   for (Use &U : Fn.uses()) {
00386     CallSite CS(U.getUser());
00387     if (!CS || !CS.isCallee(&U))
00388       continue;
00389 
00390     // Now go through all unused args and replace them with "undef".
00391     for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
00392       unsigned ArgNo = UnusedArgs[I];
00393 
00394       Value *Arg = CS.getArgument(ArgNo);
00395       CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
00396       ++NumArgumentsReplacedWithUndef;
00397       Changed = true;
00398     }
00399   }
00400 
00401   return Changed;
00402 }
00403 
00404 /// Convenience function that returns the number of return values. It returns 0
00405 /// for void functions and 1 for functions not returning a struct. It returns
00406 /// the number of struct elements for functions returning a struct.
00407 static unsigned NumRetVals(const Function *F) {
00408   if (F->getReturnType()->isVoidTy())
00409     return 0;
00410   else if (StructType *STy = dyn_cast<StructType>(F->getReturnType()))
00411     return STy->getNumElements();
00412   else
00413     return 1;
00414 }
00415 
00416 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
00417 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
00418 /// liveness of Use.
00419 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
00420   // We're live if our use or its Function is already marked as live.
00421   if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
00422     return Live;
00423 
00424   // We're maybe live otherwise, but remember that we must become live if
00425   // Use becomes live.
00426   MaybeLiveUses.push_back(Use);
00427   return MaybeLive;
00428 }
00429 
00430 
00431 /// SurveyUse - This looks at a single use of an argument or return value
00432 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
00433 /// if it causes the used value to become MaybeLive.
00434 ///
00435 /// RetValNum is the return value number to use when this use is used in a
00436 /// return instruction. This is used in the recursion, you should always leave
00437 /// it at 0.
00438 DAE::Liveness DAE::SurveyUse(const Use *U,
00439                              UseVector &MaybeLiveUses, unsigned RetValNum) {
00440     const User *V = U->getUser();
00441     if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
00442       // The value is returned from a function. It's only live when the
00443       // function's return value is live. We use RetValNum here, for the case
00444       // that U is really a use of an insertvalue instruction that uses the
00445       // original Use.
00446       RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
00447       // We might be live, depending on the liveness of Use.
00448       return MarkIfNotLive(Use, MaybeLiveUses);
00449     }
00450     if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
00451       if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex()
00452           && IV->hasIndices())
00453         // The use we are examining is inserted into an aggregate. Our liveness
00454         // depends on all uses of that aggregate, but if it is used as a return
00455         // value, only index at which we were inserted counts.
00456         RetValNum = *IV->idx_begin();
00457 
00458       // Note that if we are used as the aggregate operand to the insertvalue,
00459       // we don't change RetValNum, but do survey all our uses.
00460 
00461       Liveness Result = MaybeLive;
00462       for (const Use &UU : IV->uses()) {
00463         Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
00464         if (Result == Live)
00465           break;
00466       }
00467       return Result;
00468     }
00469 
00470     if (ImmutableCallSite CS = V) {
00471       const Function *F = CS.getCalledFunction();
00472       if (F) {
00473         // Used in a direct call.
00474 
00475         // Find the argument number. We know for sure that this use is an
00476         // argument, since if it was the function argument this would be an
00477         // indirect call and the we know can't be looking at a value of the
00478         // label type (for the invoke instruction).
00479         unsigned ArgNo = CS.getArgumentNo(U);
00480 
00481         if (ArgNo >= F->getFunctionType()->getNumParams())
00482           // The value is passed in through a vararg! Must be live.
00483           return Live;
00484 
00485         assert(CS.getArgument(ArgNo)
00486                == CS->getOperand(U->getOperandNo())
00487                && "Argument is not where we expected it");
00488 
00489         // Value passed to a normal call. It's only live when the corresponding
00490         // argument to the called function turns out live.
00491         RetOrArg Use = CreateArg(F, ArgNo);
00492         return MarkIfNotLive(Use, MaybeLiveUses);
00493       }
00494     }
00495     // Used in any other way? Value must be live.
00496     return Live;
00497 }
00498 
00499 /// SurveyUses - This looks at all the uses of the given value
00500 /// Returns the Liveness deduced from the uses of this value.
00501 ///
00502 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
00503 /// the result is Live, MaybeLiveUses might be modified but its content should
00504 /// be ignored (since it might not be complete).
00505 DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
00506   // Assume it's dead (which will only hold if there are no uses at all..).
00507   Liveness Result = MaybeLive;
00508   // Check each use.
00509   for (const Use &U : V->uses()) {
00510     Result = SurveyUse(&U, MaybeLiveUses);
00511     if (Result == Live)
00512       break;
00513   }
00514   return Result;
00515 }
00516 
00517 // SurveyFunction - This performs the initial survey of the specified function,
00518 // checking out whether or not it uses any of its incoming arguments or whether
00519 // any callers use the return value.  This fills in the LiveValues set and Uses
00520 // map.
00521 //
00522 // We consider arguments of non-internal functions to be intrinsically alive as
00523 // well as arguments to functions which have their "address taken".
00524 //
00525 void DAE::SurveyFunction(const Function &F) {
00526   // Functions with inalloca parameters are expecting args in a particular
00527   // register and memory layout.
00528   if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) {
00529     MarkLive(F);
00530     return;
00531   }
00532 
00533   unsigned RetCount = NumRetVals(&F);
00534   // Assume all return values are dead
00535   typedef SmallVector<Liveness, 5> RetVals;
00536   RetVals RetValLiveness(RetCount, MaybeLive);
00537 
00538   typedef SmallVector<UseVector, 5> RetUses;
00539   // These vectors map each return value to the uses that make it MaybeLive, so
00540   // we can add those to the Uses map if the return value really turns out to be
00541   // MaybeLive. Initialized to a list of RetCount empty lists.
00542   RetUses MaybeLiveRetUses(RetCount);
00543 
00544   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00545     if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
00546       if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
00547           != F.getFunctionType()->getReturnType()) {
00548         // We don't support old style multiple return values.
00549         MarkLive(F);
00550         return;
00551       }
00552 
00553   if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
00554     MarkLive(F);
00555     return;
00556   }
00557 
00558   DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
00559   // Keep track of the number of live retvals, so we can skip checks once all
00560   // of them turn out to be live.
00561   unsigned NumLiveRetVals = 0;
00562   Type *STy = dyn_cast<StructType>(F.getReturnType());
00563   // Loop all uses of the function.
00564   for (const Use &U : F.uses()) {
00565     // If the function is PASSED IN as an argument, its address has been
00566     // taken.
00567     ImmutableCallSite CS(U.getUser());
00568     if (!CS || !CS.isCallee(&U)) {
00569       MarkLive(F);
00570       return;
00571     }
00572 
00573     // If this use is anything other than a call site, the function is alive.
00574     const Instruction *TheCall = CS.getInstruction();
00575     if (!TheCall) {   // Not a direct call site?
00576       MarkLive(F);
00577       return;
00578     }
00579 
00580     // If we end up here, we are looking at a direct call to our function.
00581 
00582     // Now, check how our return value(s) is/are used in this caller. Don't
00583     // bother checking return values if all of them are live already.
00584     if (NumLiveRetVals != RetCount) {
00585       if (STy) {
00586         // Check all uses of the return value.
00587         for (const User *U : TheCall->users()) {
00588           const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U);
00589           if (Ext && Ext->hasIndices()) {
00590             // This use uses a part of our return value, survey the uses of
00591             // that part and store the results for this index only.
00592             unsigned Idx = *Ext->idx_begin();
00593             if (RetValLiveness[Idx] != Live) {
00594               RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
00595               if (RetValLiveness[Idx] == Live)
00596                 NumLiveRetVals++;
00597             }
00598           } else {
00599             // Used by something else than extractvalue. Mark all return
00600             // values as live.
00601             for (unsigned i = 0; i != RetCount; ++i )
00602               RetValLiveness[i] = Live;
00603             NumLiveRetVals = RetCount;
00604             break;
00605           }
00606         }
00607       } else {
00608         // Single return value
00609         RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
00610         if (RetValLiveness[0] == Live)
00611           NumLiveRetVals = RetCount;
00612       }
00613     }
00614   }
00615 
00616   // Now we've inspected all callers, record the liveness of our return values.
00617   for (unsigned i = 0; i != RetCount; ++i)
00618     MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
00619 
00620   DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
00621 
00622   // Now, check all of our arguments.
00623   unsigned i = 0;
00624   UseVector MaybeLiveArgUses;
00625   for (Function::const_arg_iterator AI = F.arg_begin(),
00626        E = F.arg_end(); AI != E; ++AI, ++i) {
00627     Liveness Result;
00628     if (F.getFunctionType()->isVarArg()) {
00629       // Variadic functions will already have a va_arg function expanded inside
00630       // them, making them potentially very sensitive to ABI changes resulting
00631       // from removing arguments entirely, so don't. For example AArch64 handles
00632       // register and stack HFAs very differently, and this is reflected in the
00633       // IR which has already been generated.
00634       Result = Live;
00635     } else {
00636       // See what the effect of this use is (recording any uses that cause
00637       // MaybeLive in MaybeLiveArgUses). 
00638       Result = SurveyUses(AI, MaybeLiveArgUses);
00639     }
00640 
00641     // Mark the result.
00642     MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
00643     // Clear the vector again for the next iteration.
00644     MaybeLiveArgUses.clear();
00645   }
00646 }
00647 
00648 /// MarkValue - This function marks the liveness of RA depending on L. If L is
00649 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
00650 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
00651 /// live later on.
00652 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
00653                     const UseVector &MaybeLiveUses) {
00654   switch (L) {
00655     case Live: MarkLive(RA); break;
00656     case MaybeLive:
00657     {
00658       // Note any uses of this value, so this return value can be
00659       // marked live whenever one of the uses becomes live.
00660       for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
00661            UE = MaybeLiveUses.end(); UI != UE; ++UI)
00662         Uses.insert(std::make_pair(*UI, RA));
00663       break;
00664     }
00665   }
00666 }
00667 
00668 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
00669 /// changed in any way. Additionally,
00670 /// mark any values that are used as this function's parameters or by its return
00671 /// values (according to Uses) live as well.
00672 void DAE::MarkLive(const Function &F) {
00673   DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
00674   // Mark the function as live.
00675   LiveFunctions.insert(&F);
00676   // Mark all arguments as live.
00677   for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
00678     PropagateLiveness(CreateArg(&F, i));
00679   // Mark all return values as live.
00680   for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
00681     PropagateLiveness(CreateRet(&F, i));
00682 }
00683 
00684 /// MarkLive - Mark the given return value or argument as live. Additionally,
00685 /// mark any values that are used by this value (according to Uses) live as
00686 /// well.
00687 void DAE::MarkLive(const RetOrArg &RA) {
00688   if (LiveFunctions.count(RA.F))
00689     return; // Function was already marked Live.
00690 
00691   if (!LiveValues.insert(RA).second)
00692     return; // We were already marked Live.
00693 
00694   DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
00695   PropagateLiveness(RA);
00696 }
00697 
00698 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
00699 /// to any other values it uses (according to Uses).
00700 void DAE::PropagateLiveness(const RetOrArg &RA) {
00701   // We don't use upper_bound (or equal_range) here, because our recursive call
00702   // to ourselves is likely to cause the upper_bound (which is the first value
00703   // not belonging to RA) to become erased and the iterator invalidated.
00704   UseMap::iterator Begin = Uses.lower_bound(RA);
00705   UseMap::iterator E = Uses.end();
00706   UseMap::iterator I;
00707   for (I = Begin; I != E && I->first == RA; ++I)
00708     MarkLive(I->second);
00709 
00710   // Erase RA from the Uses map (from the lower bound to wherever we ended up
00711   // after the loop).
00712   Uses.erase(Begin, I);
00713 }
00714 
00715 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
00716 // that are not in LiveValues. Transform the function and all of the callees of
00717 // the function to not have these arguments and return values.
00718 //
00719 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
00720   // Don't modify fully live functions
00721   if (LiveFunctions.count(F))
00722     return false;
00723 
00724   // Start by computing a new prototype for the function, which is the same as
00725   // the old function, but has fewer arguments and a different return type.
00726   FunctionType *FTy = F->getFunctionType();
00727   std::vector<Type*> Params;
00728 
00729   // Keep track of if we have a live 'returned' argument
00730   bool HasLiveReturnedArg = false;
00731 
00732   // Set up to build a new list of parameter attributes.
00733   SmallVector<AttributeSet, 8> AttributesVec;
00734   const AttributeSet &PAL = F->getAttributes();
00735 
00736   // Remember which arguments are still alive.
00737   SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
00738   // Construct the new parameter list from non-dead arguments. Also construct
00739   // a new set of parameter attributes to correspond. Skip the first parameter
00740   // attribute, since that belongs to the return value.
00741   unsigned i = 0;
00742   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00743        I != E; ++I, ++i) {
00744     RetOrArg Arg = CreateArg(F, i);
00745     if (LiveValues.erase(Arg)) {
00746       Params.push_back(I->getType());
00747       ArgAlive[i] = true;
00748 
00749       // Get the original parameter attributes (skipping the first one, that is
00750       // for the return value.
00751       if (PAL.hasAttributes(i + 1)) {
00752         AttrBuilder B(PAL, i + 1);
00753         if (B.contains(Attribute::Returned))
00754           HasLiveReturnedArg = true;
00755         AttributesVec.
00756           push_back(AttributeSet::get(F->getContext(), Params.size(), B));
00757       }
00758     } else {
00759       ++NumArgumentsEliminated;
00760       DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
00761             << ") from " << F->getName() << "\n");
00762     }
00763   }
00764 
00765   // Find out the new return value.
00766   Type *RetTy = FTy->getReturnType();
00767   Type *NRetTy = NULL;
00768   unsigned RetCount = NumRetVals(F);
00769 
00770   // -1 means unused, other numbers are the new index
00771   SmallVector<int, 5> NewRetIdxs(RetCount, -1);
00772   std::vector<Type*> RetTypes;
00773 
00774   // If there is a function with a live 'returned' argument but a dead return
00775   // value, then there are two possible actions:
00776   // 1) Eliminate the return value and take off the 'returned' attribute on the
00777   //    argument.
00778   // 2) Retain the 'returned' attribute and treat the return value (but not the
00779   //    entire function) as live so that it is not eliminated.
00780   // 
00781   // It's not clear in the general case which option is more profitable because,
00782   // even in the absence of explicit uses of the return value, code generation
00783   // is free to use the 'returned' attribute to do things like eliding
00784   // save/restores of registers across calls. Whether or not this happens is
00785   // target and ABI-specific as well as depending on the amount of register
00786   // pressure, so there's no good way for an IR-level pass to figure this out.
00787   //
00788   // Fortunately, the only places where 'returned' is currently generated by
00789   // the FE are places where 'returned' is basically free and almost always a
00790   // performance win, so the second option can just be used always for now.
00791   //
00792   // This should be revisited if 'returned' is ever applied more liberally.
00793   if (RetTy->isVoidTy() || HasLiveReturnedArg) {
00794     NRetTy = RetTy;
00795   } else {
00796     StructType *STy = dyn_cast<StructType>(RetTy);
00797     if (STy)
00798       // Look at each of the original return values individually.
00799       for (unsigned i = 0; i != RetCount; ++i) {
00800         RetOrArg Ret = CreateRet(F, i);
00801         if (LiveValues.erase(Ret)) {
00802           RetTypes.push_back(STy->getElementType(i));
00803           NewRetIdxs[i] = RetTypes.size() - 1;
00804         } else {
00805           ++NumRetValsEliminated;
00806           DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
00807                 << F->getName() << "\n");
00808         }
00809       }
00810     else
00811       // We used to return a single value.
00812       if (LiveValues.erase(CreateRet(F, 0))) {
00813         RetTypes.push_back(RetTy);
00814         NewRetIdxs[0] = 0;
00815       } else {
00816         DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
00817               << "\n");
00818         ++NumRetValsEliminated;
00819       }
00820     if (RetTypes.size() > 1)
00821       // More than one return type? Return a struct with them. Also, if we used
00822       // to return a struct and didn't change the number of return values,
00823       // return a struct again. This prevents changing {something} into
00824       // something and {} into void.
00825       // Make the new struct packed if we used to return a packed struct
00826       // already.
00827       NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
00828     else if (RetTypes.size() == 1)
00829       // One return type? Just a simple value then, but only if we didn't use to
00830       // return a struct with that simple value before.
00831       NRetTy = RetTypes.front();
00832     else if (RetTypes.size() == 0)
00833       // No return types? Make it void, but only if we didn't use to return {}.
00834       NRetTy = Type::getVoidTy(F->getContext());
00835   }
00836 
00837   assert(NRetTy && "No new return type found?");
00838 
00839   // The existing function return attributes.
00840   AttributeSet RAttrs = PAL.getRetAttributes();
00841 
00842   // Remove any incompatible attributes, but only if we removed all return
00843   // values. Otherwise, ensure that we don't have any conflicting attributes
00844   // here. Currently, this should not be possible, but special handling might be
00845   // required when new return value attributes are added.
00846   if (NRetTy->isVoidTy())
00847     RAttrs =
00848       AttributeSet::get(NRetTy->getContext(), AttributeSet::ReturnIndex,
00849                         AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00850          removeAttributes(AttributeFuncs::
00851                           typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
00852                           AttributeSet::ReturnIndex));
00853   else
00854     assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00855              hasAttributes(AttributeFuncs::
00856                            typeIncompatible(NRetTy, AttributeSet::ReturnIndex),
00857                            AttributeSet::ReturnIndex) &&
00858            "Return attributes no longer compatible?");
00859 
00860   if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
00861     AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs));
00862 
00863   if (PAL.hasAttributes(AttributeSet::FunctionIndex))
00864     AttributesVec.push_back(AttributeSet::get(F->getContext(),
00865                                               PAL.getFnAttributes()));
00866 
00867   // Reconstruct the AttributesList based on the vector we constructed.
00868   AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec);
00869 
00870   // Create the new function type based on the recomputed parameters.
00871   FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
00872 
00873   // No change?
00874   if (NFTy == FTy)
00875     return false;
00876 
00877   // Create the new function body and insert it into the module...
00878   Function *NF = Function::Create(NFTy, F->getLinkage());
00879   NF->copyAttributesFrom(F);
00880   NF->setAttributes(NewPAL);
00881   // Insert the new function before the old function, so we won't be processing
00882   // it again.
00883   F->getParent()->getFunctionList().insert(F, NF);
00884   NF->takeName(F);
00885 
00886   // Loop over all of the callers of the function, transforming the call sites
00887   // to pass in a smaller number of arguments into the new function.
00888   //
00889   std::vector<Value*> Args;
00890   while (!F->use_empty()) {
00891     CallSite CS(F->user_back());
00892     Instruction *Call = CS.getInstruction();
00893 
00894     AttributesVec.clear();
00895     const AttributeSet &CallPAL = CS.getAttributes();
00896 
00897     // The call return attributes.
00898     AttributeSet RAttrs = CallPAL.getRetAttributes();
00899 
00900     // Adjust in case the function was changed to return void.
00901     RAttrs =
00902       AttributeSet::get(NF->getContext(), AttributeSet::ReturnIndex,
00903                         AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
00904         removeAttributes(AttributeFuncs::
00905                          typeIncompatible(NF->getReturnType(),
00906                                           AttributeSet::ReturnIndex),
00907                          AttributeSet::ReturnIndex));
00908     if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
00909       AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs));
00910 
00911     // Declare these outside of the loops, so we can reuse them for the second
00912     // loop, which loops the varargs.
00913     CallSite::arg_iterator I = CS.arg_begin();
00914     unsigned i = 0;
00915     // Loop over those operands, corresponding to the normal arguments to the
00916     // original function, and add those that are still alive.
00917     for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
00918       if (ArgAlive[i]) {
00919         Args.push_back(*I);
00920         // Get original parameter attributes, but skip return attributes.
00921         if (CallPAL.hasAttributes(i + 1)) {
00922           AttrBuilder B(CallPAL, i + 1);
00923           // If the return type has changed, then get rid of 'returned' on the
00924           // call site. The alternative is to make all 'returned' attributes on
00925           // call sites keep the return value alive just like 'returned'
00926           // attributes on function declaration but it's less clearly a win
00927           // and this is not an expected case anyway
00928           if (NRetTy != RetTy && B.contains(Attribute::Returned))
00929             B.removeAttribute(Attribute::Returned);
00930           AttributesVec.
00931             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00932         }
00933       }
00934 
00935     // Push any varargs arguments on the list. Don't forget their attributes.
00936     for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
00937       Args.push_back(*I);
00938       if (CallPAL.hasAttributes(i + 1)) {
00939         AttrBuilder B(CallPAL, i + 1);
00940         AttributesVec.
00941           push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00942       }
00943     }
00944 
00945     if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
00946       AttributesVec.push_back(AttributeSet::get(Call->getContext(),
00947                                                 CallPAL.getFnAttributes()));
00948 
00949     // Reconstruct the AttributesList based on the vector we constructed.
00950     AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec);
00951 
00952     Instruction *New;
00953     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00954       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00955                                Args, "", Call);
00956       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00957       cast<InvokeInst>(New)->setAttributes(NewCallPAL);
00958     } else {
00959       New = CallInst::Create(NF, Args, "", Call);
00960       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00961       cast<CallInst>(New)->setAttributes(NewCallPAL);
00962       if (cast<CallInst>(Call)->isTailCall())
00963         cast<CallInst>(New)->setTailCall();
00964     }
00965     New->setDebugLoc(Call->getDebugLoc());
00966 
00967     Args.clear();
00968 
00969     if (!Call->use_empty()) {
00970       if (New->getType() == Call->getType()) {
00971         // Return type not changed? Just replace users then.
00972         Call->replaceAllUsesWith(New);
00973         New->takeName(Call);
00974       } else if (New->getType()->isVoidTy()) {
00975         // Our return value has uses, but they will get removed later on.
00976         // Replace by null for now.
00977         if (!Call->getType()->isX86_MMXTy())
00978           Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
00979       } else {
00980         assert(RetTy->isStructTy() &&
00981                "Return type changed, but not into a void. The old return type"
00982                " must have been a struct!");
00983         Instruction *InsertPt = Call;
00984         if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00985           BasicBlock::iterator IP = II->getNormalDest()->begin();
00986           while (isa<PHINode>(IP)) ++IP;
00987           InsertPt = IP;
00988         }
00989 
00990         // We used to return a struct. Instead of doing smart stuff with all the
00991         // uses of this struct, we will just rebuild it using
00992         // extract/insertvalue chaining and let instcombine clean that up.
00993         //
00994         // Start out building up our return value from undef
00995         Value *RetVal = UndefValue::get(RetTy);
00996         for (unsigned i = 0; i != RetCount; ++i)
00997           if (NewRetIdxs[i] != -1) {
00998             Value *V;
00999             if (RetTypes.size() > 1)
01000               // We are still returning a struct, so extract the value from our
01001               // return value
01002               V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
01003                                            InsertPt);
01004             else
01005               // We are now returning a single element, so just insert that
01006               V = New;
01007             // Insert the value at the old position
01008             RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
01009           }
01010         // Now, replace all uses of the old call instruction with the return
01011         // struct we built
01012         Call->replaceAllUsesWith(RetVal);
01013         New->takeName(Call);
01014       }
01015     }
01016 
01017     // Finally, remove the old call from the program, reducing the use-count of
01018     // F.
01019     Call->eraseFromParent();
01020   }
01021 
01022   // Since we have now created the new function, splice the body of the old
01023   // function right into the new function, leaving the old rotting hulk of the
01024   // function empty.
01025   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
01026 
01027   // Loop over the argument list, transferring uses of the old arguments over to
01028   // the new arguments, also transferring over the names as well.
01029   i = 0;
01030   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
01031        I2 = NF->arg_begin(); I != E; ++I, ++i)
01032     if (ArgAlive[i]) {
01033       // If this is a live argument, move the name and users over to the new
01034       // version.
01035       I->replaceAllUsesWith(I2);
01036       I2->takeName(I);
01037       ++I2;
01038     } else {
01039       // If this argument is dead, replace any uses of it with null constants
01040       // (these are guaranteed to become unused later on).
01041       if (!I->getType()->isX86_MMXTy())
01042         I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
01043     }
01044 
01045   // If we change the return value of the function we must rewrite any return
01046   // instructions.  Check this now.
01047   if (F->getReturnType() != NF->getReturnType())
01048     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
01049       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
01050         Value *RetVal;
01051 
01052         if (NFTy->getReturnType()->isVoidTy()) {
01053           RetVal = 0;
01054         } else {
01055           assert (RetTy->isStructTy());
01056           // The original return value was a struct, insert
01057           // extractvalue/insertvalue chains to extract only the values we need
01058           // to return and insert them into our new result.
01059           // This does generate messy code, but we'll let it to instcombine to
01060           // clean that up.
01061           Value *OldRet = RI->getOperand(0);
01062           // Start out building up our return value from undef
01063           RetVal = UndefValue::get(NRetTy);
01064           for (unsigned i = 0; i != RetCount; ++i)
01065             if (NewRetIdxs[i] != -1) {
01066               ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
01067                                                               "oldret", RI);
01068               if (RetTypes.size() > 1) {
01069                 // We're still returning a struct, so reinsert the value into
01070                 // our new return value at the new index
01071 
01072                 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
01073                                                  "newret", RI);
01074               } else {
01075                 // We are now only returning a simple value, so just return the
01076                 // extracted value.
01077                 RetVal = EV;
01078               }
01079             }
01080         }
01081         // Replace the return instruction with one returning the new return
01082         // value (possibly 0 if we became void).
01083         ReturnInst::Create(F->getContext(), RetVal, RI);
01084         BB->getInstList().erase(RI);
01085       }
01086 
01087   // Patch the pointer to LLVM function in debug info descriptor.
01088   FunctionDIMap::iterator DI = FunctionDIs.find(F);
01089   if (DI != FunctionDIs.end())
01090     DI->second.replaceFunction(NF);
01091 
01092   // Now that the old function is dead, delete it.
01093   F->eraseFromParent();
01094 
01095   return true;
01096 }
01097 
01098 bool DAE::runOnModule(Module &M) {
01099   bool Changed = false;
01100 
01101   // Collect debug info descriptors for functions.
01102   CollectFunctionDIs(M);
01103 
01104   // First pass: Do a simple check to see if any functions can have their "..."
01105   // removed.  We can do this if they never call va_start.  This loop cannot be
01106   // fused with the next loop, because deleting a function invalidates
01107   // information computed while surveying other functions.
01108   DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
01109   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
01110     Function &F = *I++;
01111     if (F.getFunctionType()->isVarArg())
01112       Changed |= DeleteDeadVarargs(F);
01113   }
01114 
01115   // Second phase:loop through the module, determining which arguments are live.
01116   // We assume all arguments are dead unless proven otherwise (allowing us to
01117   // determine that dead arguments passed into recursive functions are dead).
01118   //
01119   DEBUG(dbgs() << "DAE - Determining liveness\n");
01120   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
01121     SurveyFunction(*I);
01122 
01123   // Now, remove all dead arguments and return values from each function in
01124   // turn.
01125   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
01126     // Increment now, because the function will probably get removed (ie.
01127     // replaced by a new one).
01128     Function *F = I++;
01129     Changed |= RemoveDeadStuffFromFunction(F);
01130   }
01131 
01132   // Finally, look for any unused parameters in functions with non-local
01133   // linkage and replace the passed in parameters with undef.
01134   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
01135     Function& F = *I;
01136 
01137     Changed |= RemoveDeadArgumentsFromCallers(F);
01138   }
01139 
01140   return Changed;
01141 }