blob: e1feed922e3b0fc3aa31cd547a37c99a5e62b421 [file] [log] [blame]
Chris Lattner13bf28c2003-06-17 22:21:05 +00001//===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner13bf28c2003-06-17 22:21:05 +00009//
10// This pass deletes dead arguments from internal functions. Dead argument
11// elimination removes arguments which are directly dead, as well as arguments
Chris Lattner0658cc22003-10-23 03:48:17 +000012// only passed into function calls as dead arguments of other functions. This
13// pass also deletes dead arguments in a similar way.
Chris Lattner13bf28c2003-06-17 22:21:05 +000014//
15// This pass is often useful as a cleanup pass to run after aggressive
16// interprocedural passes, which add possibly-dead arguments.
17//
18//===----------------------------------------------------------------------===//
19
Chris Lattner9610c6f2005-06-24 16:00:46 +000020#define DEBUG_TYPE "deadargelim"
Chris Lattner13bf28c2003-06-17 22:21:05 +000021#include "llvm/Transforms/IPO.h"
Chris Lattnerc4998a02006-06-27 21:05:04 +000022#include "llvm/CallingConv.h"
23#include "llvm/Constant.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Instructions.h"
Chris Lattner13bf28c2003-06-17 22:21:05 +000026#include "llvm/Module.h"
27#include "llvm/Pass.h"
Chris Lattner13bf28c2003-06-17 22:21:05 +000028#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000029#include "llvm/Support/Debug.h"
30#include "llvm/ADT/Statistic.h"
Chris Lattnerc597b8a2006-01-22 23:32:06 +000031#include <iostream>
Chris Lattner13bf28c2003-06-17 22:21:05 +000032#include <set>
Chris Lattnerf52e03c2003-11-21 21:54:22 +000033using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000034
Chris Lattner13bf28c2003-06-17 22:21:05 +000035namespace {
Chris Lattner0658cc22003-10-23 03:48:17 +000036 Statistic<> NumArgumentsEliminated("deadargelim",
37 "Number of unread args removed");
38 Statistic<> NumRetValsEliminated("deadargelim",
39 "Number of unused return values removed");
Chris Lattner13bf28c2003-06-17 22:21:05 +000040
Chris Lattner0658cc22003-10-23 03:48:17 +000041 /// DAE - The dead argument elimination pass.
42 ///
Chris Lattner4f2cf032004-09-20 04:48:05 +000043 class DAE : public ModulePass {
Chris Lattner0658cc22003-10-23 03:48:17 +000044 /// Liveness enum - During our initial pass over the program, we determine
45 /// that things are either definately alive, definately dead, or in need of
46 /// interprocedural analysis (MaybeLive).
47 ///
48 enum Liveness { Live, MaybeLive, Dead };
49
50 /// LiveArguments, MaybeLiveArguments, DeadArguments - These sets contain
51 /// all of the arguments in the program. The Dead set contains arguments
52 /// which are completely dead (never used in the function). The MaybeLive
53 /// set contains arguments which are only passed into other function calls,
54 /// thus may be live and may be dead. The Live set contains arguments which
55 /// are known to be alive.
56 ///
57 std::set<Argument*> DeadArguments, MaybeLiveArguments, LiveArguments;
58
59 /// DeadRetVal, MaybeLiveRetVal, LifeRetVal - These sets contain all of the
60 /// functions in the program. The Dead set contains functions whose return
61 /// value is known to be dead. The MaybeLive set contains functions whose
62 /// return values are only used by return instructions, and the Live set
63 /// contains functions whose return values are used, functions that are
64 /// external, and functions that already return void.
65 ///
66 std::set<Function*> DeadRetVal, MaybeLiveRetVal, LiveRetVal;
67
68 /// InstructionsToInspect - As we mark arguments and return values
69 /// MaybeLive, we keep track of which instructions could make the values
70 /// live here. Once the entire program has had the return value and
71 /// arguments analyzed, this set is scanned to promote the MaybeLive objects
72 /// to be Live if they really are used.
73 std::vector<Instruction*> InstructionsToInspect;
74
75 /// CallSites - Keep track of the call sites of functions that have
76 /// MaybeLive arguments or return values.
77 std::multimap<Function*, CallSite> CallSites;
78
79 public:
Chris Lattner4f2cf032004-09-20 04:48:05 +000080 bool runOnModule(Module &M);
Chris Lattner2ab04f72003-06-25 04:12:49 +000081
Chris Lattner9e60ace2003-11-05 21:43:02 +000082 virtual bool ShouldHackArguments() const { return false; }
83
Chris Lattner2ab04f72003-06-25 04:12:49 +000084 private:
Chris Lattner0658cc22003-10-23 03:48:17 +000085 Liveness getArgumentLiveness(const Argument &A);
86 bool isMaybeLiveArgumentNowLive(Argument *Arg);
87
88 void SurveyFunction(Function &Fn);
89
90 void MarkArgumentLive(Argument *Arg);
91 void MarkRetValLive(Function *F);
92 void MarkReturnInstArgumentLive(ReturnInst *RI);
Misha Brukmanb1c93172005-04-21 23:48:37 +000093
Chris Lattner0658cc22003-10-23 03:48:17 +000094 void RemoveDeadArgumentsFromFunction(Function *F);
Chris Lattner13bf28c2003-06-17 22:21:05 +000095 };
96 RegisterOpt<DAE> X("deadargelim", "Dead Argument Elimination");
Chris Lattner9e60ace2003-11-05 21:43:02 +000097
98 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
99 /// deletes arguments to functions which are external. This is only for use
100 /// by bugpoint.
101 struct DAH : public DAE {
102 virtual bool ShouldHackArguments() const { return true; }
103 };
Chris Lattner4e1b4672003-11-05 21:53:41 +0000104 RegisterPass<DAH> Y("deadarghaX0r",
Brian Gaeke6204e752004-02-02 19:32:27 +0000105 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
Chris Lattner13bf28c2003-06-17 22:21:05 +0000106}
107
Chris Lattner2ab04f72003-06-25 04:12:49 +0000108/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattner9e60ace2003-11-05 21:43:02 +0000109/// which are not used by the body of the function.
Chris Lattner2ab04f72003-06-25 04:12:49 +0000110///
Chris Lattner4f2cf032004-09-20 04:48:05 +0000111ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
112ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner13bf28c2003-06-17 22:21:05 +0000113
Chris Lattner0658cc22003-10-23 03:48:17 +0000114static inline bool CallPassesValueThoughVararg(Instruction *Call,
115 const Value *Arg) {
116 CallSite CS = CallSite::get(Call);
117 const Type *CalledValueTy = CS.getCalledValue()->getType();
118 const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
119 unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
120 for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
121 AI != CS.arg_end(); ++AI)
122 if (AI->get() == Arg)
123 return true;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000124 return false;
125}
126
Chris Lattner0658cc22003-10-23 03:48:17 +0000127// getArgumentLiveness - Inspect an argument, determining if is known Live
Chris Lattner13bf28c2003-06-17 22:21:05 +0000128// (used in a computation), MaybeLive (only passed as an argument to a call), or
129// Dead (not used).
Chris Lattner0658cc22003-10-23 03:48:17 +0000130DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
Chris Lattnerc4998a02006-06-27 21:05:04 +0000131 // If this is the return value of a csret function, it's not really dead.
132 if (A.getParent()->getCallingConv() == CallingConv::CSRet &&
133 &*A.getParent()->arg_begin() == &A)
134 return Live;
135
136 if (A.use_empty()) // First check, directly dead?
137 return Dead;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000138
139 // Scan through all of the uses, looking for non-argument passing uses.
140 for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000141 // Return instructions do not immediately effect liveness.
142 if (isa<ReturnInst>(*I))
143 continue;
144
Chris Lattner13bf28c2003-06-17 22:21:05 +0000145 CallSite CS = CallSite::get(const_cast<User*>(*I));
146 if (!CS.getInstruction()) {
147 // If its used by something that is not a call or invoke, it's alive!
Chris Lattner0658cc22003-10-23 03:48:17 +0000148 return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000149 }
150 // If it's an indirect call, mark it alive...
151 Function *Callee = CS.getCalledFunction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000152 if (!Callee) return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000153
Chris Lattner5d3c1452003-06-18 16:25:51 +0000154 // Check to see if it's passed through a va_arg area: if so, we cannot
155 // remove it.
Chris Lattner0658cc22003-10-23 03:48:17 +0000156 if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
157 return Live; // If passed through va_arg area, we cannot remove it
Chris Lattner13bf28c2003-06-17 22:21:05 +0000158 }
159
160 return MaybeLive; // It must be used, but only as argument to a function
161}
162
Chris Lattner0658cc22003-10-23 03:48:17 +0000163
164// SurveyFunction - This performs the initial survey of the specified function,
165// checking out whether or not it uses any of its incoming arguments or whether
166// any callers use the return value. This fills in the
167// (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000168//
Chris Lattner0658cc22003-10-23 03:48:17 +0000169// We consider arguments of non-internal functions to be intrinsically alive as
170// well as arguments to functions which have their "address taken".
171//
172void DAE::SurveyFunction(Function &F) {
173 bool FunctionIntrinsicallyLive = false;
174 Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
175
Chris Lattner4e1b4672003-11-05 21:53:41 +0000176 if (!F.hasInternalLinkage() &&
177 (!ShouldHackArguments() || F.getIntrinsicID()))
Chris Lattner0658cc22003-10-23 03:48:17 +0000178 FunctionIntrinsicallyLive = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000179 else
Chris Lattner0658cc22003-10-23 03:48:17 +0000180 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
181 // If this use is anything other than a call site, the function is alive.
182 CallSite CS = CallSite::get(*I);
183 Instruction *TheCall = CS.getInstruction();
184 if (!TheCall) { // Not a direct call site?
185 FunctionIntrinsicallyLive = true;
186 break;
187 }
188
189 // Check to see if the return value is used...
190 if (RetValLiveness != Live)
191 for (Value::use_iterator I = TheCall->use_begin(),
192 E = TheCall->use_end(); I != E; ++I)
193 if (isa<ReturnInst>(cast<Instruction>(*I))) {
194 RetValLiveness = MaybeLive;
195 } else if (isa<CallInst>(cast<Instruction>(*I)) ||
196 isa<InvokeInst>(cast<Instruction>(*I))) {
197 if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
198 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
199 RetValLiveness = Live;
200 break;
201 } else {
202 RetValLiveness = MaybeLive;
203 }
204 } else {
205 RetValLiveness = Live;
206 break;
207 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000208
Chris Lattner0658cc22003-10-23 03:48:17 +0000209 // If the function is PASSED IN as an argument, its address has been taken
210 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
211 AI != E; ++AI)
212 if (AI->get() == &F) {
213 FunctionIntrinsicallyLive = true;
214 break;
215 }
216 if (FunctionIntrinsicallyLive) break;
217 }
218
219 if (FunctionIntrinsicallyLive) {
220 DEBUG(std::cerr << " Intrinsically live fn: " << F.getName() << "\n");
Chris Lattner53db5462005-05-06 05:34:40 +0000221 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
222 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000223 LiveArguments.insert(AI);
224 LiveRetVal.insert(&F);
225 return;
226 }
227
228 switch (RetValLiveness) {
229 case Live: LiveRetVal.insert(&F); break;
230 case MaybeLive: MaybeLiveRetVal.insert(&F); break;
231 case Dead: DeadRetVal.insert(&F); break;
232 }
233
234 DEBUG(std::cerr << " Inspecting args for fn: " << F.getName() << "\n");
235
236 // If it is not intrinsically alive, we know that all users of the
237 // function are call sites. Mark all of the arguments live which are
238 // directly used, and keep track of all of the call sites of this function
239 // if there are any arguments we assume that are dead.
240 //
241 bool AnyMaybeLiveArgs = false;
Chris Lattner53db5462005-05-06 05:34:40 +0000242 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
243 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000244 switch (getArgumentLiveness(*AI)) {
245 case Live:
246 DEBUG(std::cerr << " Arg live by use: " << AI->getName() << "\n");
247 LiveArguments.insert(AI);
248 break;
249 case Dead:
250 DEBUG(std::cerr << " Arg definitely dead: " <<AI->getName()<<"\n");
251 DeadArguments.insert(AI);
252 break;
253 case MaybeLive:
254 DEBUG(std::cerr << " Arg only passed to calls: "
255 << AI->getName() << "\n");
256 AnyMaybeLiveArgs = true;
257 MaybeLiveArguments.insert(AI);
258 break;
259 }
260
261 // If there are any "MaybeLive" arguments, we need to check callees of
262 // this function when/if they become alive. Record which functions are
263 // callees...
264 if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
265 for (Value::use_iterator I = F.use_begin(), E = F.use_end();
266 I != E; ++I) {
267 if (AnyMaybeLiveArgs)
268 CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
269
270 if (RetValLiveness == MaybeLive)
271 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
272 UI != E; ++UI)
273 InstructionsToInspect.push_back(cast<Instruction>(*UI));
274 }
275}
276
277// isMaybeLiveArgumentNowLive - Check to see if Arg is alive. At this point, we
278// know that the only uses of Arg are to be passed in as an argument to a
279// function call or return. Check to see if the formal argument passed in is in
280// the LiveArguments set. If so, return true.
281//
282bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000283 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
Chris Lattner0658cc22003-10-23 03:48:17 +0000284 if (isa<ReturnInst>(*I)) {
285 if (LiveRetVal.count(Arg->getParent())) return true;
286 continue;
287 }
288
Chris Lattner13bf28c2003-06-17 22:21:05 +0000289 CallSite CS = CallSite::get(*I);
290
291 // We know that this can only be used for direct calls...
Chris Lattner7f7285b2003-11-02 02:06:27 +0000292 Function *Callee = CS.getCalledFunction();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000293
294 // Loop over all of the arguments (because Arg may be passed into the call
295 // multiple times) and check to see if any are now alive...
296 CallSite::arg_iterator CSAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000297 for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000298 AI != E; ++AI, ++CSAI)
299 // If this is the argument we are looking for, check to see if it's alive
300 if (*CSAI == Arg && LiveArguments.count(AI))
301 return true;
302 }
303 return false;
304}
305
Chris Lattner0658cc22003-10-23 03:48:17 +0000306/// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
307/// Mark it live in the specified sets and recursively mark arguments in callers
308/// live that are needed to pass in a value.
309///
310void DAE::MarkArgumentLive(Argument *Arg) {
311 std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
312 if (It == MaybeLiveArguments.end() || *It != Arg) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000313
Chris Lattner13bf28c2003-06-17 22:21:05 +0000314 DEBUG(std::cerr << " MaybeLive argument now live: " << Arg->getName()<<"\n");
Chris Lattner0658cc22003-10-23 03:48:17 +0000315 MaybeLiveArguments.erase(It);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000316 LiveArguments.insert(Arg);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000317
Chris Lattner13bf28c2003-06-17 22:21:05 +0000318 // Loop over all of the call sites of the function, making any arguments
319 // passed in to provide a value for this argument live as necessary.
320 //
321 Function *Fn = Arg->getParent();
Chris Lattner531f9e92005-03-15 04:54:21 +0000322 unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner13bf28c2003-06-17 22:21:05 +0000323
Chris Lattner0658cc22003-10-23 03:48:17 +0000324 std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000325 for (; I != CallSites.end() && I->first == Fn; ++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000326 CallSite CS = I->second;
327 Value *ArgVal = *(CS.arg_begin()+ArgNo);
328 if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
329 MarkArgumentLive(ActualArg);
330 } else {
331 // If the value passed in at this call site is a return value computed by
332 // some other call site, make sure to mark the return value at the other
333 // call site as being needed.
334 CallSite ArgCS = CallSite::get(ArgVal);
335 if (ArgCS.getInstruction())
336 if (Function *Fn = ArgCS.getCalledFunction())
337 MarkRetValLive(Fn);
338 }
339 }
340}
341
342/// MarkArgumentLive - The MaybeLive return value for the specified function is
343/// now known to be alive. Propagate this fact to the return instructions which
344/// produce it.
345void DAE::MarkRetValLive(Function *F) {
346 assert(F && "Shame shame, we can't have null pointers here!");
347
348 // Check to see if we already knew it was live
349 std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
350 if (I == MaybeLiveRetVal.end() || *I != F) return; // It's already alive!
351
352 DEBUG(std::cerr << " MaybeLive retval now live: " << F->getName() << "\n");
353
354 MaybeLiveRetVal.erase(I);
355 LiveRetVal.insert(F); // It is now known to be live!
356
357 // Loop over all of the functions, noticing that the return value is now live.
358 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
359 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
360 MarkReturnInstArgumentLive(RI);
361}
362
363void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
364 Value *Op = RI->getOperand(0);
365 if (Argument *A = dyn_cast<Argument>(Op)) {
366 MarkArgumentLive(A);
367 } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
368 if (Function *F = CI->getCalledFunction())
369 MarkRetValLive(F);
370 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
371 if (Function *F = II->getCalledFunction())
372 MarkRetValLive(F);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000373 }
374}
375
376// RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
377// specified by the DeadArguments list. Transform the function and all of the
378// callees of the function to not have these arguments.
379//
Chris Lattner0658cc22003-10-23 03:48:17 +0000380void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000381 // Start by computing a new prototype for the function, which is the same as
382 // the old function, but has fewer arguments.
383 const FunctionType *FTy = F->getFunctionType();
384 std::vector<const Type*> Params;
385
Chris Lattner531f9e92005-03-15 04:54:21 +0000386 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner13bf28c2003-06-17 22:21:05 +0000387 if (!DeadArguments.count(I))
388 Params.push_back(I->getType());
389
Chris Lattner0658cc22003-10-23 03:48:17 +0000390 const Type *RetTy = FTy->getReturnType();
391 if (DeadRetVal.count(F)) {
392 RetTy = Type::VoidTy;
393 DeadRetVal.erase(F);
394 }
395
Chris Lattner05c71fb2003-10-23 17:44:53 +0000396 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
397 // have zero fixed arguments.
398 //
399 // FIXME: once this bug is fixed in the CWriter, this hack should be removed.
400 //
401 bool ExtraArgHack = false;
402 if (Params.empty() && FTy->isVarArg()) {
403 ExtraArgHack = true;
404 Params.push_back(Type::IntTy);
405 }
406
Chris Lattner0658cc22003-10-23 03:48:17 +0000407 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
408
Chris Lattner13bf28c2003-06-17 22:21:05 +0000409 // Create the new function body and insert it into the module...
Chris Lattner2ab04f72003-06-25 04:12:49 +0000410 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000411 NF->setCallingConv(F->getCallingConv());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000412 F->getParent()->getFunctionList().insert(F, NF);
413
414 // Loop over all of the callers of the function, transforming the call sites
415 // to pass in a smaller number of arguments into the new function.
416 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000417 std::vector<Value*> Args;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000418 while (!F->use_empty()) {
419 CallSite CS = CallSite::get(F->use_back());
420 Instruction *Call = CS.getInstruction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000421
Chris Lattner13bf28c2003-06-17 22:21:05 +0000422 // Loop over the operands, deleting dead ones...
423 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner53db5462005-05-06 05:34:40 +0000424 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
425 I != E; ++I, ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000426 if (!DeadArguments.count(I)) // Remove operands for dead arguments
427 Args.push_back(*AI);
428
Chris Lattner05c71fb2003-10-23 17:44:53 +0000429 if (ExtraArgHack)
430 Args.push_back(Constant::getNullValue(Type::IntTy));
431
432 // Push any varargs arguments on the list
433 for (; AI != CS.arg_end(); ++AI)
434 Args.push_back(*AI);
435
Chris Lattner0658cc22003-10-23 03:48:17 +0000436 Instruction *New;
437 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000438 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner0658cc22003-10-23 03:48:17 +0000439 Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000440 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner0658cc22003-10-23 03:48:17 +0000441 } else {
442 New = new CallInst(NF, Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000443 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner324d2ee2005-05-06 06:46:58 +0000444 if (cast<CallInst>(Call)->isTailCall())
445 cast<CallInst>(New)->setTailCall();
Chris Lattner0658cc22003-10-23 03:48:17 +0000446 }
447 Args.clear();
448
449 if (!Call->use_empty()) {
450 if (New->getType() == Type::VoidTy)
451 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
452 else {
453 Call->replaceAllUsesWith(New);
454 std::string Name = Call->getName();
455 Call->setName("");
456 New->setName(Name);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000457 }
Chris Lattner0658cc22003-10-23 03:48:17 +0000458 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000459
Chris Lattner0658cc22003-10-23 03:48:17 +0000460 // Finally, remove the old call from the program, reducing the use-count of
461 // F.
462 Call->getParent()->getInstList().erase(Call);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000463 }
464
465 // Since we have now created the new function, splice the body of the old
466 // function right into the new function, leaving the old rotting hulk of the
467 // function empty.
468 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
469
470 // Loop over the argument list, transfering uses of the old arguments over to
471 // the new arguments, also transfering over the names as well. While we're at
472 // it, remove the dead arguments from the DeadArguments list.
473 //
Chris Lattner53db5462005-05-06 05:34:40 +0000474 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
475 I2 = NF->arg_begin();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000476 I != E; ++I)
477 if (!DeadArguments.count(I)) {
478 // If this is a live argument, move the name and users over to the new
479 // version.
480 I->replaceAllUsesWith(I2);
481 I2->setName(I->getName());
482 ++I2;
483 } else {
484 // If this argument is dead, replace any uses of it with null constants
485 // (these are guaranteed to only be operands to call instructions which
486 // will later be simplified).
487 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
488 DeadArguments.erase(I);
489 }
490
Chris Lattner0658cc22003-10-23 03:48:17 +0000491 // If we change the return value of the function we must rewrite any return
492 // instructions. Check this now.
493 if (F->getReturnType() != NF->getReturnType())
494 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
495 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
496 new ReturnInst(0, RI);
497 BB->getInstList().erase(RI);
498 }
499
Chris Lattner13bf28c2003-06-17 22:21:05 +0000500 // Now that the old function is dead, delete it.
501 F->getParent()->getFunctionList().erase(F);
502}
503
Chris Lattner4f2cf032004-09-20 04:48:05 +0000504bool DAE::runOnModule(Module &M) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000505 // First phase: loop through the module, determining which arguments are live.
506 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000507 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner13bf28c2003-06-17 22:21:05 +0000508 //
Chris Lattner13bf28c2003-06-17 22:21:05 +0000509 DEBUG(std::cerr << "DAE - Determining liveness\n");
Chris Lattner0658cc22003-10-23 03:48:17 +0000510 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
511 SurveyFunction(*I);
512
513 // Loop over the instructions to inspect, propagating liveness among arguments
514 // and return values which are MaybeLive.
515
516 while (!InstructionsToInspect.empty()) {
517 Instruction *I = InstructionsToInspect.back();
518 InstructionsToInspect.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000519
Chris Lattner0658cc22003-10-23 03:48:17 +0000520 if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
521 // For return instructions, we just have to check to see if the return
522 // value for the current function is known now to be alive. If so, any
523 // arguments used by it are now alive, and any call instruction return
524 // value is alive as well.
525 if (LiveRetVal.count(RI->getParent()->getParent()))
526 MarkReturnInstArgumentLive(RI);
527
Chris Lattner13bf28c2003-06-17 22:21:05 +0000528 } else {
Chris Lattner0658cc22003-10-23 03:48:17 +0000529 CallSite CS = CallSite::get(I);
530 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
Chris Lattner13bf28c2003-06-17 22:21:05 +0000531
Chris Lattner0658cc22003-10-23 03:48:17 +0000532 Function *Callee = CS.getCalledFunction();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000533
Chris Lattner0658cc22003-10-23 03:48:17 +0000534 // If we found a call or invoke instruction on this list, that means that
535 // an argument of the function is a call instruction. If the argument is
536 // live, then the return value of the called instruction is now live.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000537 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000538 CallSite::arg_iterator AI = CS.arg_begin(); // ActualIterator
Chris Lattner53db5462005-05-06 05:34:40 +0000539 for (Function::arg_iterator FI = Callee->arg_begin(),
540 E = Callee->arg_end(); FI != E; ++AI, ++FI) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000541 // If this argument is another call...
542 CallSite ArgCS = CallSite::get(*AI);
543 if (ArgCS.getInstruction() && LiveArguments.count(FI))
544 if (Function *Callee = ArgCS.getCalledFunction())
545 MarkRetValLive(Callee);
546 }
Chris Lattner13bf28c2003-06-17 22:21:05 +0000547 }
548 }
549
550 // Now we loop over all of the MaybeLive arguments, promoting them to be live
551 // arguments if one of the calls that uses the arguments to the calls they are
552 // passed into requires them to be live. Of course this could make other
553 // arguments live, so process callers recursively.
554 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000555 // Because elements can be removed from the MaybeLiveArguments set, copy it to
556 // a temporary vector.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000557 //
558 std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
559 MaybeLiveArguments.end());
560 for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
561 Argument *MLA = TmpArgList[i];
562 if (MaybeLiveArguments.count(MLA) &&
Chris Lattner0658cc22003-10-23 03:48:17 +0000563 isMaybeLiveArgumentNowLive(MLA))
564 MarkArgumentLive(MLA);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000565 }
566
567 // Recover memory early...
568 CallSites.clear();
569
570 // At this point, we know that all arguments in DeadArguments and
571 // MaybeLiveArguments are dead. If the two sets are empty, there is nothing
572 // to do.
Chris Lattner0658cc22003-10-23 03:48:17 +0000573 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
574 MaybeLiveRetVal.empty() && DeadRetVal.empty())
Chris Lattner13bf28c2003-06-17 22:21:05 +0000575 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000576
Chris Lattner13bf28c2003-06-17 22:21:05 +0000577 // Otherwise, compact into one set, and start eliminating the arguments from
578 // the functions.
579 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
580 MaybeLiveArguments.clear();
Chris Lattner0658cc22003-10-23 03:48:17 +0000581 DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
582 MaybeLiveRetVal.clear();
583
584 LiveArguments.clear();
585 LiveRetVal.clear();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000586
587 NumArgumentsEliminated += DeadArguments.size();
Chris Lattner0658cc22003-10-23 03:48:17 +0000588 NumRetValsEliminated += DeadRetVal.size();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000589 while (!DeadArguments.empty())
Chris Lattner0658cc22003-10-23 03:48:17 +0000590 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
591
592 while (!DeadRetVal.empty())
593 RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000594 return true;
595}