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