blob: 019949c858fc759e1137051a71f7b90495ecd015 [file] [log] [blame]
Chris Lattner08227e42003-06-17 22:21:05 +00001//===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner08227e42003-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 Lattnerc3afd9b2003-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 Lattner08227e42003-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 Lattner543a0272005-06-24 16:00:46 +000020#define DEBUG_TYPE "deadargelim"
Chris Lattner08227e42003-06-17 22:21:05 +000021#include "llvm/Transforms/IPO.h"
Chris Lattner92044ce2006-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 Lattner4af90ab2006-09-18 07:02:31 +000026#include "llvm/IntrinsicInst.h"
Chris Lattner08227e42003-06-17 22:21:05 +000027#include "llvm/Module.h"
28#include "llvm/Pass.h"
Chris Lattner08227e42003-06-17 22:21:05 +000029#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000030#include "llvm/Support/Debug.h"
31#include "llvm/ADT/Statistic.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000032#include "llvm/Support/Compiler.h"
Chris Lattner08227e42003-06-17 22:21:05 +000033#include <set>
Chris Lattner1e2385b2003-11-21 21:54:22 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Chris Lattner86453c52006-12-19 22:09:18 +000036STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
37STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
Chris Lattner08227e42003-06-17 22:21:05 +000038
Chris Lattner86453c52006-12-19 22:09:18 +000039namespace {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000040 /// DAE - The dead argument elimination pass.
41 ///
Reid Spencer9133fe22007-02-05 23:32:05 +000042 class VISIBILITY_HIDDEN DAE : public ModulePass {
Chris Lattnerc3afd9b2003-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:
Devang Patel19974732007-05-03 01:11:54 +000079 static char ID; // Pass identifcation, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000080 DAE() : ModulePass((intptr_t)&ID) {}
Chris Lattnerb12914b2004-09-20 04:48:05 +000081 bool runOnModule(Module &M);
Chris Lattner9b2a14b2003-06-25 04:12:49 +000082
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +000083 virtual bool ShouldHackArguments() const { return false; }
84
Chris Lattner9b2a14b2003-06-25 04:12:49 +000085 private:
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000086 Liveness getArgumentLiveness(const Argument &A);
87 bool isMaybeLiveArgumentNowLive(Argument *Arg);
88
Chris Lattner4af90ab2006-09-18 07:02:31 +000089 bool DeleteDeadVarargs(Function &Fn);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000090 void SurveyFunction(Function &Fn);
91
92 void MarkArgumentLive(Argument *Arg);
93 void MarkRetValLive(Function *F);
94 void MarkReturnInstArgumentLive(ReturnInst *RI);
Misha Brukmanfd939082005-04-21 23:48:37 +000095
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000096 void RemoveDeadArgumentsFromFunction(Function *F);
Chris Lattner08227e42003-06-17 22:21:05 +000097 };
Devang Patel19974732007-05-03 01:11:54 +000098 char DAE::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000099 RegisterPass<DAE> X("deadargelim", "Dead Argument Elimination");
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000100
101 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
102 /// deletes arguments to functions which are external. This is only for use
103 /// by bugpoint.
104 struct DAH : public DAE {
Devang Patel19974732007-05-03 01:11:54 +0000105 static char ID;
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000106 virtual bool ShouldHackArguments() const { return true; }
107 };
Devang Patel19974732007-05-03 01:11:54 +0000108 char DAH::ID = 0;
Chris Lattnerb6e06312003-11-05 21:53:41 +0000109 RegisterPass<DAH> Y("deadarghaX0r",
Brian Gaeke09ca4112004-02-02 19:32:27 +0000110 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
Chris Lattner08227e42003-06-17 22:21:05 +0000111}
112
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000113/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000114/// which are not used by the body of the function.
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000115///
Chris Lattnerb12914b2004-09-20 04:48:05 +0000116ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
117ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner08227e42003-06-17 22:21:05 +0000118
Chris Lattner4af90ab2006-09-18 07:02:31 +0000119/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
120/// llvm.vastart is never called, the varargs list is dead for the function.
121bool DAE::DeleteDeadVarargs(Function &Fn) {
122 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
Reid Spencer5cbf9852007-01-30 20:08:39 +0000123 if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
Chris Lattner4af90ab2006-09-18 07:02:31 +0000124
125 // Ensure that the function is only directly called.
126 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
127 // If this use is anything other than a call site, give up.
128 CallSite CS = CallSite::get(*I);
129 Instruction *TheCall = CS.getInstruction();
130 if (!TheCall) return false; // Not a direct call site?
131
132 // The addr of this function is passed to the call.
133 if (I.getOperandNo() != 0) return false;
134 }
135
136 // Okay, we know we can transform this function if safe. Scan its body
137 // looking for calls to llvm.vastart.
138 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
139 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
140 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
141 if (II->getIntrinsicID() == Intrinsic::vastart)
142 return false;
143 }
144 }
145 }
146
147 // If we get here, there are no calls to llvm.vastart in the function body,
148 // remove the "..." and adjust all the calls.
149
150 // Start by computing a new prototype for the function, which is the same as
151 // the old function, but has fewer arguments.
152 const FunctionType *FTy = Fn.getFunctionType();
153 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
154 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
155 unsigned NumArgs = Params.size();
156
157 // Create the new function body and insert it into the module...
Chris Lattner046800a2007-02-11 01:08:35 +0000158 Function *NF = new Function(NFTy, Fn.getLinkage());
Chris Lattner4af90ab2006-09-18 07:02:31 +0000159 NF->setCallingConv(Fn.getCallingConv());
160 Fn.getParent()->getFunctionList().insert(&Fn, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000161 NF->takeName(&Fn);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000162
163 // Loop over all of the callers of the function, transforming the call sites
164 // to pass in a smaller number of arguments into the new function.
165 //
166 std::vector<Value*> Args;
167 while (!Fn.use_empty()) {
168 CallSite CS = CallSite::get(Fn.use_back());
169 Instruction *Call = CS.getInstruction();
170
171 // Loop over the operands, dropping extraneous ones at the end of the list.
172 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
173
174 Instruction *New;
175 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
176 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +0000177 &Args[0], Args.size(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000178 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
179 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +0000180 New = new CallInst(NF, &Args[0], Args.size(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000181 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
182 if (cast<CallInst>(Call)->isTailCall())
183 cast<CallInst>(New)->setTailCall();
184 }
185 Args.clear();
186
187 if (!Call->use_empty())
188 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
189
Chris Lattner046800a2007-02-11 01:08:35 +0000190 New->takeName(Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000191
192 // Finally, remove the old call from the program, reducing the use-count of
193 // F.
194 Call->getParent()->getInstList().erase(Call);
195 }
196
197 // Since we have now created the new function, splice the body of the old
198 // function right into the new function, leaving the old rotting hulk of the
199 // function empty.
200 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
201
202 // Loop over the argument list, transfering uses of the old arguments over to
203 // the new arguments, also transfering over the names as well. While we're at
204 // it, remove the dead arguments from the DeadArguments list.
205 //
206 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
207 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
208 // Move the name and users over to the new version.
209 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000210 I2->takeName(I);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000211 }
212
213 // Finally, nuke the old function.
214 Fn.eraseFromParent();
215 return true;
216}
217
218
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000219static inline bool CallPassesValueThoughVararg(Instruction *Call,
220 const Value *Arg) {
221 CallSite CS = CallSite::get(Call);
222 const Type *CalledValueTy = CS.getCalledValue()->getType();
223 const Type *FTy = cast<PointerType>(CalledValueTy)->getElementType();
224 unsigned NumFixedArgs = cast<FunctionType>(FTy)->getNumParams();
225 for (CallSite::arg_iterator AI = CS.arg_begin()+NumFixedArgs;
226 AI != CS.arg_end(); ++AI)
227 if (AI->get() == Arg)
228 return true;
Chris Lattner08227e42003-06-17 22:21:05 +0000229 return false;
230}
231
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000232// getArgumentLiveness - Inspect an argument, determining if is known Live
Chris Lattner08227e42003-06-17 22:21:05 +0000233// (used in a computation), MaybeLive (only passed as an argument to a call), or
234// Dead (not used).
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000235DAE::Liveness DAE::getArgumentLiveness(const Argument &A) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +0000236 const FunctionType *FTy = A.getParent()->getFunctionType();
237
238 // If this is the return value of a struct function, it's not really dead.
239 if (FTy->isStructReturn() && &*A.getParent()->arg_begin() == &A)
Chris Lattner92044ce2006-06-27 21:05:04 +0000240 return Live;
241
242 if (A.use_empty()) // First check, directly dead?
243 return Dead;
Chris Lattner08227e42003-06-17 22:21:05 +0000244
245 // Scan through all of the uses, looking for non-argument passing uses.
246 for (Value::use_const_iterator I = A.use_begin(), E = A.use_end(); I!=E;++I) {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000247 // Return instructions do not immediately effect liveness.
248 if (isa<ReturnInst>(*I))
249 continue;
250
Chris Lattner08227e42003-06-17 22:21:05 +0000251 CallSite CS = CallSite::get(const_cast<User*>(*I));
252 if (!CS.getInstruction()) {
253 // If its used by something that is not a call or invoke, it's alive!
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000254 return Live;
Chris Lattner08227e42003-06-17 22:21:05 +0000255 }
256 // If it's an indirect call, mark it alive...
257 Function *Callee = CS.getCalledFunction();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000258 if (!Callee) return Live;
Chris Lattner08227e42003-06-17 22:21:05 +0000259
Chris Lattner97f4b662003-06-18 16:25:51 +0000260 // Check to see if it's passed through a va_arg area: if so, we cannot
261 // remove it.
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000262 if (CallPassesValueThoughVararg(CS.getInstruction(), &A))
263 return Live; // If passed through va_arg area, we cannot remove it
Chris Lattner08227e42003-06-17 22:21:05 +0000264 }
265
266 return MaybeLive; // It must be used, but only as argument to a function
267}
268
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000269
270// SurveyFunction - This performs the initial survey of the specified function,
271// checking out whether or not it uses any of its incoming arguments or whether
272// any callers use the return value. This fills in the
273// (Dead|MaybeLive|Live)(Arguments|RetVal) sets.
Chris Lattner08227e42003-06-17 22:21:05 +0000274//
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000275// We consider arguments of non-internal functions to be intrinsically alive as
276// well as arguments to functions which have their "address taken".
277//
278void DAE::SurveyFunction(Function &F) {
279 bool FunctionIntrinsicallyLive = false;
280 Liveness RetValLiveness = F.getReturnType() == Type::VoidTy ? Live : Dead;
281
Chris Lattnerb6e06312003-11-05 21:53:41 +0000282 if (!F.hasInternalLinkage() &&
283 (!ShouldHackArguments() || F.getIntrinsicID()))
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000284 FunctionIntrinsicallyLive = true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000285 else
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000286 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
287 // If this use is anything other than a call site, the function is alive.
288 CallSite CS = CallSite::get(*I);
289 Instruction *TheCall = CS.getInstruction();
290 if (!TheCall) { // Not a direct call site?
291 FunctionIntrinsicallyLive = true;
292 break;
293 }
294
295 // Check to see if the return value is used...
296 if (RetValLiveness != Live)
297 for (Value::use_iterator I = TheCall->use_begin(),
298 E = TheCall->use_end(); I != E; ++I)
299 if (isa<ReturnInst>(cast<Instruction>(*I))) {
300 RetValLiveness = MaybeLive;
301 } else if (isa<CallInst>(cast<Instruction>(*I)) ||
302 isa<InvokeInst>(cast<Instruction>(*I))) {
303 if (CallPassesValueThoughVararg(cast<Instruction>(*I), TheCall) ||
304 !CallSite::get(cast<Instruction>(*I)).getCalledFunction()) {
305 RetValLiveness = Live;
306 break;
307 } else {
308 RetValLiveness = MaybeLive;
309 }
310 } else {
311 RetValLiveness = Live;
312 break;
313 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000314
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000315 // If the function is PASSED IN as an argument, its address has been taken
316 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
317 AI != E; ++AI)
318 if (AI->get() == &F) {
319 FunctionIntrinsicallyLive = true;
320 break;
321 }
322 if (FunctionIntrinsicallyLive) break;
323 }
324
325 if (FunctionIntrinsicallyLive) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000326 DOUT << " Intrinsically live fn: " << F.getName() << "\n";
Chris Lattner19bdc032005-05-06 05:34:40 +0000327 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
328 AI != E; ++AI)
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000329 LiveArguments.insert(AI);
330 LiveRetVal.insert(&F);
331 return;
332 }
333
334 switch (RetValLiveness) {
335 case Live: LiveRetVal.insert(&F); break;
336 case MaybeLive: MaybeLiveRetVal.insert(&F); break;
337 case Dead: DeadRetVal.insert(&F); break;
338 }
339
Bill Wendling0a81aac2006-11-26 10:02:32 +0000340 DOUT << " Inspecting args for fn: " << F.getName() << "\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000341
342 // If it is not intrinsically alive, we know that all users of the
343 // function are call sites. Mark all of the arguments live which are
344 // directly used, and keep track of all of the call sites of this function
345 // if there are any arguments we assume that are dead.
346 //
347 bool AnyMaybeLiveArgs = false;
Chris Lattner19bdc032005-05-06 05:34:40 +0000348 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
349 AI != E; ++AI)
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000350 switch (getArgumentLiveness(*AI)) {
351 case Live:
Bill Wendling0a81aac2006-11-26 10:02:32 +0000352 DOUT << " Arg live by use: " << AI->getName() << "\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000353 LiveArguments.insert(AI);
354 break;
355 case Dead:
Bill Wendling0a81aac2006-11-26 10:02:32 +0000356 DOUT << " Arg definitely dead: " << AI->getName() <<"\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000357 DeadArguments.insert(AI);
358 break;
359 case MaybeLive:
Bill Wendling0a81aac2006-11-26 10:02:32 +0000360 DOUT << " Arg only passed to calls: " << AI->getName() << "\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000361 AnyMaybeLiveArgs = true;
362 MaybeLiveArguments.insert(AI);
363 break;
364 }
365
366 // If there are any "MaybeLive" arguments, we need to check callees of
367 // this function when/if they become alive. Record which functions are
368 // callees...
369 if (AnyMaybeLiveArgs || RetValLiveness == MaybeLive)
370 for (Value::use_iterator I = F.use_begin(), E = F.use_end();
371 I != E; ++I) {
372 if (AnyMaybeLiveArgs)
373 CallSites.insert(std::make_pair(&F, CallSite::get(*I)));
374
375 if (RetValLiveness == MaybeLive)
376 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
377 UI != E; ++UI)
378 InstructionsToInspect.push_back(cast<Instruction>(*UI));
379 }
380}
381
382// isMaybeLiveArgumentNowLive - Check to see if Arg is alive. At this point, we
383// know that the only uses of Arg are to be passed in as an argument to a
384// function call or return. Check to see if the formal argument passed in is in
385// the LiveArguments set. If so, return true.
386//
387bool DAE::isMaybeLiveArgumentNowLive(Argument *Arg) {
Chris Lattner08227e42003-06-17 22:21:05 +0000388 for (Value::use_iterator I = Arg->use_begin(), E = Arg->use_end(); I!=E; ++I){
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000389 if (isa<ReturnInst>(*I)) {
390 if (LiveRetVal.count(Arg->getParent())) return true;
391 continue;
392 }
393
Chris Lattner08227e42003-06-17 22:21:05 +0000394 CallSite CS = CallSite::get(*I);
395
396 // We know that this can only be used for direct calls...
Chris Lattnerd6d0d8c2003-11-02 02:06:27 +0000397 Function *Callee = CS.getCalledFunction();
Chris Lattner08227e42003-06-17 22:21:05 +0000398
399 // Loop over all of the arguments (because Arg may be passed into the call
400 // multiple times) and check to see if any are now alive...
401 CallSite::arg_iterator CSAI = CS.arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000402 for (Function::arg_iterator AI = Callee->arg_begin(), E = Callee->arg_end();
Chris Lattner08227e42003-06-17 22:21:05 +0000403 AI != E; ++AI, ++CSAI)
404 // If this is the argument we are looking for, check to see if it's alive
405 if (*CSAI == Arg && LiveArguments.count(AI))
406 return true;
407 }
408 return false;
409}
410
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000411/// MarkArgumentLive - The MaybeLive argument 'Arg' is now known to be alive.
412/// Mark it live in the specified sets and recursively mark arguments in callers
413/// live that are needed to pass in a value.
414///
415void DAE::MarkArgumentLive(Argument *Arg) {
416 std::set<Argument*>::iterator It = MaybeLiveArguments.lower_bound(Arg);
417 if (It == MaybeLiveArguments.end() || *It != Arg) return;
Misha Brukmanfd939082005-04-21 23:48:37 +0000418
Bill Wendling0a81aac2006-11-26 10:02:32 +0000419 DOUT << " MaybeLive argument now live: " << Arg->getName() <<"\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000420 MaybeLiveArguments.erase(It);
Chris Lattner08227e42003-06-17 22:21:05 +0000421 LiveArguments.insert(Arg);
Misha Brukmanfd939082005-04-21 23:48:37 +0000422
Chris Lattner08227e42003-06-17 22:21:05 +0000423 // Loop over all of the call sites of the function, making any arguments
424 // passed in to provide a value for this argument live as necessary.
425 //
426 Function *Fn = Arg->getParent();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000427 unsigned ArgNo = std::distance(Fn->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner08227e42003-06-17 22:21:05 +0000428
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000429 std::multimap<Function*, CallSite>::iterator I = CallSites.lower_bound(Fn);
Chris Lattner08227e42003-06-17 22:21:05 +0000430 for (; I != CallSites.end() && I->first == Fn; ++I) {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000431 CallSite CS = I->second;
432 Value *ArgVal = *(CS.arg_begin()+ArgNo);
433 if (Argument *ActualArg = dyn_cast<Argument>(ArgVal)) {
434 MarkArgumentLive(ActualArg);
435 } else {
436 // If the value passed in at this call site is a return value computed by
437 // some other call site, make sure to mark the return value at the other
438 // call site as being needed.
439 CallSite ArgCS = CallSite::get(ArgVal);
440 if (ArgCS.getInstruction())
441 if (Function *Fn = ArgCS.getCalledFunction())
442 MarkRetValLive(Fn);
443 }
444 }
445}
446
447/// MarkArgumentLive - The MaybeLive return value for the specified function is
448/// now known to be alive. Propagate this fact to the return instructions which
449/// produce it.
450void DAE::MarkRetValLive(Function *F) {
451 assert(F && "Shame shame, we can't have null pointers here!");
452
453 // Check to see if we already knew it was live
454 std::set<Function*>::iterator I = MaybeLiveRetVal.lower_bound(F);
455 if (I == MaybeLiveRetVal.end() || *I != F) return; // It's already alive!
456
Bill Wendling0a81aac2006-11-26 10:02:32 +0000457 DOUT << " MaybeLive retval now live: " << F->getName() << "\n";
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000458
459 MaybeLiveRetVal.erase(I);
460 LiveRetVal.insert(F); // It is now known to be live!
461
462 // Loop over all of the functions, noticing that the return value is now live.
463 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
464 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
465 MarkReturnInstArgumentLive(RI);
466}
467
468void DAE::MarkReturnInstArgumentLive(ReturnInst *RI) {
469 Value *Op = RI->getOperand(0);
470 if (Argument *A = dyn_cast<Argument>(Op)) {
471 MarkArgumentLive(A);
472 } else if (CallInst *CI = dyn_cast<CallInst>(Op)) {
473 if (Function *F = CI->getCalledFunction())
474 MarkRetValLive(F);
475 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
476 if (Function *F = II->getCalledFunction())
477 MarkRetValLive(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000478 }
479}
480
481// RemoveDeadArgumentsFromFunction - We know that F has dead arguments, as
482// specified by the DeadArguments list. Transform the function and all of the
483// callees of the function to not have these arguments.
484//
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000485void DAE::RemoveDeadArgumentsFromFunction(Function *F) {
Chris Lattner08227e42003-06-17 22:21:05 +0000486 // Start by computing a new prototype for the function, which is the same as
487 // the old function, but has fewer arguments.
488 const FunctionType *FTy = F->getFunctionType();
489 std::vector<const Type*> Params;
490
Chris Lattnere4d5c442005-03-15 04:54:21 +0000491 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner08227e42003-06-17 22:21:05 +0000492 if (!DeadArguments.count(I))
493 Params.push_back(I->getType());
494
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000495 const Type *RetTy = FTy->getReturnType();
496 if (DeadRetVal.count(F)) {
497 RetTy = Type::VoidTy;
498 DeadRetVal.erase(F);
499 }
500
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000501 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
502 // have zero fixed arguments.
503 //
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000504 bool ExtraArgHack = false;
505 if (Params.empty() && FTy->isVarArg()) {
506 ExtraArgHack = true;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000507 Params.push_back(Type::Int32Ty);
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000508 }
509
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000510 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
511
Chris Lattner08227e42003-06-17 22:21:05 +0000512 // Create the new function body and insert it into the module...
Chris Lattner046800a2007-02-11 01:08:35 +0000513 Function *NF = new Function(NFTy, F->getLinkage());
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000514 NF->setCallingConv(F->getCallingConv());
Chris Lattner08227e42003-06-17 22:21:05 +0000515 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000516 NF->takeName(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000517
518 // Loop over all of the callers of the function, transforming the call sites
519 // to pass in a smaller number of arguments into the new function.
520 //
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000521 std::vector<Value*> Args;
Chris Lattner08227e42003-06-17 22:21:05 +0000522 while (!F->use_empty()) {
523 CallSite CS = CallSite::get(F->use_back());
524 Instruction *Call = CS.getInstruction();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000525
Chris Lattner08227e42003-06-17 22:21:05 +0000526 // Loop over the operands, deleting dead ones...
527 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner19bdc032005-05-06 05:34:40 +0000528 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
529 I != E; ++I, ++AI)
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000530 if (!DeadArguments.count(I)) // Remove operands for dead arguments
531 Args.push_back(*AI);
532
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000533 if (ExtraArgHack)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000534 Args.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000535
536 // Push any varargs arguments on the list
537 for (; AI != CS.arg_end(); ++AI)
538 Args.push_back(*AI);
539
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000540 Instruction *New;
541 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +0000542 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +0000543 &Args[0], Args.size(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000544 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000545 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +0000546 New = new CallInst(NF, &Args[0], Args.size(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000547 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner1430ef12005-05-06 06:46:58 +0000548 if (cast<CallInst>(Call)->isTailCall())
549 cast<CallInst>(New)->setTailCall();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000550 }
551 Args.clear();
552
553 if (!Call->use_empty()) {
554 if (New->getType() == Type::VoidTy)
555 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
556 else {
557 Call->replaceAllUsesWith(New);
Chris Lattner046800a2007-02-11 01:08:35 +0000558 New->takeName(Call);
Chris Lattner08227e42003-06-17 22:21:05 +0000559 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000560 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000561
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000562 // Finally, remove the old call from the program, reducing the use-count of
563 // F.
564 Call->getParent()->getInstList().erase(Call);
Chris Lattner08227e42003-06-17 22:21:05 +0000565 }
566
567 // Since we have now created the new function, splice the body of the old
568 // function right into the new function, leaving the old rotting hulk of the
569 // function empty.
570 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
571
572 // Loop over the argument list, transfering uses of the old arguments over to
573 // the new arguments, also transfering over the names as well. While we're at
574 // it, remove the dead arguments from the DeadArguments list.
575 //
Chris Lattner19bdc032005-05-06 05:34:40 +0000576 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
577 I2 = NF->arg_begin();
Chris Lattner08227e42003-06-17 22:21:05 +0000578 I != E; ++I)
579 if (!DeadArguments.count(I)) {
580 // If this is a live argument, move the name and users over to the new
581 // version.
582 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000583 I2->takeName(I);
Chris Lattner08227e42003-06-17 22:21:05 +0000584 ++I2;
585 } else {
586 // If this argument is dead, replace any uses of it with null constants
587 // (these are guaranteed to only be operands to call instructions which
588 // will later be simplified).
589 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
590 DeadArguments.erase(I);
591 }
592
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000593 // If we change the return value of the function we must rewrite any return
594 // instructions. Check this now.
595 if (F->getReturnType() != NF->getReturnType())
596 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
597 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
598 new ReturnInst(0, RI);
599 BB->getInstList().erase(RI);
600 }
601
Chris Lattner08227e42003-06-17 22:21:05 +0000602 // Now that the old function is dead, delete it.
603 F->getParent()->getFunctionList().erase(F);
604}
605
Chris Lattnerb12914b2004-09-20 04:48:05 +0000606bool DAE::runOnModule(Module &M) {
Chris Lattner08227e42003-06-17 22:21:05 +0000607 // First phase: loop through the module, determining which arguments are live.
608 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000609 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner08227e42003-06-17 22:21:05 +0000610 //
Bill Wendling0a81aac2006-11-26 10:02:32 +0000611 DOUT << "DAE - Determining liveness\n";
Chris Lattner4af90ab2006-09-18 07:02:31 +0000612 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
613 Function &F = *I++;
614 if (F.getFunctionType()->isVarArg())
615 if (DeleteDeadVarargs(F))
616 continue;
617
618 SurveyFunction(F);
619 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000620
621 // Loop over the instructions to inspect, propagating liveness among arguments
622 // and return values which are MaybeLive.
623
624 while (!InstructionsToInspect.empty()) {
625 Instruction *I = InstructionsToInspect.back();
626 InstructionsToInspect.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000627
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000628 if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
629 // For return instructions, we just have to check to see if the return
630 // value for the current function is known now to be alive. If so, any
631 // arguments used by it are now alive, and any call instruction return
632 // value is alive as well.
633 if (LiveRetVal.count(RI->getParent()->getParent()))
634 MarkReturnInstArgumentLive(RI);
635
Chris Lattner08227e42003-06-17 22:21:05 +0000636 } else {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000637 CallSite CS = CallSite::get(I);
638 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
Chris Lattner08227e42003-06-17 22:21:05 +0000639
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000640 Function *Callee = CS.getCalledFunction();
Misha Brukmanfd939082005-04-21 23:48:37 +0000641
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000642 // If we found a call or invoke instruction on this list, that means that
643 // an argument of the function is a call instruction. If the argument is
644 // live, then the return value of the called instruction is now live.
Chris Lattner08227e42003-06-17 22:21:05 +0000645 //
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000646 CallSite::arg_iterator AI = CS.arg_begin(); // ActualIterator
Chris Lattner19bdc032005-05-06 05:34:40 +0000647 for (Function::arg_iterator FI = Callee->arg_begin(),
648 E = Callee->arg_end(); FI != E; ++AI, ++FI) {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000649 // If this argument is another call...
650 CallSite ArgCS = CallSite::get(*AI);
651 if (ArgCS.getInstruction() && LiveArguments.count(FI))
652 if (Function *Callee = ArgCS.getCalledFunction())
653 MarkRetValLive(Callee);
654 }
Chris Lattner08227e42003-06-17 22:21:05 +0000655 }
656 }
657
658 // Now we loop over all of the MaybeLive arguments, promoting them to be live
659 // arguments if one of the calls that uses the arguments to the calls they are
660 // passed into requires them to be live. Of course this could make other
661 // arguments live, so process callers recursively.
662 //
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000663 // Because elements can be removed from the MaybeLiveArguments set, copy it to
664 // a temporary vector.
Chris Lattner08227e42003-06-17 22:21:05 +0000665 //
666 std::vector<Argument*> TmpArgList(MaybeLiveArguments.begin(),
667 MaybeLiveArguments.end());
668 for (unsigned i = 0, e = TmpArgList.size(); i != e; ++i) {
669 Argument *MLA = TmpArgList[i];
670 if (MaybeLiveArguments.count(MLA) &&
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000671 isMaybeLiveArgumentNowLive(MLA))
672 MarkArgumentLive(MLA);
Chris Lattner08227e42003-06-17 22:21:05 +0000673 }
674
675 // Recover memory early...
676 CallSites.clear();
677
678 // At this point, we know that all arguments in DeadArguments and
679 // MaybeLiveArguments are dead. If the two sets are empty, there is nothing
680 // to do.
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000681 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
682 MaybeLiveRetVal.empty() && DeadRetVal.empty())
Chris Lattner08227e42003-06-17 22:21:05 +0000683 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000684
Chris Lattner08227e42003-06-17 22:21:05 +0000685 // Otherwise, compact into one set, and start eliminating the arguments from
686 // the functions.
687 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
688 MaybeLiveArguments.clear();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000689 DeadRetVal.insert(MaybeLiveRetVal.begin(), MaybeLiveRetVal.end());
690 MaybeLiveRetVal.clear();
691
692 LiveArguments.clear();
693 LiveRetVal.clear();
Chris Lattner08227e42003-06-17 22:21:05 +0000694
695 NumArgumentsEliminated += DeadArguments.size();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000696 NumRetValsEliminated += DeadRetVal.size();
Chris Lattner08227e42003-06-17 22:21:05 +0000697 while (!DeadArguments.empty())
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000698 RemoveDeadArgumentsFromFunction((*DeadArguments.begin())->getParent());
699
700 while (!DeadRetVal.empty())
701 RemoveDeadArgumentsFromFunction(*DeadRetVal.begin());
Chris Lattner08227e42003-06-17 22:21:05 +0000702 return true;
703}