1 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass deletes dead arguments from internal functions. Dead argument
11 // elimination removes arguments which are directly dead, as well as arguments
12 // only passed into function calls as dead arguments of other functions. This
13 // pass also deletes dead arguments in a similar way.
15 // This pass is often useful as a cleanup pass to run after aggressive
16 // interprocedural passes, which add possibly-dead arguments.
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "deadargelim"
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constant.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Module.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
38 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
39 STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
42 /// DAE - The dead argument elimination pass.
44 class VISIBILITY_HIDDEN DAE : public ModulePass {
45 /// Liveness enum - During our initial pass over the program, we determine
46 /// that things are either definately alive, definately dead, or in need of
47 /// interprocedural analysis (MaybeLive).
49 enum Liveness { Live, MaybeLive, Dead };
51 /// LiveArguments, MaybeLiveArguments, DeadArguments - These sets contain
52 /// all of the arguments in the program. The Dead set contains arguments
53 /// which are completely dead (never used in the function). The MaybeLive
54 /// set contains arguments which are only passed into other function calls,
55 /// thus may be live and may be dead. The Live set contains arguments which
56 /// are known to be alive.
58 std::set<Argument*> DeadArguments, MaybeLiveArguments, LiveArguments;
60 /// DeadRetVal, MaybeLiveRetVal, LifeRetVal - These sets contain all of the
61 /// functions in the program. The Dead set contains functions whose return
62 /// value is known to be dead. The MaybeLive set contains functions whose
63 /// return values are only used by return instructions, and the Live set
64 /// contains functions whose return values are used, functions that are
65 /// external, and functions that already return void.
67 std::set<Function*> DeadRetVal, MaybeLiveRetVal, LiveRetVal;
69 /// InstructionsToInspect - As we mark arguments and return values
70 /// MaybeLive, we keep track of which instructions could make the values
71 /// live here. Once the entire program has had the return value and
72 /// arguments analyzed, this set is scanned to promote the MaybeLive objects
73 /// to be Live if they really are used.
74 std::vector<Instruction*> InstructionsToInspect;
76 /// CallSites - Keep track of the call sites of functions that have
77 /// MaybeLive arguments or return values.
78 std::multimap<Function*, CallSite> CallSites;
81 static char ID; // Pass identification, replacement for typeid
82 DAE() : ModulePass((intptr_t)&ID) {}
83 bool runOnModule(Module &M);
85 virtual bool ShouldHackArguments() const { return false; }
88 Liveness getArgumentLiveness(const Argument &A);
89 bool isMaybeLiveArgumentNowLive(Argument *Arg);
91 bool DeleteDeadVarargs(Function &Fn);
92 void SurveyFunction(Function &Fn);
94 void MarkArgumentLive(Argument *Arg);
95 void MarkRetValLive(Function *F);
96 void MarkReturnInstArgumentLive(ReturnInst *RI);
98 void RemoveDeadArgumentsFromFunction(Function *F);
103 static RegisterPass<DAE>
104 X("deadargelim", "Dead Argument Elimination");
107 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
108 /// deletes arguments to functions which are external. This is only for use
110 struct DAH : public DAE {
112 virtual bool ShouldHackArguments() const { return true; }
117 static RegisterPass<DAH>
118 Y("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
120 /// createDeadArgEliminationPass - This pass removes arguments from functions
121 /// which are not used by the body of the function.
123 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
124 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
126 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
127 /// llvm.vastart is never called, the varargs list is dead for the function.
128 bool DAE::DeleteDeadVarargs(Function &Fn) {
129 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
130 if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
132 // Ensure that the function is only directly called.
133 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
134 // If this use is anything other than a call site, give up.
135 CallSite CS = CallSite::get(*I);
136 Instruction *TheCall = CS.getInstruction();
137 if (!TheCall) return false; // Not a direct call site?
139 // The addr of this function is passed to the call.
140 if (I.getOperandNo() != 0) return false;
143 // Okay, we know we can transform this function if safe. Scan its body
144 // looking for calls to llvm.vastart.
145 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
146 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
147 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
148 if (II->getIntrinsicID() == Intrinsic::vastart)
154 // If we get here, there are no calls to llvm.vastart in the function body,
155 // remove the "..." and adjust all the calls.
157 // Start by computing a new prototype for the function, which is the same as
158 // the old function, but has fewer arguments.
159 const FunctionType *FTy = Fn.getFunctionType();
160 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
161 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
162 unsigned NumArgs = Params.size();
164 // Create the new function body and insert it into the module...
165 Function *NF = Function::Create(NFTy, Fn.getLinkage());
166 NF->setCallingConv(Fn.getCallingConv());
167 NF->setParamAttrs(Fn.getParamAttrs());
168 if (Fn.hasCollector())
169 NF->setCollector(Fn.getCollector());
170 Fn.getParent()->getFunctionList().insert(&Fn, NF);
173 // Loop over all of the callers of the function, transforming the call sites
174 // to pass in a smaller number of arguments into the new function.
176 std::vector<Value*> Args;
177 while (!Fn.use_empty()) {
178 CallSite CS = CallSite::get(Fn.use_back());
179 Instruction *Call = CS.getInstruction();
181 // Pass all the same arguments.
182 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
184 // Drop any attributes that were on the vararg arguments.
185 PAListPtr PAL = CS.getParamAttrs();
186 if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
187 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
188 for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
189 ParamAttrsVec.push_back(PAL.getSlot(i));
190 PAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
194 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
195 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
196 Args.begin(), Args.end(), "", Call);
197 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
198 cast<InvokeInst>(New)->setParamAttrs(PAL);
200 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
201 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
202 cast<CallInst>(New)->setParamAttrs(PAL);
203 if (cast<CallInst>(Call)->isTailCall())
204 cast<CallInst>(New)->setTailCall();
208 if (!Call->use_empty())
209 Call->replaceAllUsesWith(New);
213 // Finally, remove the old call from the program, reducing the use-count of
215 Call->eraseFromParent();
218 // Since we have now created the new function, splice the body of the old
219 // function right into the new function, leaving the old rotting hulk of the
221 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
223 // Loop over the argument list, transfering uses of the old arguments over to
224 // the new arguments, also transfering over the names as well. While we're at
225 // it, remove the dead arguments from the DeadArguments list.
227 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
228 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
229 // Move the name and users over to the new version.
230 I->replaceAllUsesWith(I2);
234 // Finally, nuke the old function.
235 Fn.eraseFromParent();
240 static inline bool CallPassesValueThoughVararg(Instruction *Call,
242 CallSite CS = CallSite::get(Call);
243 const Type *CalledValueTy = CS.getCalledValue()->getType();
244 const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
245 unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
246 for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
247 AI != CS.arg_end(); ++AI)
248 if (AI->get() == Arg)
253 // getArgumentLiveness - Inspect an argument, determining if is known Live
254 // (used in a computation), MaybeLive (only passed as an argument to a call), or
256 DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
257 const Function *F = A.getParent();
259 // If this is the return value of a struct function, it's not really dead.
260 if (F->hasStructRetAttr() && &*(F->arg_begin()) == &A)
263 if (A.use_empty()) // First check, directly dead?
266 // Scan through all of the uses, looking for non-argument passing uses.
267 for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
268 // Return instructions do not immediately effect liveness.
269 if (isa<ReturnInst>(*I))
272 CallSite CS = CallSite::get(const_cast<User*>(*I));
273 if (!CS.getInstruction()) {
274 // If its used by something that is not a call or invoke, it's alive!
277 // If it's an indirect call, mark it alive...
278 Function *Callee = CS.getCalledFunction();
279 if (!Callee) return Live;
281 // Check to see if it's passed through a va_arg area: if so, we cannot
283 if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
284 return Live; // If passed through va_arg area, we cannot remove it
287 return MaybeLive; // It must be used, but only as argument to a function
291 // SurveyFunction - This performs the initial survey of the specified function,
292 // checking out whether or not it uses any of its incoming arguments or whether
293 // any callers use the return value. This fills in the
294 // (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
296 // We consider arguments of non-internal functions to be intrinsically alive as
297 // well as arguments to functions which have their "address taken".
299 void DAE::SurveyFunction(Function &F) {
300 bool FunctionIntrinsicallyLive = false;
301 Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
303 if (!F.hasInternalLinkage() &&
304 (!ShouldHackArguments() || F.isIntrinsic()))
305 FunctionIntrinsicallyLive = true;
307 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
308 // If this use is anything other than a call site, the function is alive.
309 CallSite CS = CallSite::get(*I);
310 Instruction *TheCall = CS.getInstruction();
311 if (!TheCall) { // Not a direct call site?
312 FunctionIntrinsicallyLive = true;
316 // Check to see if the return value is used...
317 if (RetValLiveness != Live)
318 for (Value::use_iterator I = TheCall->use_begin(),
319 E = TheCall->use_end(); I != E; ++I)
320 if (isa<ReturnInst>(cast<Instruction>(*I))) {
321 RetValLiveness = MaybeLive;
322 } else if (isa<CallInst>(cast<Instruction>(*I)) ||
323 isa<InvokeInst>(cast<Instruction>(*I))) {
324 if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
325 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
326 RetValLiveness = Live;
329 RetValLiveness = MaybeLive;
332 RetValLiveness = Live;
336 // If the function is PASSED IN as an argument, its address has been taken
337 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
339 if (AI->get() == &F) {
340 FunctionIntrinsicallyLive = true;
343 if (FunctionIntrinsicallyLive) break;
346 if (FunctionIntrinsicallyLive) {
347 DOUT << " Intrinsically live fn: " << F.getName() << "\n";
348 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
350 LiveArguments.insert(AI);
351 LiveRetVal.insert(&F);
355 switch (RetValLiveness) {
356 case Live: LiveRetVal.insert(&F); break;
357 case MaybeLive: MaybeLiveRetVal.insert(&F); break;
358 case Dead: DeadRetVal.insert(&F); break;
361 DOUT << " Inspecting args for fn: " << F.getName() << "\n";
363 // If it is not intrinsically alive, we know that all users of the
364 // function are call sites. Mark all of the arguments live which are
365 // directly used, and keep track of all of the call sites of this function
366 // if there are any arguments we assume that are dead.
368 bool AnyMaybeLiveArgs = false;
369 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
371 switch (getArgumentLiveness(*AI)) {
373 DOUT << " Arg live by use: " << AI->getName() << "\n";
374 LiveArguments.insert(AI);
377 DOUT << " Arg definitely dead: " << AI->getName() <<"\n";
378 DeadArguments.insert(AI);
381 DOUT << " Arg only passed to calls: " << AI->getName() << "\n";
382 AnyMaybeLiveArgs = true;
383 MaybeLiveArguments.insert(AI);
387 // If there are any "MaybeLive" arguments, we need to check callees of
388 // this function when/if they become alive. Record which functions are
390 if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
391 for (Value::use_iterator I = F.use_begin(), E = F.use_end();
393 if (AnyMaybeLiveArgs)
394 CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
396 if (RetValLiveness == MaybeLive)
397 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
399 InstructionsToInspect.push_back(cast<Instruction>(*UI));
403 // isMaybeLiveArgumentNowLive - Check to see if Arg is alive. At this point, we
404 // know that the only uses of Arg are to be passed in as an argument to a
405 // function call or return. Check to see if the formal argument passed in is in
406 // the LiveArguments set. If so, return true.
408 bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
409 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
410 if (isa<ReturnInst>(*I)) {
411 if (LiveRetVal.count(Arg->getParent())) return true;
415 CallSite CS = CallSite::get(*I);
417 // We know that this can only be used for direct calls...
418 Function *Callee = CS.getCalledFunction();
420 // Loop over all of the arguments (because Arg may be passed into the call
421 // multiple times) and check to see if any are now alive...
422 CallSite::arg_iterator CSAI = CS.arg_begin();
423 for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
424 AI != E; ++AI, ++CSAI)
425 // If this is the argument we are looking for, check to see if it's alive
426 if (*CSAI == Arg && LiveArguments.count(AI))
432 /// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
433 /// Mark it live in the specified sets and recursively mark arguments in callers
434 /// live that are needed to pass in a value.
436 void DAE::MarkArgumentLive(Argument *Arg) {
437 std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
438 if (It == MaybeLiveArguments.end() || *It != Arg) return;
440 DOUT << " MaybeLive argument now live: " << Arg->getName() <<"\n";
441 MaybeLiveArguments.erase(It);
442 LiveArguments.insert(Arg);
444 // Loop over all of the call sites of the function, making any arguments
445 // passed in to provide a value for this argument live as necessary.
447 Function *Fn = Arg->getParent();
448 unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
450 std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
451 for (; I != CallSites.end() && I->first == Fn; ++I) {
452 CallSite CS = I->second;
453 Value *ArgVal = *(CS.arg_begin()+ArgNo);
454 if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
455 MarkArgumentLive(ActualArg);
457 // If the value passed in at this call site is a return value computed by
458 // some other call site, make sure to mark the return value at the other
459 // call site as being needed.
460 CallSite ArgCS = CallSite::get(ArgVal);
461 if (ArgCS.getInstruction())
462 if (Function *Fn = ArgCS.getCalledFunction())
468 /// MarkArgumentLive - The MaybeLive return value for the specified function is
469 /// now known to be alive. Propagate this fact to the return instructions which
471 void DAE::MarkRetValLive(Function *F) {
472 assert(F && "Shame shame, we can't have null pointers here!");
474 // Check to see if we already knew it was live
475 std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
476 if (I == MaybeLiveRetVal.end() || *I != F) return; // It's already alive!
478 DOUT << " MaybeLive retval now live: " << F->getName() << "\n";
480 MaybeLiveRetVal.erase(I);
481 LiveRetVal.insert(F); // It is now known to be live!
483 // Loop over all of the functions, noticing that the return value is now live.
484 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
485 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
486 MarkReturnInstArgumentLive(RI);
489 void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
490 Value *Op = RI->getOperand(0);
491 if (Argument *A = dyn_cast<Argument>(Op)) {
493 } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
494 if (Function *F = CI->getCalledFunction())
496 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
497 if (Function *F = II->getCalledFunction())
502 // RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
503 // specified by the DeadArguments list. Transform the function and all of the
504 // callees of the function to not have these arguments.
506 void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
507 // Start by computing a new prototype for the function, which is the same as
508 // the old function, but has fewer arguments.
509 const FunctionType *FTy = F->getFunctionType();
510 std::vector<const Type*> Params;
512 // Set up to build a new list of parameter attributes
513 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
514 const PAListPtr &PAL = F->getParamAttrs();
516 // The existing function return attributes.
517 ParameterAttributes RAttrs = PAL.getParamAttrs(0);
519 // Make the function return void if the return value is dead.
520 const Type *RetTy = FTy->getReturnType();
521 if (DeadRetVal.count(F)) {
522 RetTy = Type::VoidTy;
523 RAttrs &= ~ParamAttr::typeIncompatible(RetTy);
528 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
530 // Construct the new parameter list from non-dead arguments. Also construct
531 // a new set of parameter attributes to correspond.
533 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
535 if (!DeadArguments.count(I)) {
536 Params.push_back(I->getType());
538 if (ParameterAttributes Attrs = PAL.getParamAttrs(index))
539 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), Attrs));
542 // Reconstruct the ParamAttrsList based on the vector we constructed.
543 PAListPtr NewPAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
545 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
546 // have zero fixed arguments.
548 bool ExtraArgHack = false;
549 if (Params.empty() && FTy->isVarArg()) {
551 Params.push_back(Type::Int32Ty);
554 // Create the new function type based on the recomputed parameters.
555 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
557 // Create the new function body and insert it into the module...
558 Function *NF = Function::Create(NFTy, F->getLinkage());
559 NF->setCallingConv(F->getCallingConv());
560 NF->setParamAttrs(NewPAL);
561 if (F->hasCollector())
562 NF->setCollector(F->getCollector());
563 F->getParent()->getFunctionList().insert(F, NF);
566 // Loop over all of the callers of the function, transforming the call sites
567 // to pass in a smaller number of arguments into the new function.
569 std::vector<Value*> Args;
570 while (!F->use_empty()) {
571 CallSite CS = CallSite::get(F->use_back());
572 Instruction *Call = CS.getInstruction();
573 ParamAttrsVec.clear();
574 const PAListPtr &CallPAL = CS.getParamAttrs();
576 // The call return attributes.
577 ParameterAttributes RAttrs = CallPAL.getParamAttrs(0);
578 // Adjust in case the function was changed to return void.
579 RAttrs &= ~ParamAttr::typeIncompatible(NF->getReturnType());
581 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
583 // Loop over the operands, deleting dead ones...
584 CallSite::arg_iterator AI = CS.arg_begin();
586 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
587 I != E; ++I, ++AI, ++index)
588 if (!DeadArguments.count(I)) { // Remove operands for dead arguments
590 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(index))
591 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
595 Args.push_back(UndefValue::get(Type::Int32Ty));
597 // Push any varargs arguments on the list. Don't forget their attributes.
598 for (; AI != CS.arg_end(); ++AI) {
600 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(index++))
601 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
604 // Reconstruct the ParamAttrsList based on the vector we constructed.
605 PAListPtr NewCallPAL = PAListPtr::get(ParamAttrsVec.begin(),
606 ParamAttrsVec.end());
609 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
610 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
611 Args.begin(), Args.end(), "", Call);
612 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
613 cast<InvokeInst>(New)->setParamAttrs(NewCallPAL);
615 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
616 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
617 cast<CallInst>(New)->setParamAttrs(NewCallPAL);
618 if (cast<CallInst>(Call)->isTailCall())
619 cast<CallInst>(New)->setTailCall();
623 if (!Call->use_empty()) {
624 if (New->getType() == Type::VoidTy)
625 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
627 Call->replaceAllUsesWith(New);
632 // Finally, remove the old call from the program, reducing the use-count of
634 Call->getParent()->getInstList().erase(Call);
637 // Since we have now created the new function, splice the body of the old
638 // function right into the new function, leaving the old rotting hulk of the
640 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
642 // Loop over the argument list, transfering uses of the old arguments over to
643 // the new arguments, also transfering over the names as well. While we're at
644 // it, remove the dead arguments from the DeadArguments list.
646 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
647 I2 = NF->arg_begin();
649 if (!DeadArguments.count(I)) {
650 // If this is a live argument, move the name and users over to the new
652 I->replaceAllUsesWith(I2);
656 // If this argument is dead, replace any uses of it with null constants
657 // (these are guaranteed to only be operands to call instructions which
658 // will later be simplified).
659 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
660 DeadArguments.erase(I);
663 // If we change the return value of the function we must rewrite any return
664 // instructions. Check this now.
665 if (F->getReturnType() != NF->getReturnType())
666 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
667 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
668 ReturnInst::Create(0, RI);
669 BB->getInstList().erase(RI);
672 // Now that the old function is dead, delete it.
673 F->getParent()->getFunctionList().erase(F);
676 bool DAE::runOnModule(Module &M) {
677 bool Changed = false;
678 // First pass: Do a simple check to see if any functions can have their "..."
679 // removed. We can do this if they never call va_start. This loop cannot be
680 // fused with the next loop, because deleting a function invalidates
681 // information computed while surveying other functions.
682 DOUT << "DAE - Deleting dead varargs\n";
683 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
685 if (F.getFunctionType()->isVarArg())
686 Changed |= DeleteDeadVarargs(F);
689 // Second phase:loop through the module, determining which arguments are live.
690 // We assume all arguments are dead unless proven otherwise (allowing us to
691 // determine that dead arguments passed into recursive functions are dead).
693 DOUT << "DAE - Determining liveness\n";
694 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
697 // Loop over the instructions to inspect, propagating liveness among arguments
698 // and return values which are MaybeLive.
699 while (!InstructionsToInspect.empty()) {
700 Instruction *I = InstructionsToInspect.back();
701 InstructionsToInspect.pop_back();
703 if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
704 // For return instructions, we just have to check to see if the return
705 // value for the current function is known now to be alive. If so, any
706 // arguments used by it are now alive, and any call instruction return
707 // value is alive as well.
708 if (LiveRetVal.count(RI->getParent()->getParent()))
709 MarkReturnInstArgumentLive(RI);
712 CallSite CS = CallSite::get(I);
713 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
715 Function *Callee = CS.getCalledFunction();
717 // If we found a call or invoke instruction on this list, that means that
718 // an argument of the function is a call instruction. If the argument is
719 // live, then the return value of the called instruction is now live.
721 CallSite::arg_iterator AI = CS.arg_begin(); // ActualIterator
722 for (Function::arg_iterator FI = Callee->arg_begin(),
723 E = Callee->arg_end(); FI != E; ++AI, ++FI) {
724 // If this argument is another call...
725 CallSite ArgCS = CallSite::get(*AI);
726 if (ArgCS.getInstruction() && LiveArguments.count(FI))
727 if (Function *Callee = ArgCS.getCalledFunction())
728 MarkRetValLive(Callee);
733 // Now we loop over all of the MaybeLive arguments, promoting them to be live
734 // arguments if one of the calls that uses the arguments to the calls they are
735 // passed into requires them to be live. Of course this could make other
736 // arguments live, so process callers recursively.
738 // Because elements can be removed from the MaybeLiveArguments set, copy it to
739 // a temporary vector.
741 std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
742 MaybeLiveArguments.end());
743 for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
744 Argument *MLA = TmpArgList[i];
745 if (MaybeLiveArguments.count(MLA) &&
746 isMaybeLiveArgumentNowLive(MLA))
747 MarkArgumentLive(MLA);
750 // Recover memory early...
753 // At this point, we know that all arguments in DeadArguments and
754 // MaybeLiveArguments are dead. If the two sets are empty, there is nothing
756 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
757 MaybeLiveRetVal.empty() && DeadRetVal.empty())
760 // Otherwise, compact into one set, and start eliminating the arguments from
762 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
763 MaybeLiveArguments.clear();
764 DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
765 MaybeLiveRetVal.clear();
767 LiveArguments.clear();
770 NumArgumentsEliminated += DeadArguments.size();
771 NumRetValsEliminated += DeadRetVal.size();
772 while (!DeadArguments.empty())
773 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
775 while (!DeadRetVal.empty())
776 RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());