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/CallingConv.h"
00023 #include "llvm/Constant.h"
00024 #include "llvm/DerivedTypes.h"
00025 #include "llvm/Instructions.h"
00026 #include "llvm/IntrinsicInst.h"
00027 #include "llvm/Module.h"
00028 #include "llvm/Pass.h"
00029 #include "llvm/Support/CallSite.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/ADT/SmallVector.h"
00032 #include "llvm/ADT/Statistic.h"
00033 #include "llvm/ADT/StringExtras.h"
00034 #include "llvm/Support/Compiler.h"
00035 #include <map>
00036 #include <set>
00037 using namespace llvm;
00038 
00039 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
00040 STATISTIC(NumRetValsEliminated  , "Number of unused return values removed");
00041 
00042 namespace {
00043   /// DAE - The dead argument elimination pass.
00044   ///
00045   class VISIBILITY_HIDDEN DAE : public ModulePass {
00046   public:
00047 
00048     /// Struct that represents (part of) either a return value or a function
00049     /// argument.  Used so that arguments and return values can be used
00050     /// interchangably.
00051     struct RetOrArg {
00052       RetOrArg(const Function* F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
00053                IsArg(IsArg) {}
00054       const Function *F;
00055       unsigned Idx;
00056       bool IsArg;
00057 
00058       /// Make RetOrArg comparable, so we can put it into a map.
00059       bool operator<(const RetOrArg &O) const {
00060         if (F != O.F)
00061           return F < O.F;
00062         else if (Idx != O.Idx)
00063           return Idx < O.Idx;
00064         else
00065           return IsArg < 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();
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   public:
00123     static char ID; // Pass identification, replacement for typeid
00124     DAE() : ModulePass(&ID) {}
00125     bool runOnModule(Module &M);
00126 
00127     virtual bool ShouldHackArguments() const { return false; }
00128 
00129   private:
00130     Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
00131     Liveness SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
00132                        unsigned RetValNum = 0);
00133     Liveness SurveyUses(Value *V, UseVector &MaybeLiveUses);
00134 
00135     void SurveyFunction(Function &F);
00136     void MarkValue(const RetOrArg &RA, Liveness L,
00137                    const UseVector &MaybeLiveUses);
00138     void MarkLive(const RetOrArg &RA);
00139     void MarkLive(const Function &F);
00140     void PropagateLiveness(const RetOrArg &RA);
00141     bool RemoveDeadStuffFromFunction(Function *F);
00142     bool DeleteDeadVarargs(Function &Fn);
00143   };
00144 }
00145 
00146 
00147 char DAE::ID = 0;
00148 static RegisterPass<DAE>
00149 X("deadargelim", "Dead Argument Elimination");
00150 
00151 namespace {
00152   /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
00153   /// deletes arguments to functions which are external.  This is only for use
00154   /// by bugpoint.
00155   struct DAH : public DAE {
00156     static char ID;
00157     virtual bool ShouldHackArguments() const { return true; }
00158   };
00159 }
00160 
00161 char DAH::ID = 0;
00162 static RegisterPass<DAH>
00163 Y("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
00164 
00165 /// createDeadArgEliminationPass - This pass removes arguments from functions
00166 /// which are not used by the body of the function.
00167 ///
00168 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
00169 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
00170 
00171 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
00172 /// llvm.vastart is never called, the varargs list is dead for the function.
00173 bool DAE::DeleteDeadVarargs(Function &Fn) {
00174   assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
00175   if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
00176 
00177   // Ensure that the function is only directly called.
00178   for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
00179     // If this use is anything other than a call site, give up.
00180     CallSite CS = CallSite::get(*I);
00181     Instruction *TheCall = CS.getInstruction();
00182     if (!TheCall) return false;   // Not a direct call site?
00183 
00184     // The addr of this function is passed to the call.
00185     if (!CS.isCallee(I)) return false;
00186   }
00187 
00188   // Okay, we know we can transform this function if safe.  Scan its body
00189   // looking for calls to llvm.vastart.
00190   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
00191     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00192       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00193         if (II->getIntrinsicID() == Intrinsic::vastart)
00194           return false;
00195       }
00196     }
00197   }
00198 
00199   // If we get here, there are no calls to llvm.vastart in the function body,
00200   // remove the "..." and adjust all the calls.
00201 
00202   // Start by computing a new prototype for the function, which is the same as
00203   // the old function, but doesn't have isVarArg set.
00204   const FunctionType *FTy = Fn.getFunctionType();
00205   std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
00206   FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
00207   unsigned NumArgs = Params.size();
00208 
00209   // Create the new function body and insert it into the module...
00210   Function *NF = Function::Create(NFTy, Fn.getLinkage());
00211   NF->copyAttributesFrom(&Fn);
00212   Fn.getParent()->getFunctionList().insert(&Fn, NF);
00213   NF->takeName(&Fn);
00214 
00215   // Loop over all of the callers of the function, transforming the call sites
00216   // to pass in a smaller number of arguments into the new function.
00217   //
00218   std::vector<Value*> Args;
00219   while (!Fn.use_empty()) {
00220     CallSite CS = CallSite::get(Fn.use_back());
00221     Instruction *Call = CS.getInstruction();
00222 
00223     // Pass all the same arguments.
00224     Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
00225 
00226     // Drop any attributes that were on the vararg arguments.
00227     AttrListPtr PAL = CS.getAttributes();
00228     if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
00229       SmallVector<AttributeWithIndex, 8> AttributesVec;
00230       for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
00231         AttributesVec.push_back(PAL.getSlot(i));
00232       if (Attributes FnAttrs = PAL.getFnAttributes()) 
00233         AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
00234       PAL = AttrListPtr::get(AttributesVec.begin(), AttributesVec.end());
00235     }
00236 
00237     Instruction *New;
00238     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00239       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00240                                Args.begin(), Args.end(), "", Call);
00241       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00242       cast<InvokeInst>(New)->setAttributes(PAL);
00243     } else {
00244       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
00245       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00246       cast<CallInst>(New)->setAttributes(PAL);
00247       if (cast<CallInst>(Call)->isTailCall())
00248         cast<CallInst>(New)->setTailCall();
00249     }
00250     Args.clear();
00251 
00252     if (!Call->use_empty())
00253       Call->replaceAllUsesWith(New);
00254 
00255     New->takeName(Call);
00256 
00257     // Finally, remove the old call from the program, reducing the use-count of
00258     // F.
00259     Call->eraseFromParent();
00260   }
00261 
00262   // Since we have now created the new function, splice the body of the old
00263   // function right into the new function, leaving the old rotting hulk of the
00264   // function empty.
00265   NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
00266 
00267   // Loop over the argument list, transfering uses of the old arguments over to
00268   // the new arguments, also transfering over the names as well.  While we're at
00269   // it, remove the dead arguments from the DeadArguments list.
00270   //
00271   for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
00272        I2 = NF->arg_begin(); I != E; ++I, ++I2) {
00273     // Move the name and users over to the new version.
00274     I->replaceAllUsesWith(I2);
00275     I2->takeName(I);
00276   }
00277 
00278   // Finally, nuke the old function.
00279   Fn.eraseFromParent();
00280   return true;
00281 }
00282 
00283 /// Convenience function that returns the number of return values. It returns 0
00284 /// for void functions and 1 for functions not returning a struct. It returns
00285 /// the number of struct elements for functions returning a struct.
00286 static unsigned NumRetVals(const Function *F) {
00287   if (F->getReturnType() == Type::VoidTy)
00288     return 0;
00289   else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType()))
00290     return STy->getNumElements();
00291   else
00292     return 1;
00293 }
00294 
00295 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
00296 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
00297 /// liveness of Use.
00298 DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
00299   // We're live if our use or its Function is already marked as live.
00300   if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
00301     return Live;
00302 
00303   // We're maybe live otherwise, but remember that we must become live if
00304   // Use becomes live.
00305   MaybeLiveUses.push_back(Use);
00306   return MaybeLive;
00307 }
00308 
00309 
00310 /// SurveyUse - This looks at a single use of an argument or return value
00311 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
00312 /// if it causes the used value to become MaybeAlive.
00313 ///
00314 /// RetValNum is the return value number to use when this use is used in a
00315 /// return instruction. This is used in the recursion, you should always leave
00316 /// it at 0.
00317 DAE::Liveness DAE::SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
00318                              unsigned RetValNum) {
00319     Value *V = *U;
00320     if (ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
00321       // The value is returned from a function. It's only live when the
00322       // function's return value is live. We use RetValNum here, for the case
00323       // that U is really a use of an insertvalue instruction that uses the
00324       // orginal Use.
00325       RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
00326       // We might be live, depending on the liveness of Use.
00327       return MarkIfNotLive(Use, MaybeLiveUses);
00328     }
00329     if (InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
00330       if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
00331           && IV->hasIndices())
00332         // The use we are examining is inserted into an aggregate. Our liveness
00333         // depends on all uses of that aggregate, but if it is used as a return
00334         // value, only index at which we were inserted counts.
00335         RetValNum = *IV->idx_begin();
00336 
00337       // Note that if we are used as the aggregate operand to the insertvalue,
00338       // we don't change RetValNum, but do survey all our uses.
00339 
00340       Liveness Result = MaybeLive;
00341       for (Value::use_iterator I = IV->use_begin(),
00342            E = V->use_end(); I != E; ++I) {
00343         Result = SurveyUse(I, MaybeLiveUses, RetValNum);
00344         if (Result == Live)
00345           break;
00346       }
00347       return Result;
00348     }
00349     CallSite CS = CallSite::get(V);
00350     if (CS.getInstruction()) {
00351       Function *F = CS.getCalledFunction();
00352       if (F) {
00353         // Used in a direct call.
00354   
00355         // Find the argument number. We know for sure that this use is an
00356         // argument, since if it was the function argument this would be an
00357         // indirect call and the we know can't be looking at a value of the
00358         // label type (for the invoke instruction).
00359         unsigned ArgNo = CS.getArgumentNo(U.getOperandNo());
00360 
00361         if (ArgNo >= F->getFunctionType()->getNumParams())
00362           // The value is passed in through a vararg! Must be live.
00363           return Live;
00364 
00365         assert(CS.getArgument(ArgNo) 
00366                == CS.getInstruction()->getOperand(U.getOperandNo()) 
00367                && "Argument is not where we expected it");
00368 
00369         // Value passed to a normal call. It's only live when the corresponding
00370         // argument to the called function turns out live.
00371         RetOrArg Use = CreateArg(F, ArgNo);
00372         return MarkIfNotLive(Use, MaybeLiveUses);
00373       }
00374     }
00375     // Used in any other way? Value must be live.
00376     return Live;
00377 }
00378 
00379 /// SurveyUses - This looks at all the uses of the given value
00380 /// Returns the Liveness deduced from the uses of this value.
00381 ///
00382 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
00383 /// the result is Live, MaybeLiveUses might be modified but its content should
00384 /// be ignored (since it might not be complete).
00385 DAE::Liveness DAE::SurveyUses(Value *V, UseVector &MaybeLiveUses) {
00386   // Assume it's dead (which will only hold if there are no uses at all..).
00387   Liveness Result = MaybeLive;
00388   // Check each use.
00389   for (Value::use_iterator I = V->use_begin(),
00390        E = V->use_end(); I != E; ++I) {
00391     Result = SurveyUse(I, MaybeLiveUses);
00392     if (Result == Live)
00393       break;
00394   }
00395   return Result;
00396 }
00397 
00398 // SurveyFunction - This performs the initial survey of the specified function,
00399 // checking out whether or not it uses any of its incoming arguments or whether
00400 // any callers use the return value.  This fills in the LiveValues set and Uses
00401 // map.
00402 //
00403 // We consider arguments of non-internal functions to be intrinsically alive as
00404 // well as arguments to functions which have their "address taken".
00405 //
00406 void DAE::SurveyFunction(Function &F) {
00407   unsigned RetCount = NumRetVals(&F);
00408   // Assume all return values are dead
00409   typedef SmallVector<Liveness, 5> RetVals;
00410   RetVals RetValLiveness(RetCount, MaybeLive);
00411 
00412   typedef SmallVector<UseVector, 5> RetUses;
00413   // These vectors map each return value to the uses that make it MaybeLive, so
00414   // we can add those to the Uses map if the return value really turns out to be
00415   // MaybeLive. Initialized to a list of RetCount empty lists.
00416   RetUses MaybeLiveRetUses(RetCount);
00417 
00418   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00419     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
00420       if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
00421           != F.getFunctionType()->getReturnType()) {
00422         // We don't support old style multiple return values.
00423         MarkLive(F);
00424         return;
00425       }
00426 
00427   if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
00428     MarkLive(F);
00429     return;
00430   }
00431 
00432   DOUT << "DAE - Inspecting callers for fn: " << F.getName() << "\n";
00433   // Keep track of the number of live retvals, so we can skip checks once all
00434   // of them turn out to be live.
00435   unsigned NumLiveRetVals = 0;
00436   const Type *STy = dyn_cast<StructType>(F.getReturnType());
00437   // Loop all uses of the function.
00438   for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
00439     // If the function is PASSED IN as an argument, its address has been
00440     // taken.
00441     CallSite CS = CallSite::get(*I);
00442     if (!CS.getInstruction() || !CS.isCallee(I)) {
00443       MarkLive(F);
00444       return;
00445     }
00446 
00447     // If this use is anything other than a call site, the function is alive.
00448     Instruction *TheCall = CS.getInstruction();
00449     if (!TheCall) {   // Not a direct call site?
00450       MarkLive(F);
00451       return;
00452     }
00453 
00454     // If we end up here, we are looking at a direct call to our function.
00455 
00456     // Now, check how our return value(s) is/are used in this caller. Don't
00457     // bother checking return values if all of them are live already.
00458     if (NumLiveRetVals != RetCount) {
00459       if (STy) {
00460         // Check all uses of the return value.
00461         for (Value::use_iterator I = TheCall->use_begin(),
00462              E = TheCall->use_end(); I != E; ++I) {
00463           ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
00464           if (Ext && Ext->hasIndices()) {
00465             // This use uses a part of our return value, survey the uses of
00466             // that part and store the results for this index only.
00467             unsigned Idx = *Ext->idx_begin();
00468             if (RetValLiveness[Idx] != Live) {
00469               RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
00470               if (RetValLiveness[Idx] == Live)
00471                 NumLiveRetVals++;
00472             }
00473           } else {
00474             // Used by something else than extractvalue. Mark all return
00475             // values as live.
00476             for (unsigned i = 0; i != RetCount; ++i )
00477               RetValLiveness[i] = Live;
00478             NumLiveRetVals = RetCount;
00479             break;
00480           }
00481         }
00482       } else {
00483         // Single return value
00484         RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
00485         if (RetValLiveness[0] == Live)
00486           NumLiveRetVals = RetCount;
00487       }
00488     }
00489   }
00490 
00491   // Now we've inspected all callers, record the liveness of our return values.
00492   for (unsigned i = 0; i != RetCount; ++i)
00493     MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
00494 
00495   DOUT << "DAE - Inspecting args for fn: " << F.getName() << "\n";
00496 
00497   // Now, check all of our arguments.
00498   unsigned i = 0;
00499   UseVector MaybeLiveArgUses;
00500   for (Function::arg_iterator AI = F.arg_begin(),
00501        E = F.arg_end(); AI != E; ++AI, ++i) {
00502     // See what the effect of this use is (recording any uses that cause
00503     // MaybeLive in MaybeLiveArgUses).
00504     Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
00505     // Mark the result.
00506     MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
00507     // Clear the vector again for the next iteration.
00508     MaybeLiveArgUses.clear();
00509   }
00510 }
00511 
00512 /// MarkValue - This function marks the liveness of RA depending on L. If L is
00513 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
00514 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
00515 /// live later on.
00516 void DAE::MarkValue(const RetOrArg &RA, Liveness L,
00517                     const UseVector &MaybeLiveUses) {
00518   switch (L) {
00519     case Live: MarkLive(RA); break;
00520     case MaybeLive:
00521     {
00522       // Note any uses of this value, so this return value can be
00523       // marked live whenever one of the uses becomes live.
00524       for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
00525            UE = MaybeLiveUses.end(); UI != UE; ++UI)
00526         Uses.insert(std::make_pair(*UI, RA));
00527       break;
00528     }
00529   }
00530 }
00531 
00532 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
00533 /// changed in any way. Additionally,
00534 /// mark any values that are used as this function's parameters or by its return
00535 /// values (according to Uses) live as well.
00536 void DAE::MarkLive(const Function &F) {
00537     DOUT << "DAE - Intrinsically live fn: " << F.getName() << "\n";
00538     // Mark the function as live.
00539     LiveFunctions.insert(&F);
00540     // Mark all arguments as live.
00541     for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
00542       PropagateLiveness(CreateArg(&F, i));
00543     // Mark all return values as live.
00544     for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
00545       PropagateLiveness(CreateRet(&F, i));
00546 }
00547 
00548 /// MarkLive - Mark the given return value or argument as live. Additionally,
00549 /// mark any values that are used by this value (according to Uses) live as
00550 /// well.
00551 void DAE::MarkLive(const RetOrArg &RA) {
00552   if (LiveFunctions.count(RA.F))
00553     return; // Function was already marked Live.
00554 
00555   if (!LiveValues.insert(RA).second)
00556     return; // We were already marked Live.
00557 
00558   DOUT << "DAE - Marking " << RA.getDescription() << " live\n";
00559   PropagateLiveness(RA);
00560 }
00561 
00562 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
00563 /// to any other values it uses (according to Uses).
00564 void DAE::PropagateLiveness(const RetOrArg &RA) {
00565   // We don't use upper_bound (or equal_range) here, because our recursive call
00566   // to ourselves is likely to cause the upper_bound (which is the first value
00567   // not belonging to RA) to become erased and the iterator invalidated.
00568   UseMap::iterator Begin = Uses.lower_bound(RA);
00569   UseMap::iterator E = Uses.end();
00570   UseMap::iterator I;
00571   for (I = Begin; I != E && I->first == RA; ++I)
00572     MarkLive(I->second);
00573 
00574   // Erase RA from the Uses map (from the lower bound to wherever we ended up
00575   // after the loop).
00576   Uses.erase(Begin, I);
00577 }
00578 
00579 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
00580 // that are not in LiveValues. Transform the function and all of the callees of
00581 // the function to not have these arguments and return values.
00582 //
00583 bool DAE::RemoveDeadStuffFromFunction(Function *F) {
00584   // Don't modify fully live functions
00585   if (LiveFunctions.count(F))
00586     return false;
00587 
00588   // Start by computing a new prototype for the function, which is the same as
00589   // the old function, but has fewer arguments and a different return type.
00590   const FunctionType *FTy = F->getFunctionType();
00591   std::vector<const Type*> Params;
00592 
00593   // Set up to build a new list of parameter attributes.
00594   SmallVector<AttributeWithIndex, 8> AttributesVec;
00595   const AttrListPtr &PAL = F->getAttributes();
00596 
00597   // The existing function return attributes.
00598   Attributes RAttrs = PAL.getRetAttributes();
00599   Attributes FnAttrs = PAL.getFnAttributes();
00600 
00601   // Find out the new return value.
00602 
00603   const Type *RetTy = FTy->getReturnType();
00604   const Type *NRetTy = NULL;
00605   unsigned RetCount = NumRetVals(F);
00606   // -1 means unused, other numbers are the new index
00607   SmallVector<int, 5> NewRetIdxs(RetCount, -1);
00608   std::vector<const Type*> RetTypes;
00609   if (RetTy == Type::VoidTy) {
00610     NRetTy = Type::VoidTy;
00611   } else {
00612     const StructType *STy = dyn_cast<StructType>(RetTy);
00613     if (STy)
00614       // Look at each of the original return values individually.
00615       for (unsigned i = 0; i != RetCount; ++i) {
00616         RetOrArg Ret = CreateRet(F, i);
00617         if (LiveValues.erase(Ret)) {
00618           RetTypes.push_back(STy->getElementType(i));
00619           NewRetIdxs[i] = RetTypes.size() - 1;
00620         } else {
00621           ++NumRetValsEliminated;
00622           DOUT << "DAE - Removing return value " << i << " from "
00623                << F->getNameStart() << "\n";
00624         }
00625       }
00626     else
00627       // We used to return a single value.
00628       if (LiveValues.erase(CreateRet(F, 0))) {
00629         RetTypes.push_back(RetTy);
00630         NewRetIdxs[0] = 0;
00631       } else {
00632         DOUT << "DAE - Removing return value from " << F->getNameStart()
00633              << "\n";
00634         ++NumRetValsEliminated;
00635       }
00636     if (RetTypes.size() > 1)
00637       // More than one return type? Return a struct with them. Also, if we used
00638       // to return a struct and didn't change the number of return values,
00639       // return a struct again. This prevents changing {something} into
00640       // something and {} into void.
00641       // Make the new struct packed if we used to return a packed struct
00642       // already.
00643       NRetTy = StructType::get(RetTypes, STy->isPacked());
00644     else if (RetTypes.size() == 1)
00645       // One return type? Just a simple value then, but only if we didn't use to
00646       // return a struct with that simple value before.
00647       NRetTy = RetTypes.front();
00648     else if (RetTypes.size() == 0)
00649       // No return types? Make it void, but only if we didn't use to return {}.
00650       NRetTy = Type::VoidTy;
00651   }
00652 
00653   assert(NRetTy && "No new return type found?");
00654 
00655   // Remove any incompatible attributes, but only if we removed all return
00656   // values. Otherwise, ensure that we don't have any conflicting attributes
00657   // here. Currently, this should not be possible, but special handling might be
00658   // required when new return value attributes are added.
00659   if (NRetTy == Type::VoidTy)
00660     RAttrs &= ~Attribute::typeIncompatible(NRetTy);
00661   else
00662     assert((RAttrs & Attribute::typeIncompatible(NRetTy)) == 0 
00663            && "Return attributes no longer compatible?");
00664 
00665   if (RAttrs)
00666     AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
00667 
00668   // Remember which arguments are still alive.
00669   SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
00670   // Construct the new parameter list from non-dead arguments. Also construct
00671   // a new set of parameter attributes to correspond. Skip the first parameter
00672   // attribute, since that belongs to the return value.
00673   unsigned i = 0;
00674   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00675        I != E; ++I, ++i) {
00676     RetOrArg Arg = CreateArg(F, i);
00677     if (LiveValues.erase(Arg)) {
00678       Params.push_back(I->getType());
00679       ArgAlive[i] = true;
00680 
00681       // Get the original parameter attributes (skipping the first one, that is
00682       // for the return value.
00683       if (Attributes Attrs = PAL.getParamAttributes(i + 1))
00684         AttributesVec.push_back(AttributeWithIndex::get(Params.size(), Attrs));
00685     } else {
00686       ++NumArgumentsEliminated;
00687       DOUT << "DAE - Removing argument " << i << " (" << I->getNameStart()
00688            << ") from " << F->getNameStart() << "\n";
00689     }
00690   }
00691 
00692   if (FnAttrs != Attribute::None) 
00693     AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
00694 
00695   // Reconstruct the AttributesList based on the vector we constructed.
00696   AttrListPtr NewPAL = AttrListPtr::get(AttributesVec.begin(), AttributesVec.end());
00697 
00698   // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
00699   // have zero fixed arguments.
00700   //
00701   // Note that we apply this hack for a vararg fuction that does not have any
00702   // arguments anymore, but did have them before (so don't bother fixing
00703   // functions that were already broken wrt CWriter).
00704   bool ExtraArgHack = false;
00705   if (Params.empty() && FTy->isVarArg() && FTy->getNumParams() != 0) {
00706     ExtraArgHack = true;
00707     Params.push_back(Type::Int32Ty);
00708   }
00709 
00710   // Create the new function type based on the recomputed parameters.
00711   FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
00712 
00713   // No change?
00714   if (NFTy == FTy)
00715     return false;
00716 
00717   // Create the new function body and insert it into the module...
00718   Function *NF = Function::Create(NFTy, F->getLinkage());
00719   NF->copyAttributesFrom(F);
00720   NF->setAttributes(NewPAL);
00721   // Insert the new function before the old function, so we won't be processing
00722   // it again.
00723   F->getParent()->getFunctionList().insert(F, NF);
00724   NF->takeName(F);
00725 
00726   // Loop over all of the callers of the function, transforming the call sites
00727   // to pass in a smaller number of arguments into the new function.
00728   //
00729   std::vector<Value*> Args;
00730   while (!F->use_empty()) {
00731     CallSite CS = CallSite::get(F->use_back());
00732     Instruction *Call = CS.getInstruction();
00733 
00734     AttributesVec.clear();
00735     const AttrListPtr &CallPAL = CS.getAttributes();
00736 
00737     // The call return attributes.
00738     Attributes RAttrs = CallPAL.getRetAttributes();
00739     Attributes FnAttrs = CallPAL.getFnAttributes();
00740     // Adjust in case the function was changed to return void.
00741     RAttrs &= ~Attribute::typeIncompatible(NF->getReturnType());
00742     if (RAttrs)
00743       AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
00744 
00745     // Declare these outside of the loops, so we can reuse them for the second
00746     // loop, which loops the varargs.
00747     CallSite::arg_iterator I = CS.arg_begin();
00748     unsigned i = 0;
00749     // Loop over those operands, corresponding to the normal arguments to the
00750     // original function, and add those that are still alive.
00751     for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
00752       if (ArgAlive[i]) {
00753         Args.push_back(*I);
00754         // Get original parameter attributes, but skip return attributes.
00755         if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
00756           AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
00757       }
00758 
00759     if (ExtraArgHack)
00760       Args.push_back(UndefValue::get(Type::Int32Ty));
00761 
00762     // Push any varargs arguments on the list. Don't forget their attributes.
00763     for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
00764       Args.push_back(*I);
00765       if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
00766         AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
00767     }
00768 
00769     if (FnAttrs != Attribute::None)
00770       AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
00771 
00772     // Reconstruct the AttributesList based on the vector we constructed.
00773     AttrListPtr NewCallPAL = AttrListPtr::get(AttributesVec.begin(),
00774                                               AttributesVec.end());
00775 
00776     Instruction *New;
00777     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00778       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00779                                Args.begin(), Args.end(), "", Call);
00780       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00781       cast<InvokeInst>(New)->setAttributes(NewCallPAL);
00782     } else {
00783       New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
00784       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00785       cast<CallInst>(New)->setAttributes(NewCallPAL);
00786       if (cast<CallInst>(Call)->isTailCall())
00787         cast<CallInst>(New)->setTailCall();
00788     }
00789     Args.clear();
00790 
00791     if (!Call->use_empty()) {
00792       if (New->getType() == Call->getType()) {
00793         // Return type not changed? Just replace users then.
00794         Call->replaceAllUsesWith(New);
00795         New->takeName(Call);
00796       } else if (New->getType() == Type::VoidTy) {
00797         // Our return value has uses, but they will get removed later on.
00798         // Replace by null for now.
00799         Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
00800       } else {
00801         assert(isa<StructType>(RetTy) && "Return type changed, but not into a"
00802                                          "void. The old return type must have"
00803                                          "been a struct!");
00804         // We used to return a struct. Instead of doing smart stuff with all the
00805         // uses of this struct, we will just rebuild it using
00806         // extract/insertvalue chaining and let instcombine clean that up.
00807         //
00808         // Start out building up our return value from undef
00809         Value *RetVal = llvm::UndefValue::get(RetTy);
00810         for (unsigned i = 0; i != RetCount; ++i)
00811           if (NewRetIdxs[i] != -1) {
00812             Value *V;
00813             if (RetTypes.size() > 1)
00814               // We are still returning a struct, so extract the value from our
00815               // return value
00816               V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret", Call);
00817             else
00818               // We are now returning a single element, so just insert that
00819               V = New;
00820             // Insert the value at the old position
00821             RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", Call);
00822           }
00823         // Now, replace all uses of the old call instruction with the return
00824         // struct we built
00825         Call->replaceAllUsesWith(RetVal);
00826         New->takeName(Call);
00827       }
00828     }
00829 
00830     // Finally, remove the old call from the program, reducing the use-count of
00831     // F.
00832     Call->eraseFromParent();
00833   }
00834 
00835   // Since we have now created the new function, splice the body of the old
00836   // function right into the new function, leaving the old rotting hulk of the
00837   // function empty.
00838   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
00839 
00840   // Loop over the argument list, transfering uses of the old arguments over to
00841   // the new arguments, also transfering over the names as well.
00842   i = 0;
00843   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
00844        I2 = NF->arg_begin(); I != E; ++I, ++i)
00845     if (ArgAlive[i]) {
00846       // If this is a live argument, move the name and users over to the new
00847       // version.
00848       I->replaceAllUsesWith(I2);
00849       I2->takeName(I);
00850       ++I2;
00851     } else {
00852       // If this argument is dead, replace any uses of it with null constants
00853       // (these are guaranteed to become unused later on).
00854       I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
00855     }
00856 
00857   // If we change the return value of the function we must rewrite any return
00858   // instructions.  Check this now.
00859   if (F->getReturnType() != NF->getReturnType())
00860     for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
00861       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
00862         Value *RetVal;
00863 
00864         if (NFTy->getReturnType() == Type::VoidTy) {
00865           RetVal = 0;
00866         } else {
00867           assert (isa<StructType>(RetTy));
00868           // The original return value was a struct, insert
00869           // extractvalue/insertvalue chains to extract only the values we need
00870           // to return and insert them into our new result.
00871           // This does generate messy code, but we'll let it to instcombine to
00872           // clean that up.
00873           Value *OldRet = RI->getOperand(0);
00874           // Start out building up our return value from undef
00875           RetVal = llvm::UndefValue::get(NRetTy);
00876           for (unsigned i = 0; i != RetCount; ++i)
00877             if (NewRetIdxs[i] != -1) {
00878               ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
00879                                                               "oldret", RI);
00880               if (RetTypes.size() > 1) {
00881                 // We're still returning a struct, so reinsert the value into
00882                 // our new return value at the new index
00883 
00884                 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
00885                                                  "newret", RI);
00886               } else {
00887                 // We are now only returning a simple value, so just return the
00888                 // extracted value.
00889                 RetVal = EV;
00890               }
00891             }
00892         }
00893         // Replace the return instruction with one returning the new return
00894         // value (possibly 0 if we became void).
00895         ReturnInst::Create(RetVal, RI);
00896         BB->getInstList().erase(RI);
00897       }
00898 
00899   // Now that the old function is dead, delete it.
00900   F->eraseFromParent();
00901 
00902   return true;
00903 }
00904 
00905 bool DAE::runOnModule(Module &M) {
00906   bool Changed = false;
00907 
00908   // First pass: Do a simple check to see if any functions can have their "..."
00909   // removed.  We can do this if they never call va_start.  This loop cannot be
00910   // fused with the next loop, because deleting a function invalidates
00911   // information computed while surveying other functions.
00912   DOUT << "DAE - Deleting dead varargs\n";
00913   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
00914     Function &F = *I++;
00915     if (F.getFunctionType()->isVarArg())
00916       Changed |= DeleteDeadVarargs(F);
00917   }
00918 
00919   // Second phase:loop through the module, determining which arguments are live.
00920   // We assume all arguments are dead unless proven otherwise (allowing us to
00921   // determine that dead arguments passed into recursive functions are dead).
00922   //
00923   DOUT << "DAE - Determining liveness\n";
00924   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00925     SurveyFunction(*I);
00926   
00927   // Now, remove all dead arguments and return values from each function in
00928   // turn
00929   for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
00930     // Increment now, because the function will probably get removed (ie
00931     // replaced by a new one).
00932     Function *F = I++;
00933     Changed |= RemoveDeadStuffFromFunction(F);
00934   }
00935   return Changed;
00936 }