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