blob: 149043d05ce7f40ae57f9b10b845397617b08ac3 [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 Lattner67a35bb2006-09-18 07:02:31 +000026#include "llvm/IntrinsicInst.h"
Chris Lattner13bf28c2003-06-17 22:21:05 +000027#include "llvm/Module.h"
28#include "llvm/Pass.h"
Chris Lattner13bf28c2003-06-17 22:21:05 +000029#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000030#include "llvm/Support/Debug.h"
31#include "llvm/ADT/Statistic.h"
Reid Spencer557ab152007-02-05 23:32:05 +000032#include "llvm/Support/Compiler.h"
Chris Lattner13bf28c2003-06-17 22:21:05 +000033#include <set>
Chris Lattnerf52e03c2003-11-21 21:54:22 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Chris Lattner1631bcb2006-12-19 22:09:18 +000036STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
37STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
Chris Lattner13bf28c2003-06-17 22:21:05 +000038
Chris Lattner1631bcb2006-12-19 22:09:18 +000039namespace {
Chris Lattner0658cc22003-10-23 03:48:17 +000040 /// DAE - The dead argument elimination pass.
41 ///
Reid Spencer557ab152007-02-05 23:32:05 +000042 class VISIBILITY_HIDDEN DAE : public ModulePass {
Chris Lattner0658cc22003-10-23 03:48:17 +000043 /// Liveness enum - During our initial pass over the program, we determine
44 /// that things are either definately alive, definately dead, or in need of
45 /// interprocedural analysis (MaybeLive).
46 ///
47 enum Liveness { Live, MaybeLive, Dead };
48
49 /// LiveArguments, MaybeLiveArguments, DeadArguments - These sets contain
50 /// all of the arguments in the program. The Dead set contains arguments
51 /// which are completely dead (never used in the function). The MaybeLive
52 /// set contains arguments which are only passed into other function calls,
53 /// thus may be live and may be dead. The Live set contains arguments which
54 /// are known to be alive.
55 ///
56 std::set<Argument*> DeadArguments, MaybeLiveArguments, LiveArguments;
57
58 /// DeadRetVal, MaybeLiveRetVal, LifeRetVal - These sets contain all of the
59 /// functions in the program. The Dead set contains functions whose return
60 /// value is known to be dead. The MaybeLive set contains functions whose
61 /// return values are only used by return instructions, and the Live set
62 /// contains functions whose return values are used, functions that are
63 /// external, and functions that already return void.
64 ///
65 std::set<Function*> DeadRetVal, MaybeLiveRetVal, LiveRetVal;
66
67 /// InstructionsToInspect - As we mark arguments and return values
68 /// MaybeLive, we keep track of which instructions could make the values
69 /// live here. Once the entire program has had the return value and
70 /// arguments analyzed, this set is scanned to promote the MaybeLive objects
71 /// to be Live if they really are used.
72 std::vector<Instruction*> InstructionsToInspect;
73
74 /// CallSites - Keep track of the call sites of functions that have
75 /// MaybeLive arguments or return values.
76 std::multimap<Function*, CallSite> CallSites;
77
78 public:
Chris Lattner4f2cf032004-09-20 04:48:05 +000079 bool runOnModule(Module &M);
Chris Lattner2ab04f72003-06-25 04:12:49 +000080
Chris Lattner9e60ace2003-11-05 21:43:02 +000081 virtual bool ShouldHackArguments() const { return false; }
82
Chris Lattner2ab04f72003-06-25 04:12:49 +000083 private:
Chris Lattner0658cc22003-10-23 03:48:17 +000084 Liveness getArgumentLiveness(const Argument &A);
85 bool isMaybeLiveArgumentNowLive(Argument *Arg);
86
Chris Lattner67a35bb2006-09-18 07:02:31 +000087 bool DeleteDeadVarargs(Function &Fn);
Chris Lattner0658cc22003-10-23 03:48:17 +000088 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 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000096 RegisterPass<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 Lattner67a35bb2006-09-18 07:02:31 +0000114/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
115/// llvm.vastart is never called, the varargs list is dead for the function.
116bool DAE::DeleteDeadVarargs(Function &Fn) {
117 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
Reid Spencer5301e7c2007-01-30 20:08:39 +0000118 if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
Chris Lattner67a35bb2006-09-18 07:02:31 +0000119
120 // Ensure that the function is only directly called.
121 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
122 // If this use is anything other than a call site, give up.
123 CallSite CS = CallSite::get(*I);
124 Instruction *TheCall = CS.getInstruction();
125 if (!TheCall) return false; // Not a direct call site?
126
127 // The addr of this function is passed to the call.
128 if (I.getOperandNo() != 0) return false;
129 }
130
131 // Okay, we know we can transform this function if safe. Scan its body
132 // looking for calls to llvm.vastart.
133 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
134 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
135 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
136 if (II->getIntrinsicID() == Intrinsic::vastart)
137 return false;
138 }
139 }
140 }
141
142 // If we get here, there are no calls to llvm.vastart in the function body,
143 // remove the "..." and adjust all the calls.
144
145 // Start by computing a new prototype for the function, which is the same as
146 // the old function, but has fewer arguments.
147 const FunctionType *FTy = Fn.getFunctionType();
148 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
149 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
150 unsigned NumArgs = Params.size();
151
152 // Create the new function body and insert it into the module...
153 Function *NF = new Function(NFTy, Fn.getLinkage(), Fn.getName());
154 NF->setCallingConv(Fn.getCallingConv());
155 Fn.getParent()->getFunctionList().insert(&Fn, NF);
156
157 // Loop over all of the callers of the function, transforming the call sites
158 // to pass in a smaller number of arguments into the new function.
159 //
160 std::vector<Value*> Args;
161 while (!Fn.use_empty()) {
162 CallSite CS = CallSite::get(Fn.use_back());
163 Instruction *Call = CS.getInstruction();
164
165 // Loop over the operands, dropping extraneous ones at the end of the list.
166 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
167
168 Instruction *New;
169 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
170 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
171 Args, "", Call);
172 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
173 } else {
174 New = new CallInst(NF, Args, "", Call);
175 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
176 if (cast<CallInst>(Call)->isTailCall())
177 cast<CallInst>(New)->setTailCall();
178 }
179 Args.clear();
180
181 if (!Call->use_empty())
182 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
183
184 if (Call->hasName()) {
185 std::string Name = Call->getName();
186 Call->setName("");
187 New->setName(Name);
188 }
189
190 // Finally, remove the old call from the program, reducing the use-count of
191 // F.
192 Call->getParent()->getInstList().erase(Call);
193 }
194
195 // Since we have now created the new function, splice the body of the old
196 // function right into the new function, leaving the old rotting hulk of the
197 // function empty.
198 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
199
200 // Loop over the argument list, transfering uses of the old arguments over to
201 // the new arguments, also transfering over the names as well. While we're at
202 // it, remove the dead arguments from the DeadArguments list.
203 //
204 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
205 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
206 // Move the name and users over to the new version.
207 I->replaceAllUsesWith(I2);
208 I2->setName(I->getName());
209 }
210
211 // Finally, nuke the old function.
212 Fn.eraseFromParent();
213 return true;
214}
215
216
Chris Lattner0658cc22003-10-23 03:48:17 +0000217static inline bool CallPassesValueThoughVararg(Instruction *Call,
218 const Value *Arg) {
219 CallSite CS = CallSite::get(Call);
220 const Type *CalledValueTy = CS.getCalledValue()->getType();
221 const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
222 unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
223 for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
224 AI != CS.arg_end(); ++AI)
225 if (AI->get() == Arg)
226 return true;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000227 return false;
228}
229
Chris Lattner0658cc22003-10-23 03:48:17 +0000230// getArgumentLiveness - Inspect an argument, determining if is known Live
Chris Lattner13bf28c2003-06-17 22:21:05 +0000231// (used in a computation), MaybeLive (only passed as an argument to a call), or
232// Dead (not used).
Chris Lattner0658cc22003-10-23 03:48:17 +0000233DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +0000234 const FunctionType *FTy = A.getParent()->getFunctionType();
235
236 // If this is the return value of a struct function, it's not really dead.
237 if (FTy->isStructReturn() && &*A.getParent()->arg_begin() == &A)
Chris Lattnerc4998a02006-06-27 21:05:04 +0000238 return Live;
239
240 if (A.use_empty()) // First check, directly dead?
241 return Dead;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000242
243 // Scan through all of the uses, looking for non-argument passing uses.
244 for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000245 // Return instructions do not immediately effect liveness.
246 if (isa<ReturnInst>(*I))
247 continue;
248
Chris Lattner13bf28c2003-06-17 22:21:05 +0000249 CallSite CS = CallSite::get(const_cast<User*>(*I));
250 if (!CS.getInstruction()) {
251 // If its used by something that is not a call or invoke, it's alive!
Chris Lattner0658cc22003-10-23 03:48:17 +0000252 return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000253 }
254 // If it's an indirect call, mark it alive...
255 Function *Callee = CS.getCalledFunction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000256 if (!Callee) return Live;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000257
Chris Lattner5d3c1452003-06-18 16:25:51 +0000258 // Check to see if it's passed through a va_arg area: if so, we cannot
259 // remove it.
Chris Lattner0658cc22003-10-23 03:48:17 +0000260 if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
261 return Live; // If passed through va_arg area, we cannot remove it
Chris Lattner13bf28c2003-06-17 22:21:05 +0000262 }
263
264 return MaybeLive; // It must be used, but only as argument to a function
265}
266
Chris Lattner0658cc22003-10-23 03:48:17 +0000267
268// SurveyFunction - This performs the initial survey of the specified function,
269// checking out whether or not it uses any of its incoming arguments or whether
270// any callers use the return value. This fills in the
271// (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000272//
Chris Lattner0658cc22003-10-23 03:48:17 +0000273// We consider arguments of non-internal functions to be intrinsically alive as
274// well as arguments to functions which have their "address taken".
275//
276void DAE::SurveyFunction(Function &F) {
277 bool FunctionIntrinsicallyLive = false;
278 Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
279
Chris Lattner4e1b4672003-11-05 21:53:41 +0000280 if (!F.hasInternalLinkage() &&
281 (!ShouldHackArguments() || F.getIntrinsicID()))
Chris Lattner0658cc22003-10-23 03:48:17 +0000282 FunctionIntrinsicallyLive = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000283 else
Chris Lattner0658cc22003-10-23 03:48:17 +0000284 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
285 // If this use is anything other than a call site, the function is alive.
286 CallSite CS = CallSite::get(*I);
287 Instruction *TheCall = CS.getInstruction();
288 if (!TheCall) { // Not a direct call site?
289 FunctionIntrinsicallyLive = true;
290 break;
291 }
292
293 // Check to see if the return value is used...
294 if (RetValLiveness != Live)
295 for (Value::use_iterator I = TheCall->use_begin(),
296 E = TheCall->use_end(); I != E; ++I)
297 if (isa<ReturnInst>(cast<Instruction>(*I))) {
298 RetValLiveness = MaybeLive;
299 } else if (isa<CallInst>(cast<Instruction>(*I)) ||
300 isa<InvokeInst>(cast<Instruction>(*I))) {
301 if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
302 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
303 RetValLiveness = Live;
304 break;
305 } else {
306 RetValLiveness = MaybeLive;
307 }
308 } else {
309 RetValLiveness = Live;
310 break;
311 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000312
Chris Lattner0658cc22003-10-23 03:48:17 +0000313 // If the function is PASSED IN as an argument, its address has been taken
314 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
315 AI != E; ++AI)
316 if (AI->get() == &F) {
317 FunctionIntrinsicallyLive = true;
318 break;
319 }
320 if (FunctionIntrinsicallyLive) break;
321 }
322
323 if (FunctionIntrinsicallyLive) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000324 DOUT << " Intrinsically live fn: " << F.getName() << "\n";
Chris Lattner53db5462005-05-06 05:34:40 +0000325 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
326 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000327 LiveArguments.insert(AI);
328 LiveRetVal.insert(&F);
329 return;
330 }
331
332 switch (RetValLiveness) {
333 case Live: LiveRetVal.insert(&F); break;
334 case MaybeLive: MaybeLiveRetVal.insert(&F); break;
335 case Dead: DeadRetVal.insert(&F); break;
336 }
337
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000338 DOUT << " Inspecting args for fn: " << F.getName() << "\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000339
340 // If it is not intrinsically alive, we know that all users of the
341 // function are call sites. Mark all of the arguments live which are
342 // directly used, and keep track of all of the call sites of this function
343 // if there are any arguments we assume that are dead.
344 //
345 bool AnyMaybeLiveArgs = false;
Chris Lattner53db5462005-05-06 05:34:40 +0000346 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
347 AI != E; ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000348 switch (getArgumentLiveness(*AI)) {
349 case Live:
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000350 DOUT << " Arg live by use: " << AI->getName() << "\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000351 LiveArguments.insert(AI);
352 break;
353 case Dead:
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000354 DOUT << " Arg definitely dead: " << AI->getName() <<"\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000355 DeadArguments.insert(AI);
356 break;
357 case MaybeLive:
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000358 DOUT << " Arg only passed to calls: " << AI->getName() << "\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000359 AnyMaybeLiveArgs = true;
360 MaybeLiveArguments.insert(AI);
361 break;
362 }
363
364 // If there are any "MaybeLive" arguments, we need to check callees of
365 // this function when/if they become alive. Record which functions are
366 // callees...
367 if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
368 for (Value::use_iterator I = F.use_begin(), E = F.use_end();
369 I != E; ++I) {
370 if (AnyMaybeLiveArgs)
371 CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
372
373 if (RetValLiveness == MaybeLive)
374 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
375 UI != E; ++UI)
376 InstructionsToInspect.push_back(cast<Instruction>(*UI));
377 }
378}
379
380// isMaybeLiveArgumentNowLive - Check to see if Arg is alive. At this point, we
381// know that the only uses of Arg are to be passed in as an argument to a
382// function call or return. Check to see if the formal argument passed in is in
383// the LiveArguments set. If so, return true.
384//
385bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000386 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
Chris Lattner0658cc22003-10-23 03:48:17 +0000387 if (isa<ReturnInst>(*I)) {
388 if (LiveRetVal.count(Arg->getParent())) return true;
389 continue;
390 }
391
Chris Lattner13bf28c2003-06-17 22:21:05 +0000392 CallSite CS = CallSite::get(*I);
393
394 // We know that this can only be used for direct calls...
Chris Lattner7f7285b2003-11-02 02:06:27 +0000395 Function *Callee = CS.getCalledFunction();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000396
397 // Loop over all of the arguments (because Arg may be passed into the call
398 // multiple times) and check to see if any are now alive...
399 CallSite::arg_iterator CSAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000400 for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000401 AI != E; ++AI, ++CSAI)
402 // If this is the argument we are looking for, check to see if it's alive
403 if (*CSAI == Arg && LiveArguments.count(AI))
404 return true;
405 }
406 return false;
407}
408
Chris Lattner0658cc22003-10-23 03:48:17 +0000409/// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
410/// Mark it live in the specified sets and recursively mark arguments in callers
411/// live that are needed to pass in a value.
412///
413void DAE::MarkArgumentLive(Argument *Arg) {
414 std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
415 if (It == MaybeLiveArguments.end() || *It != Arg) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000416
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000417 DOUT << " MaybeLive argument now live: " << Arg->getName() <<"\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000418 MaybeLiveArguments.erase(It);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000419 LiveArguments.insert(Arg);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000420
Chris Lattner13bf28c2003-06-17 22:21:05 +0000421 // Loop over all of the call sites of the function, making any arguments
422 // passed in to provide a value for this argument live as necessary.
423 //
424 Function *Fn = Arg->getParent();
Chris Lattner531f9e92005-03-15 04:54:21 +0000425 unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner13bf28c2003-06-17 22:21:05 +0000426
Chris Lattner0658cc22003-10-23 03:48:17 +0000427 std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000428 for (; I != CallSites.end() && I->first == Fn; ++I) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000429 CallSite CS = I->second;
430 Value *ArgVal = *(CS.arg_begin()+ArgNo);
431 if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
432 MarkArgumentLive(ActualArg);
433 } else {
434 // If the value passed in at this call site is a return value computed by
435 // some other call site, make sure to mark the return value at the other
436 // call site as being needed.
437 CallSite ArgCS = CallSite::get(ArgVal);
438 if (ArgCS.getInstruction())
439 if (Function *Fn = ArgCS.getCalledFunction())
440 MarkRetValLive(Fn);
441 }
442 }
443}
444
445/// MarkArgumentLive - The MaybeLive return value for the specified function is
446/// now known to be alive. Propagate this fact to the return instructions which
447/// produce it.
448void DAE::MarkRetValLive(Function *F) {
449 assert(F && "Shame shame, we can't have null pointers here!");
450
451 // Check to see if we already knew it was live
452 std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
453 if (I == MaybeLiveRetVal.end() || *I != F) return; // It's already alive!
454
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000455 DOUT << " MaybeLive retval now live: " << F->getName() << "\n";
Chris Lattner0658cc22003-10-23 03:48:17 +0000456
457 MaybeLiveRetVal.erase(I);
458 LiveRetVal.insert(F); // It is now known to be live!
459
460 // Loop over all of the functions, noticing that the return value is now live.
461 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
462 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
463 MarkReturnInstArgumentLive(RI);
464}
465
466void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
467 Value *Op = RI->getOperand(0);
468 if (Argument *A = dyn_cast<Argument>(Op)) {
469 MarkArgumentLive(A);
470 } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
471 if (Function *F = CI->getCalledFunction())
472 MarkRetValLive(F);
473 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
474 if (Function *F = II->getCalledFunction())
475 MarkRetValLive(F);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000476 }
477}
478
479// RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
480// specified by the DeadArguments list. Transform the function and all of the
481// callees of the function to not have these arguments.
482//
Chris Lattner0658cc22003-10-23 03:48:17 +0000483void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000484 // Start by computing a new prototype for the function, which is the same as
485 // the old function, but has fewer arguments.
486 const FunctionType *FTy = F->getFunctionType();
487 std::vector<const Type*> Params;
488
Chris Lattner531f9e92005-03-15 04:54:21 +0000489 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner13bf28c2003-06-17 22:21:05 +0000490 if (!DeadArguments.count(I))
491 Params.push_back(I->getType());
492
Chris Lattner0658cc22003-10-23 03:48:17 +0000493 const Type *RetTy = FTy->getReturnType();
494 if (DeadRetVal.count(F)) {
495 RetTy = Type::VoidTy;
496 DeadRetVal.erase(F);
497 }
498
Chris Lattner05c71fb2003-10-23 17:44:53 +0000499 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
500 // have zero fixed arguments.
501 //
Chris Lattner05c71fb2003-10-23 17:44:53 +0000502 bool ExtraArgHack = false;
503 if (Params.empty() && FTy->isVarArg()) {
504 ExtraArgHack = true;
Reid Spencerc635f472006-12-31 05:48:39 +0000505 Params.push_back(Type::Int32Ty);
Chris Lattner05c71fb2003-10-23 17:44:53 +0000506 }
507
Chris Lattner0658cc22003-10-23 03:48:17 +0000508 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
509
Chris Lattner13bf28c2003-06-17 22:21:05 +0000510 // Create the new function body and insert it into the module...
Chris Lattner2ab04f72003-06-25 04:12:49 +0000511 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000512 NF->setCallingConv(F->getCallingConv());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000513 F->getParent()->getFunctionList().insert(F, NF);
514
515 // Loop over all of the callers of the function, transforming the call sites
516 // to pass in a smaller number of arguments into the new function.
517 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000518 std::vector<Value*> Args;
Chris Lattner13bf28c2003-06-17 22:21:05 +0000519 while (!F->use_empty()) {
520 CallSite CS = CallSite::get(F->use_back());
521 Instruction *Call = CS.getInstruction();
Chris Lattner0658cc22003-10-23 03:48:17 +0000522
Chris Lattner13bf28c2003-06-17 22:21:05 +0000523 // Loop over the operands, deleting dead ones...
524 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner53db5462005-05-06 05:34:40 +0000525 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
526 I != E; ++I, ++AI)
Chris Lattner0658cc22003-10-23 03:48:17 +0000527 if (!DeadArguments.count(I)) // Remove operands for dead arguments
528 Args.push_back(*AI);
529
Chris Lattner05c71fb2003-10-23 17:44:53 +0000530 if (ExtraArgHack)
Reid Spencerc635f472006-12-31 05:48:39 +0000531 Args.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner05c71fb2003-10-23 17:44:53 +0000532
533 // Push any varargs arguments on the list
534 for (; AI != CS.arg_end(); ++AI)
535 Args.push_back(*AI);
536
Chris Lattner0658cc22003-10-23 03:48:17 +0000537 Instruction *New;
538 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000539 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner0658cc22003-10-23 03:48:17 +0000540 Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000541 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner0658cc22003-10-23 03:48:17 +0000542 } else {
543 New = new CallInst(NF, Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000544 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner324d2ee2005-05-06 06:46:58 +0000545 if (cast<CallInst>(Call)->isTailCall())
546 cast<CallInst>(New)->setTailCall();
Chris Lattner0658cc22003-10-23 03:48:17 +0000547 }
548 Args.clear();
549
550 if (!Call->use_empty()) {
551 if (New->getType() == Type::VoidTy)
552 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
553 else {
554 Call->replaceAllUsesWith(New);
555 std::string Name = Call->getName();
556 Call->setName("");
557 New->setName(Name);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000558 }
Chris Lattner0658cc22003-10-23 03:48:17 +0000559 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000560
Chris Lattner0658cc22003-10-23 03:48:17 +0000561 // Finally, remove the old call from the program, reducing the use-count of
562 // F.
563 Call->getParent()->getInstList().erase(Call);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000564 }
565
566 // Since we have now created the new function, splice the body of the old
567 // function right into the new function, leaving the old rotting hulk of the
568 // function empty.
569 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
570
571 // Loop over the argument list, transfering uses of the old arguments over to
572 // the new arguments, also transfering over the names as well. While we're at
573 // it, remove the dead arguments from the DeadArguments list.
574 //
Chris Lattner53db5462005-05-06 05:34:40 +0000575 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
576 I2 = NF->arg_begin();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000577 I != E; ++I)
578 if (!DeadArguments.count(I)) {
579 // If this is a live argument, move the name and users over to the new
580 // version.
581 I->replaceAllUsesWith(I2);
582 I2->setName(I->getName());
583 ++I2;
584 } else {
585 // If this argument is dead, replace any uses of it with null constants
586 // (these are guaranteed to only be operands to call instructions which
587 // will later be simplified).
588 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
589 DeadArguments.erase(I);
590 }
591
Chris Lattner0658cc22003-10-23 03:48:17 +0000592 // If we change the return value of the function we must rewrite any return
593 // instructions. Check this now.
594 if (F->getReturnType() != NF->getReturnType())
595 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
596 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
597 new ReturnInst(0, RI);
598 BB->getInstList().erase(RI);
599 }
600
Chris Lattner13bf28c2003-06-17 22:21:05 +0000601 // Now that the old function is dead, delete it.
602 F->getParent()->getFunctionList().erase(F);
603}
604
Chris Lattner4f2cf032004-09-20 04:48:05 +0000605bool DAE::runOnModule(Module &M) {
Chris Lattner13bf28c2003-06-17 22:21:05 +0000606 // First phase: loop through the module, determining which arguments are live.
607 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000608 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner13bf28c2003-06-17 22:21:05 +0000609 //
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000610 DOUT << "DAE - Determining liveness\n";
Chris Lattner67a35bb2006-09-18 07:02:31 +0000611 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
612 Function &F = *I++;
613 if (F.getFunctionType()->isVarArg())
614 if (DeleteDeadVarargs(F))
615 continue;
616
617 SurveyFunction(F);
618 }
Chris Lattner0658cc22003-10-23 03:48:17 +0000619
620 // Loop over the instructions to inspect, propagating liveness among arguments
621 // and return values which are MaybeLive.
622
623 while (!InstructionsToInspect.empty()) {
624 Instruction *I = InstructionsToInspect.back();
625 InstructionsToInspect.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000626
Chris Lattner0658cc22003-10-23 03:48:17 +0000627 if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
628 // For return instructions, we just have to check to see if the return
629 // value for the current function is known now to be alive. If so, any
630 // arguments used by it are now alive, and any call instruction return
631 // value is alive as well.
632 if (LiveRetVal.count(RI->getParent()->getParent()))
633 MarkReturnInstArgumentLive(RI);
634
Chris Lattner13bf28c2003-06-17 22:21:05 +0000635 } else {
Chris Lattner0658cc22003-10-23 03:48:17 +0000636 CallSite CS = CallSite::get(I);
637 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
Chris Lattner13bf28c2003-06-17 22:21:05 +0000638
Chris Lattner0658cc22003-10-23 03:48:17 +0000639 Function *Callee = CS.getCalledFunction();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000640
Chris Lattner0658cc22003-10-23 03:48:17 +0000641 // If we found a call or invoke instruction on this list, that means that
642 // an argument of the function is a call instruction. If the argument is
643 // live, then the return value of the called instruction is now live.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000644 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000645 CallSite::arg_iterator AI = CS.arg_begin(); // ActualIterator
Chris Lattner53db5462005-05-06 05:34:40 +0000646 for (Function::arg_iterator FI = Callee->arg_begin(),
647 E = Callee->arg_end(); FI != E; ++AI, ++FI) {
Chris Lattner0658cc22003-10-23 03:48:17 +0000648 // If this argument is another call...
649 CallSite ArgCS = CallSite::get(*AI);
650 if (ArgCS.getInstruction() && LiveArguments.count(FI))
651 if (Function *Callee = ArgCS.getCalledFunction())
652 MarkRetValLive(Callee);
653 }
Chris Lattner13bf28c2003-06-17 22:21:05 +0000654 }
655 }
656
657 // Now we loop over all of the MaybeLive arguments, promoting them to be live
658 // arguments if one of the calls that uses the arguments to the calls they are
659 // passed into requires them to be live. Of course this could make other
660 // arguments live, so process callers recursively.
661 //
Chris Lattner0658cc22003-10-23 03:48:17 +0000662 // Because elements can be removed from the MaybeLiveArguments set, copy it to
663 // a temporary vector.
Chris Lattner13bf28c2003-06-17 22:21:05 +0000664 //
665 std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
666 MaybeLiveArguments.end());
667 for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
668 Argument *MLA = TmpArgList[i];
669 if (MaybeLiveArguments.count(MLA) &&
Chris Lattner0658cc22003-10-23 03:48:17 +0000670 isMaybeLiveArgumentNowLive(MLA))
671 MarkArgumentLive(MLA);
Chris Lattner13bf28c2003-06-17 22:21:05 +0000672 }
673
674 // Recover memory early...
675 CallSites.clear();
676
677 // At this point, we know that all arguments in DeadArguments and
678 // MaybeLiveArguments are dead. If the two sets are empty, there is nothing
679 // to do.
Chris Lattner0658cc22003-10-23 03:48:17 +0000680 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
681 MaybeLiveRetVal.empty() && DeadRetVal.empty())
Chris Lattner13bf28c2003-06-17 22:21:05 +0000682 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000683
Chris Lattner13bf28c2003-06-17 22:21:05 +0000684 // Otherwise, compact into one set, and start eliminating the arguments from
685 // the functions.
686 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
687 MaybeLiveArguments.clear();
Chris Lattner0658cc22003-10-23 03:48:17 +0000688 DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
689 MaybeLiveRetVal.clear();
690
691 LiveArguments.clear();
692 LiveRetVal.clear();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000693
694 NumArgumentsEliminated += DeadArguments.size();
Chris Lattner0658cc22003-10-23 03:48:17 +0000695 NumRetValsEliminated += DeadRetVal.size();
Chris Lattner13bf28c2003-06-17 22:21:05 +0000696 while (!DeadArguments.empty())
Chris Lattner0658cc22003-10-23 03:48:17 +0000697 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
698
699 while (!DeadRetVal.empty())
700 RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());
Chris Lattner13bf28c2003-06-17 22:21:05 +0000701 return true;
702}