blob: 34e73295d770f71d1af013906e7475971936e4c7 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000013// pass also deletes dead return values 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
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000016// interprocedural passes, which add possibly-dead arguments or return values.
Chris Lattner08227e42003-06-17 22:21:05 +000017//
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"
Chris Lattner58d74912008-03-12 17:45:29 +000031#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/ADT/Statistic.h"
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000033#include "llvm/ADT/StringExtras.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000034#include "llvm/Support/Compiler.h"
Dan Gohmanc9235d22008-03-21 23:51:57 +000035#include <map>
Chris Lattner08227e42003-06-17 22:21:05 +000036#include <set>
Chris Lattner1e2385b2003-11-21 21:54:22 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Chris Lattner86453c52006-12-19 22:09:18 +000039STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
40STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
Chris Lattner08227e42003-06-17 22:21:05 +000041
Chris Lattner86453c52006-12-19 22:09:18 +000042namespace {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000043 /// DAE - The dead argument elimination pass.
44 ///
Reid Spencer9133fe22007-02-05 23:32:05 +000045 class VISIBILITY_HIDDEN DAE : public ModulePass {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000046 public:
47
48 /// Struct that represents (part of) either a return value or a function
49 /// argument. Used so that arguments and return values can be used
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +000050 /// interchangably. Idx == -1 means the entire return value, while other
51 /// indices mean the corresponding element in the struct return type (if
52 /// any).
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000053 struct RetOrArg {
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +000054 RetOrArg(const Function* F, signed Idx, bool IsArg) : F(F), Idx(Idx),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000055 IsArg(IsArg) {}
56 const Function *F;
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +000057 signed Idx;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000058 bool IsArg;
59
60 /// Make RetOrArg comparable, so we can put it into a map.
61 bool operator<(const RetOrArg &O) const {
62 if (F != O.F)
63 return F < O.F;
64 else if (Idx != O.Idx)
65 return Idx < O.Idx;
66 else
67 return IsArg < O.IsArg;
68 }
69
70 /// Make RetOrArg comparable, so we can easily iterate the multimap.
71 bool operator==(const RetOrArg &O) const {
72 return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
73 }
74
Matthijs Kooijman6cdd54b2008-07-15 08:56:49 +000075 std::string getDescription() const {
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +000076 return std::string((!IsArg && Idx != -1 ? "partial " : ""))
77 + (IsArg ? "argument #" : "return value")
78 + (!IsArg && Idx == -1 ? "" : " #" + utostr(Idx))
79 + " of function " + F->getName();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000080 }
81 };
82
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000083 /// Liveness enum - During our initial pass over the program, we determine
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000084 /// that things are either alive or maybe alive. We don't mark anything
85 /// explicitly dead (even if we know they are), since anything not alive
86 /// with no registered uses (in Uses) will never be marked alive and will
87 /// thus become dead in the end.
88 enum Liveness { Live, MaybeLive };
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000089
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000090 /// Convenience wrapper
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +000091 RetOrArg CreateRet(const Function *F, signed Idx) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000092 return RetOrArg(F, Idx, false);
93 }
94 /// Convenience wrapper
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +000095 RetOrArg CreateArg(const Function *F, signed Idx) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000096 return RetOrArg(F, Idx, true);
97 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000098
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000099 typedef std::multimap<RetOrArg, RetOrArg> UseMap;
100 /// This maps a return value or argument to any MaybeLive return values or
101 /// arguments it uses. This allows the MaybeLive values to be marked live
102 /// when any of its users is marked live.
103 /// For example (indices are left out for clarity):
104 /// - Uses[ret F] = ret G
105 /// This means that F calls G, and F returns the value returned by G.
106 /// - Uses[arg F] = ret G
107 /// This means that some function calls G and passes its result as an
108 /// argument to F.
109 /// - Uses[ret F] = arg F
110 /// This means that F returns one of its own arguments.
111 /// - Uses[arg F] = arg G
112 /// This means that G calls F and passes one of its own (G's) arguments
113 /// directly to F.
114 UseMap Uses;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000115
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000116 typedef std::set<RetOrArg> LiveSet;
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000117 typedef std::set<const Function*> LiveFuncSet;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000118
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000119 /// This set contains all values that have been determined to be live.
120 LiveSet LiveValues;
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000121 /// This set contains all values that are cannot be changed in any way.
122 LiveFuncSet LiveFunctions;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000123
124 typedef SmallVector<RetOrArg, 5> UseVector;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000125
126 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000127 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +0000128 DAE() : ModulePass((intptr_t)&ID) {}
Chris Lattnerb12914b2004-09-20 04:48:05 +0000129 bool runOnModule(Module &M);
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000130
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000131 virtual bool ShouldHackArguments() const { return false; }
132
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000133 private:
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000134 Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
135 Liveness SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000136 signed RetValNum = -1);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000137 Liveness SurveyUses(Value *V, UseVector &MaybeLiveUses);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000138
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000139 void SurveyFunction(Function &F);
140 void MarkValue(const RetOrArg &RA, Liveness L,
141 const UseVector &MaybeLiveUses);
Matthijs Kooijman6cdd54b2008-07-15 08:56:49 +0000142 void MarkLive(const RetOrArg &RA);
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000143 void MarkLive(const Function &F);
Matthijs Kooijman30156522008-07-15 09:00:17 +0000144 void PropagateLiveness(const RetOrArg &RA);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000145 bool RemoveDeadStuffFromFunction(Function *F);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000146 bool DeleteDeadVarargs(Function &Fn);
Chris Lattner08227e42003-06-17 22:21:05 +0000147 };
Dan Gohman844731a2008-05-13 00:00:25 +0000148}
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000149
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000150
Dan Gohman844731a2008-05-13 00:00:25 +0000151char DAE::ID = 0;
152static RegisterPass<DAE>
153X("deadargelim", "Dead Argument Elimination");
154
155namespace {
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000156 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
157 /// deletes arguments to functions which are external. This is only for use
158 /// by bugpoint.
159 struct DAH : public DAE {
Devang Patel19974732007-05-03 01:11:54 +0000160 static char ID;
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000161 virtual bool ShouldHackArguments() const { return true; }
162 };
Chris Lattner08227e42003-06-17 22:21:05 +0000163}
164
Dan Gohman844731a2008-05-13 00:00:25 +0000165char DAH::ID = 0;
166static RegisterPass<DAH>
167Y("deadarghaX0r", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)");
168
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000169/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000170/// which are not used by the body of the function.
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000171///
Chris Lattnerb12914b2004-09-20 04:48:05 +0000172ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
173ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner08227e42003-06-17 22:21:05 +0000174
Chris Lattner4af90ab2006-09-18 07:02:31 +0000175/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
176/// llvm.vastart is never called, the varargs list is dead for the function.
177bool DAE::DeleteDeadVarargs(Function &Fn) {
178 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
Reid Spencer5cbf9852007-01-30 20:08:39 +0000179 if (Fn.isDeclaration() || !Fn.hasInternalLinkage()) return false;
Duncan Sands110c8352007-12-21 19:16:16 +0000180
Chris Lattner4af90ab2006-09-18 07:02:31 +0000181 // Ensure that the function is only directly called.
182 for (Value::use_iterator I = Fn.use_begin(), E = Fn.use_end(); I != E; ++I) {
183 // If this use is anything other than a call site, give up.
184 CallSite CS = CallSite::get(*I);
185 Instruction *TheCall = CS.getInstruction();
186 if (!TheCall) return false; // Not a direct call site?
Duncan Sands110c8352007-12-21 19:16:16 +0000187
Chris Lattner4af90ab2006-09-18 07:02:31 +0000188 // The addr of this function is passed to the call.
189 if (I.getOperandNo() != 0) return false;
190 }
Duncan Sands110c8352007-12-21 19:16:16 +0000191
Chris Lattner4af90ab2006-09-18 07:02:31 +0000192 // Okay, we know we can transform this function if safe. Scan its body
193 // looking for calls to llvm.vastart.
194 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
195 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
196 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
197 if (II->getIntrinsicID() == Intrinsic::vastart)
198 return false;
199 }
200 }
201 }
Duncan Sands110c8352007-12-21 19:16:16 +0000202
Chris Lattner4af90ab2006-09-18 07:02:31 +0000203 // If we get here, there are no calls to llvm.vastart in the function body,
204 // remove the "..." and adjust all the calls.
Duncan Sands110c8352007-12-21 19:16:16 +0000205
Chris Lattner4af90ab2006-09-18 07:02:31 +0000206 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000207 // the old function, but doesn't have isVarArg set.
Chris Lattner4af90ab2006-09-18 07:02:31 +0000208 const FunctionType *FTy = Fn.getFunctionType();
209 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
210 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), Params, false);
211 unsigned NumArgs = Params.size();
Duncan Sands110c8352007-12-21 19:16:16 +0000212
Chris Lattner4af90ab2006-09-18 07:02:31 +0000213 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000214 Function *NF = Function::Create(NFTy, Fn.getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000215 NF->copyAttributesFrom(&Fn);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000216 Fn.getParent()->getFunctionList().insert(&Fn, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000217 NF->takeName(&Fn);
Duncan Sands110c8352007-12-21 19:16:16 +0000218
Chris Lattner4af90ab2006-09-18 07:02:31 +0000219 // Loop over all of the callers of the function, transforming the call sites
220 // to pass in a smaller number of arguments into the new function.
221 //
222 std::vector<Value*> Args;
223 while (!Fn.use_empty()) {
224 CallSite CS = CallSite::get(Fn.use_back());
225 Instruction *Call = CS.getInstruction();
Duncan Sands110c8352007-12-21 19:16:16 +0000226
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000227 // Pass all the same arguments.
Chris Lattner4af90ab2006-09-18 07:02:31 +0000228 Args.assign(CS.arg_begin(), CS.arg_begin()+NumArgs);
Duncan Sands110c8352007-12-21 19:16:16 +0000229
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000230 // Drop any attributes that were on the vararg arguments.
Chris Lattner58d74912008-03-12 17:45:29 +0000231 PAListPtr PAL = CS.getParamAttrs();
232 if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
233 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
234 for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
235 ParamAttrsVec.push_back(PAL.getSlot(i));
236 PAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000237 }
238
Chris Lattner4af90ab2006-09-18 07:02:31 +0000239 Instruction *New;
240 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000241 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
242 Args.begin(), Args.end(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000243 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000244 cast<InvokeInst>(New)->setParamAttrs(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000245 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000246 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000247 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000248 cast<CallInst>(New)->setParamAttrs(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000249 if (cast<CallInst>(Call)->isTailCall())
250 cast<CallInst>(New)->setTailCall();
251 }
252 Args.clear();
Duncan Sands110c8352007-12-21 19:16:16 +0000253
Chris Lattner4af90ab2006-09-18 07:02:31 +0000254 if (!Call->use_empty())
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000255 Call->replaceAllUsesWith(New);
Duncan Sands110c8352007-12-21 19:16:16 +0000256
Chris Lattner046800a2007-02-11 01:08:35 +0000257 New->takeName(Call);
Duncan Sands110c8352007-12-21 19:16:16 +0000258
Chris Lattner4af90ab2006-09-18 07:02:31 +0000259 // Finally, remove the old call from the program, reducing the use-count of
260 // F.
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000261 Call->eraseFromParent();
Chris Lattner4af90ab2006-09-18 07:02:31 +0000262 }
Duncan Sands110c8352007-12-21 19:16:16 +0000263
Chris Lattner4af90ab2006-09-18 07:02:31 +0000264 // Since we have now created the new function, splice the body of the old
265 // function right into the new function, leaving the old rotting hulk of the
266 // function empty.
267 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
Duncan Sands110c8352007-12-21 19:16:16 +0000268
Chris Lattner4af90ab2006-09-18 07:02:31 +0000269 // Loop over the argument list, transfering uses of the old arguments over to
270 // the new arguments, also transfering over the names as well. While we're at
271 // it, remove the dead arguments from the DeadArguments list.
272 //
273 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
274 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
275 // Move the name and users over to the new version.
276 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000277 I2->takeName(I);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000278 }
Duncan Sands110c8352007-12-21 19:16:16 +0000279
Chris Lattner4af90ab2006-09-18 07:02:31 +0000280 // Finally, nuke the old function.
281 Fn.eraseFromParent();
282 return true;
283}
284
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000285/// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
286/// live, it adds Use to the MaybeLiveUses argument. Returns the determined
287/// liveness of Use.
288DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000289 // We're live if our use or its Function is already marked as live.
290 if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
Chris Lattner92044ce2006-06-27 21:05:04 +0000291 return Live;
Chris Lattner08227e42003-06-17 22:21:05 +0000292
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000293 // We're maybe live otherwise, but remember that we must become live if
294 // Use becomes live.
295 MaybeLiveUses.push_back(Use);
296 return MaybeLive;
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000297}
298
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000299/// SurveyUse - This looks at a single use of an argument or return value
300/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
301/// if it causes the used value to become MaybeAlive.
302///
303/// RetValNum is the return value number to use when this use is used in a
304/// return instruction. This is used in the recursion, you should always leave
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000305/// it at -1.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000306DAE::Liveness DAE::SurveyUse(Value::use_iterator U, UseVector &MaybeLiveUses,
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000307 signed RetValNum) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000308 Value *V = *U;
309 if (ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
310 // The value is returned from a function. It's only live when the
311 // function's return value is live. We use RetValNum here, for the case
312 // that U is really a use of an insertvalue instruction that uses the
313 // orginal Use.
314 RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
315 // We might be live, depending on the liveness of Use.
316 return MarkIfNotLive(Use, MaybeLiveUses);
317 }
318 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
319 if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
320 && IV->hasIndices())
321 // The use we are examining is inserted into an aggregate. Our liveness
322 // depends on all uses of that aggregate, but if it is used as a return
323 // value, only index at which we were inserted counts.
324 RetValNum = *IV->idx_begin();
325
326 // Note that if we are used as the aggregate operand to the insertvalue,
327 // we don't change RetValNum, but do survey all our uses.
328
329 Liveness Result = MaybeLive;
330 for (Value::use_iterator I = IV->use_begin(),
331 E = V->use_end(); I != E; ++I) {
332 Result = SurveyUse(I, MaybeLiveUses, RetValNum);
333 if (Result == Live)
334 break;
335 }
336 return Result;
337 }
338 CallSite CS = CallSite::get(V);
339 if (CS.getInstruction()) {
340 Function *F = CS.getCalledFunction();
341 if (F) {
342 // Used in a direct call.
343
344 // Find the argument number. We know for sure that this use is an
345 // argument, since if it was the function argument this would be an
346 // indirect call and the we know can't be looking at a value of the
347 // label type (for the invoke instruction).
348 unsigned ArgNo = CS.getArgumentNo(U.getOperandNo());
349
350 if (ArgNo >= F->getFunctionType()->getNumParams())
351 // The value is passed in through a vararg! Must be live.
352 return Live;
353
354 assert(CS.getArgument(ArgNo)
355 == CS.getInstruction()->getOperand(U.getOperandNo())
356 && "Argument is not where we expected it");
357
358 // Value passed to a normal call. It's only live when the corresponding
359 // argument to the called function turns out live.
360 RetOrArg Use = CreateArg(F, ArgNo);
361 return MarkIfNotLive(Use, MaybeLiveUses);
362 }
363 }
364 // Used in any other way? Value must be live.
365 return Live;
366}
367
368/// SurveyUses - This looks at all the uses of the given value
369/// Returns the Liveness deduced from the uses of this value.
370///
371/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
372/// the result is Live, MaybeLiveUses might be modified but its content should
373/// be ignored (since it might not be complete).
374DAE::Liveness DAE::SurveyUses(Value *V, UseVector &MaybeLiveUses) {
375 // Assume it's dead (which will only hold if there are no uses at all..).
376 Liveness Result = MaybeLive;
377 // Check each use.
378 for (Value::use_iterator I = V->use_begin(),
379 E = V->use_end(); I != E; ++I) {
380 Result = SurveyUse(I, MaybeLiveUses);
381 if (Result == Live)
382 break;
383 }
384 return Result;
385}
386
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000387// SurveyFunction - This performs the initial survey of the specified function,
388// checking out whether or not it uses any of its incoming arguments or whether
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000389// any callers use the return value. This fills in the LiveValues set and Uses
390// map.
Chris Lattner08227e42003-06-17 22:21:05 +0000391//
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000392// We consider arguments of non-internal functions to be intrinsically alive as
393// well as arguments to functions which have their "address taken".
394//
395void DAE::SurveyFunction(Function &F) {
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000396 const StructType *STy = dyn_cast<StructType>(F.getFunctionType()->getReturnType());
397 // Store the number of partial return values, which we only have if the return
398 // type is a struct.
399 unsigned PartialRetVals = (STy ? STy->getNumElements() : 0);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000400 // Assume all return values are dead
401 typedef SmallVector<Liveness, 5> RetVals;
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000402 // Allocate one slot for the entire return value (index 0) and one for each
403 // partial return value.
404 RetVals RetValLiveness(PartialRetVals + 1, MaybeLive);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000405
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000406 typedef SmallVector<UseVector, 5> RetUses;
407 // These vectors map each return value to the uses that make it MaybeLive, so
408 // we can add those to the Uses map if the return value really turns out to be
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000409 // MaybeLive.
410 // Allocate one slot for the entire return value (index 0) and one for each
411 // partial return value.
412 RetUses MaybeLiveRetUses(PartialRetVals + 1);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000413
414 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
415 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
416 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
417 != F.getFunctionType()->getReturnType()) {
418 // We don't support old style multiple return values.
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000419 MarkLive(F);
420 return;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000421 }
422
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000423 if (!F.hasInternalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
424 MarkLive(F);
425 return;
426 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000427
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000428 DOUT << "DAE - Inspecting callers for fn: " << F.getName() << "\n";
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000429 // Loop all uses of the function.
430 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
431 // If the function is PASSED IN as an argument, its address has been
432 // taken.
433 if (I.getOperandNo() != 0) {
434 MarkLive(F);
435 return;
436 }
Matthijs Kooijman41335412008-06-05 08:34:25 +0000437
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000438 // If this use is anything other than a call site, the function is alive.
439 CallSite CS = CallSite::get(*I);
440 Instruction *TheCall = CS.getInstruction();
441 if (!TheCall) { // Not a direct call site?
442 MarkLive(F);
443 return;
444 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000445
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000446 // If we end up here, we are looking at a direct call to our function.
Evan Cheng890aaa82008-06-25 18:10:09 +0000447
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000448 // Now, check how our return value(s) is/are used in this caller. Don't
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000449 // bother checking return values if the entire value is live already.
450 if (RetValLiveness[0] != Live) {
451 // Check all uses of the return value.
452 for (Value::use_iterator I = TheCall->use_begin(),
453 E = TheCall->use_end(); I != E; ++I) {
454 ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
455 if (Ext && Ext->hasIndices()) {
456 // This use uses a part of our return value, survey the uses of
457 // that part and store the results for this index only.
458 unsigned Idx = *Ext->idx_begin();
459 // + 1 to skip the "entire retval" index (0)
460 Liveness &IsLive = RetValLiveness[Idx + 1];
461 if (IsLive != Live) {
462 // Don't bother checking if this retval was already live
463 // Survey all uses of the extractvalue
464 // + 1 to skip the "entire retval" index (0)
465 IsLive = SurveyUses(Ext, MaybeLiveRetUses[Idx + 1]);
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000466 }
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000467 } else {
468 // Survey this use
469 RetValLiveness[0] = SurveyUse(I, MaybeLiveRetUses[0]);
470 if (RetValLiveness[0] == Live)
471 break;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000472 }
473 }
474 }
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000475 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000476
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000477 // Now we've inspected all callers, record the liveness of our return values.
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000478 MarkValue(CreateRet(&F, -1), RetValLiveness[0], MaybeLiveRetUses[0]);
479 if (RetValLiveness[0] != Live)
480 // If the entire retval (0) is Live, MarkValue will have marked all other retvals live
481 // as well, so we can skip this.
482 for (unsigned i = 0; i != PartialRetVals; ++i)
483 // + 1 to skip the "entire retval" index (0)
484 MarkValue(CreateRet(&F, i), RetValLiveness[i + 1], MaybeLiveRetUses[i + 1]);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000485
486 DOUT << "DAE - Inspecting args for fn: " << F.getName() << "\n";
487
488 // Now, check all of our arguments.
489 unsigned i = 0;
490 UseVector MaybeLiveArgUses;
491 for (Function::arg_iterator AI = F.arg_begin(),
492 E = F.arg_end(); AI != E; ++AI, ++i) {
493 // See what the effect of this use is (recording any uses that cause
494 // MaybeLive in MaybeLiveArgUses).
495 Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
496 // Mark the result.
497 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
498 // Clear the vector again for the next iteration.
499 MaybeLiveArgUses.clear();
Matthijs Kooijmanca85d652008-06-18 11:12:53 +0000500 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000501}
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000502
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000503/// MarkValue - This function marks the liveness of RA depending on L. If L is
504/// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
505/// such that RA will be marked live if any use in MaybeLiveUses gets marked
506/// live later on.
507void DAE::MarkValue(const RetOrArg &RA, Liveness L,
508 const UseVector &MaybeLiveUses) {
509 switch (L) {
510 case Live: MarkLive(RA); break;
Evan Cheng890aaa82008-06-25 18:10:09 +0000511 case MaybeLive:
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000512 {
513 // Note any uses of this value, so this return value can be
514 // marked live whenever one of the uses becomes live.
515 for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
516 UE = MaybeLiveUses.end(); UI != UE; ++UI)
517 Uses.insert(std::make_pair(*UI, RA));
Evan Cheng890aaa82008-06-25 18:10:09 +0000518 break;
519 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000520 }
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000521}
Owen Andersonbb3761c2008-06-18 17:32:16 +0000522
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000523/// MarkLive - Mark the given Function as alive, meaning that it cannot be
524/// changed in any way. Additionally,
525/// mark any values that are used as this function's parameters or by its return
526/// values (according to Uses) live as well.
527void DAE::MarkLive(const Function &F) {
528 DOUT << "DAE - Intrinsically live fn: " << F.getName() << "\n";
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000529 // Mark the function as live.
530 LiveFunctions.insert(&F);
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000531 // Mark all arguments as live.
532 for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000533 PropagateLiveness(CreateArg(&F, i));
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000534 // Mark all return values as live.
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000535 const Type *RTy = F.getFunctionType()->getReturnType();
536 if (const StructType *STy = dyn_cast<StructType>(RTy))
537 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
538 PropagateLiveness(CreateRet(&F, i));
539 PropagateLiveness(CreateRet(&F, -1));
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000540}
541
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000542/// MarkLive - Mark the given return value or argument as live. Additionally,
543/// mark any values that are used by this value (according to Uses) live as
544/// well.
Matthijs Kooijman6cdd54b2008-07-15 08:56:49 +0000545void DAE::MarkLive(const RetOrArg &RA) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000546 if (LiveFunctions.count(RA.F))
547 return; // Function was already marked Live.
548
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000549 if (!LiveValues.insert(RA).second)
550 return; // We were already marked Live.
551
Matthijs Kooijman03016ca2008-07-15 08:53:36 +0000552 DOUT << "DAE - Marking " << RA.getDescription() << " live\n";
Matthijs Kooijman30156522008-07-15 09:00:17 +0000553 PropagateLiveness(RA);
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000554
555 if (!RA.IsArg && RA.Idx == -1) {
556 // Entire return value live?
557 const Type *RTy = RA.F->getFunctionType()->getReturnType();
558 if (const StructType *STy = dyn_cast<StructType>(RTy))
559 // And the function returns a struct?
560 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
561 // Mark all partial return values live as well then
562 MarkLive(CreateRet(RA.F, i));
563 }
Matthijs Kooijman30156522008-07-15 09:00:17 +0000564}
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000565
Matthijs Kooijman30156522008-07-15 09:00:17 +0000566/// PropagateLiveness - Given that RA is a live value, propagate it's liveness
567/// to any other values it uses (according to Uses).
568void DAE::PropagateLiveness(const RetOrArg &RA) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000569 // We don't use upper_bound (or equal_range) here, because our recursive call
570 // to ourselves is likely to cause the upper_bound (which is the first value
571 // not belonging to RA) to become erased and the iterator invalidated.
572 UseMap::iterator Begin = Uses.lower_bound(RA);
573 UseMap::iterator E = Uses.end();
574 UseMap::iterator I;
575 for (I = Begin; I != E && I->first == RA; ++I)
576 MarkLive(I->second);
577
578 // Erase RA from the Uses map (from the lower bound to wherever we ended up
579 // after the loop).
580 Uses.erase(Begin, I);
581}
582
583// RemoveDeadStuffFromFunction - Remove any arguments and return values from F
584// that are not in LiveValues. Transform the function and all of the callees of
585// the function to not have these arguments and return values.
Evan Cheng890aaa82008-06-25 18:10:09 +0000586//
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000587bool DAE::RemoveDeadStuffFromFunction(Function *F) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000588 // Don't modify fully live functions
589 if (LiveFunctions.count(F))
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000590 return false;
Evan Cheng890aaa82008-06-25 18:10:09 +0000591
Chris Lattner08227e42003-06-17 22:21:05 +0000592 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000593 // the old function, but has fewer arguments and a different return type.
Chris Lattner08227e42003-06-17 22:21:05 +0000594 const FunctionType *FTy = F->getFunctionType();
595 std::vector<const Type*> Params;
596
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000597 // Set up to build a new list of parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000598 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
599 const PAListPtr &PAL = F->getParamAttrs();
Chris Lattner08227e42003-06-17 22:21:05 +0000600
Duncan Sands110c8352007-12-21 19:16:16 +0000601 // The existing function return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000602 ParameterAttributes RAttrs = PAL.getParamAttrs(0);
Duncan Sands110c8352007-12-21 19:16:16 +0000603
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000604
605 // Find out the new return value.
606
Duncan Sands110c8352007-12-21 19:16:16 +0000607 const Type *RetTy = FTy->getReturnType();
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000608 const StructType *STy = dyn_cast<StructType>(RetTy);
609 const unsigned PartialRetVals = (STy ? STy->getNumElements() : 0);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000610 const Type *NRetTy = NULL;
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000611 // -1 means unused, other numbers are the new index. Initialized to -1 for
612 // every partial return value we have.
613 SmallVector<int, 5> NewRetIdxs(PartialRetVals, -1);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000614 std::vector<const Type*> RetTypes;
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000615 if (LiveValues.count(CreateRet(F, -1))) {
616 // If the entire return value is live, leave it unchanged.
617 NRetTy = RetTy;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000618 } else {
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000619 if (STy) {
620 // Look at each of the partial return values individually.
621 for (unsigned i = 0; i != PartialRetVals; ++i) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000622 RetOrArg Ret = CreateRet(F, i);
623 if (LiveValues.erase(Ret)) {
624 RetTypes.push_back(STy->getElementType(i));
625 NewRetIdxs[i] = RetTypes.size() - 1;
626 } else {
627 ++NumRetValsEliminated;
628 DOUT << "DAE - Removing return value " << i << " from "
629 << F->getNameStart() << "\n";
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000630 // We remove the value by not adding anything to RetTypes.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000631 }
632 }
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000633 } else if (RetTy != Type::VoidTy) {
634 // We used to return a single value, which is now dead (already checked in
635 // the if above)
636 DOUT << "DAE - Removing return value from " << F->getNameStart()
637 << "\n";
638 ++NumRetValsEliminated;
639 // We remove the value by not adding anything to RetTypes.
640 }
641
642 if (RetTypes.size() > 1)
643 // More than one return type? Return a struct with them.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000644 // Make the new struct packed if we used to return a packed struct
645 // already.
646 NRetTy = StructType::get(RetTypes, STy->isPacked());
647 else if (RetTypes.size() == 1)
648 // One return type? Just a simple value then, but only if we didn't use to
649 // return a struct with that simple value before.
650 NRetTy = RetTypes.front();
651 else if (RetTypes.size() == 0)
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000652 // No return types? Make it void.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000653 NRetTy = Type::VoidTy;
Duncan Sands110c8352007-12-21 19:16:16 +0000654 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000655
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000656 assert(NRetTy && "No new return type found?");
657
658 // Remove any incompatible attributes, but only if we removed all return
659 // values. Otherwise, ensure that we don't have any conflicting attributes
660 // here. Currently, this should not be possible, but special handling might be
661 // required when new return value attributes are added.
662 if (NRetTy == Type::VoidTy)
663 RAttrs &= ~ParamAttr::typeIncompatible(NRetTy);
664 else
665 assert((RAttrs & ParamAttr::typeIncompatible(NRetTy)) == 0
666 && "Return attributes no longer compatible?");
667
Duncan Sands110c8352007-12-21 19:16:16 +0000668 if (RAttrs)
669 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000670
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000671 // Remember which arguments are still alive.
672 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
Duncan Sandsdc024672007-11-27 13:23:08 +0000673 // Construct the new parameter list from non-dead arguments. Also construct
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000674 // a new set of parameter attributes to correspond. Skip the first parameter
675 // attribute, since that belongs to the return value.
676 unsigned i = 0;
677 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
678 I != E; ++I, ++i) {
679 RetOrArg Arg = CreateArg(F, i);
680 if (LiveValues.erase(Arg)) {
Duncan Sandsdc024672007-11-27 13:23:08 +0000681 Params.push_back(I->getType());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000682 ArgAlive[i] = true;
683
684 // Get the original parameter attributes (skipping the first one, that is
685 // for the return value.
686 if (ParameterAttributes Attrs = PAL.getParamAttrs(i + 1))
Duncan Sands110c8352007-12-21 19:16:16 +0000687 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), Attrs));
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000688 } else {
689 ++NumArgumentsEliminated;
690 DOUT << "DAE - Removing argument " << i << " (" << I->getNameStart()
691 << ") from " << F->getNameStart() << "\n";
Duncan Sandsdc024672007-11-27 13:23:08 +0000692 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000693 }
Duncan Sandsdc024672007-11-27 13:23:08 +0000694
695 // Reconstruct the ParamAttrsList based on the vector we constructed.
Chris Lattner58d74912008-03-12 17:45:29 +0000696 PAListPtr NewPAL = PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end());
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000697
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000698 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
699 // have zero fixed arguments.
700 //
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000701 // Note that we apply this hack for a vararg fuction that does not have any
702 // arguments anymore, but did have them before (so don't bother fixing
703 // functions that were already broken wrt CWriter).
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000704 bool ExtraArgHack = false;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000705 if (Params.empty() && FTy->isVarArg() && FTy->getNumParams() != 0) {
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000706 ExtraArgHack = true;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000707 Params.push_back(Type::Int32Ty);
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000708 }
709
Duncan Sandsdc024672007-11-27 13:23:08 +0000710 // Create the new function type based on the recomputed parameters.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000711 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
712
713 // No change?
714 if (NFTy == FTy)
715 return false;
716
Chris Lattner08227e42003-06-17 22:21:05 +0000717 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000718 Function *NF = Function::Create(NFTy, F->getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000719 NF->copyAttributesFrom(F);
Chris Lattner58d74912008-03-12 17:45:29 +0000720 NF->setParamAttrs(NewPAL);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000721 // Insert the new function before the old function, so we won't be processing
722 // it again.
Chris Lattner08227e42003-06-17 22:21:05 +0000723 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000724 NF->takeName(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000725
726 // Loop over all of the callers of the function, transforming the call sites
727 // to pass in a smaller number of arguments into the new function.
728 //
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000729 std::vector<Value*> Args;
Chris Lattner08227e42003-06-17 22:21:05 +0000730 while (!F->use_empty()) {
731 CallSite CS = CallSite::get(F->use_back());
732 Instruction *Call = CS.getInstruction();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000733
Duncan Sands110c8352007-12-21 19:16:16 +0000734 ParamAttrsVec.clear();
Chris Lattner58d74912008-03-12 17:45:29 +0000735 const PAListPtr &CallPAL = CS.getParamAttrs();
Duncan Sands110c8352007-12-21 19:16:16 +0000736
737 // The call return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000738 ParameterAttributes RAttrs = CallPAL.getParamAttrs(0);
Duncan Sands110c8352007-12-21 19:16:16 +0000739 // Adjust in case the function was changed to return void.
Duncan Sands6c3470e2008-01-07 17:16:06 +0000740 RAttrs &= ~ParamAttr::typeIncompatible(NF->getReturnType());
Duncan Sands110c8352007-12-21 19:16:16 +0000741 if (RAttrs)
742 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000743
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000744 // Declare these outside of the loops, so we can reuse them for the second
745 // loop, which loops the varargs.
746 CallSite::arg_iterator I = CS.arg_begin();
747 unsigned i = 0;
748 // Loop over those operands, corresponding to the normal arguments to the
749 // original function, and add those that are still alive.
750 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
751 if (ArgAlive[i]) {
752 Args.push_back(*I);
753 // Get original parameter attributes, but skip return attributes.
754 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
Duncan Sands110c8352007-12-21 19:16:16 +0000755 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
756 }
757
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000758 if (ExtraArgHack)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000759 Args.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000760
Evan Chengb2fc2a32008-01-17 04:18:54 +0000761 // Push any varargs arguments on the list. Don't forget their attributes.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000762 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
763 Args.push_back(*I);
764 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(i + 1))
Evan Chengb2fc2a32008-01-17 04:18:54 +0000765 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
766 }
767
768 // Reconstruct the ParamAttrsList based on the vector we constructed.
Chris Lattner58d74912008-03-12 17:45:29 +0000769 PAListPtr NewCallPAL = PAListPtr::get(ParamAttrsVec.begin(),
770 ParamAttrsVec.end());
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000771
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000772 Instruction *New;
773 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000774 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
775 Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000776 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000777 cast<InvokeInst>(New)->setParamAttrs(NewCallPAL);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000778 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000779 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000780 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000781 cast<CallInst>(New)->setParamAttrs(NewCallPAL);
Chris Lattner1430ef12005-05-06 06:46:58 +0000782 if (cast<CallInst>(Call)->isTailCall())
783 cast<CallInst>(New)->setTailCall();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000784 }
785 Args.clear();
786
787 if (!Call->use_empty()) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000788 if (New->getType() == Call->getType()) {
789 // Return type not changed? Just replace users then.
Evan Cheng890aaa82008-06-25 18:10:09 +0000790 Call->replaceAllUsesWith(New);
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000791 New->takeName(Call);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000792 } else if (New->getType() == Type::VoidTy) {
793 // Our return value has uses, but they will get removed later on.
794 // Replace by null for now.
795 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
796 } else {
Matthijs Kooijman9c9418d2008-07-15 13:39:08 +0000797 assert(STy && "Return type changed, but not into a void. The old "
798 "return type must have been a struct!");
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000799 // The original return value was a struct, update all uses (which are
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000800 // all extractvalue instructions, or uses that are unused themselves).
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000801 for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
802 I != E;) {
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000803 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(*I)) {
804 // Increment now, since we're about to throw away this use.
805 ++I;
806 assert(EV->hasIndices() && "Return value used by extractvalue without"
807 "indices?");
808 unsigned Idx = *EV->idx_begin();
809 if (NewRetIdxs[Idx] != -1) {
810 if (RetTypes.size() > 1) {
811 // We're still returning a struct, create a new extractvalue
812 // instruction with the first index updated
813 std::vector<unsigned> NewIdxs(EV->idx_begin(), EV->idx_end());
814 NewIdxs[0] = NewRetIdxs[Idx];
815 Value *NEV = ExtractValueInst::Create(New, NewIdxs.begin(),
816 NewIdxs.end(), "retval",
817 EV);
818 EV->replaceAllUsesWith(NEV);
819 EV->eraseFromParent();
820 } else {
821 // We are now only returning a simple value, remove the
822 // extractvalue.
823 EV->replaceAllUsesWith(New);
824 EV->eraseFromParent();
825 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000826 } else {
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000827 // Value unused, replace uses by null for now, they will get removed
828 // later on.
829 EV->replaceAllUsesWith(Constant::getNullValue(EV->getType()));
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000830 EV->eraseFromParent();
831 }
832 } else {
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000833 // Not an extractvalue, so this use will become dead soon. Just
834 // replace it with null.
835 I.getUse().set(Constant::getNullValue(I.getUse().get()->getType()));
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000836 }
837 }
838 New->takeName(Call);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000839 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000840 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000841
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000842 // Finally, remove the old call from the program, reducing the use-count of
843 // F.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000844 Call->eraseFromParent();
Chris Lattner08227e42003-06-17 22:21:05 +0000845 }
846
847 // Since we have now created the new function, splice the body of the old
848 // function right into the new function, leaving the old rotting hulk of the
849 // function empty.
850 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
851
852 // Loop over the argument list, transfering uses of the old arguments over to
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000853 // the new arguments, also transfering over the names as well.
854 i = 0;
Chris Lattner19bdc032005-05-06 05:34:40 +0000855 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000856 I2 = NF->arg_begin(); I != E; ++I, ++i)
857 if (ArgAlive[i]) {
Chris Lattner08227e42003-06-17 22:21:05 +0000858 // If this is a live argument, move the name and users over to the new
859 // version.
860 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000861 I2->takeName(I);
Chris Lattner08227e42003-06-17 22:21:05 +0000862 ++I2;
863 } else {
864 // If this argument is dead, replace any uses of it with null constants
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000865 // (these are guaranteed to become unused later on).
Chris Lattner08227e42003-06-17 22:21:05 +0000866 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
Chris Lattner08227e42003-06-17 22:21:05 +0000867 }
868
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000869 // If we change the return value of the function we must rewrite any return
870 // instructions. Check this now.
871 if (F->getReturnType() != NF->getReturnType())
872 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
873 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000874 Value *RetVal;
875
876 if (NFTy->getReturnType() == Type::VoidTy) {
877 RetVal = 0;
878 } else {
879 assert (isa<StructType>(RetTy));
880 // The original return value was a struct, insert
881 // extractvalue/insertvalue chains to extract only the values we need
882 // to return and insert them into our new result.
883 // This does generate messy code, but we'll let it to instcombine to
884 // clean that up.
885 Value *OldRet = RI->getOperand(0);
886 // Start out building up our return value from undef
887 RetVal = llvm::UndefValue::get(NRetTy);
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000888 for (unsigned i = 0; i != PartialRetVals; ++i)
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000889 if (NewRetIdxs[i] != -1) {
890 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
891 "oldret", RI);
892 if (RetTypes.size() > 1) {
893 // We're still returning a struct, so reinsert the value into
894 // our new return value at the new index
895
896 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
897 "newret", RI);
898 } else {
899 // We are now only returning a simple value, so just return the
900 // extracted value.
901 RetVal = EV;
902 }
903 }
904 }
905 // Replace the return instruction with one returning the new return
906 // value (possibly 0 if we became void).
907 ReturnInst::Create(RetVal, RI);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000908 BB->getInstList().erase(RI);
909 }
910
Chris Lattner08227e42003-06-17 22:21:05 +0000911 // Now that the old function is dead, delete it.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000912 F->eraseFromParent();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000913
914 return true;
Chris Lattner08227e42003-06-17 22:21:05 +0000915}
916
Chris Lattnerb12914b2004-09-20 04:48:05 +0000917bool DAE::runOnModule(Module &M) {
Chris Lattner701bc422007-11-15 06:10:55 +0000918 bool Changed = false;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000919
Chris Lattner701bc422007-11-15 06:10:55 +0000920 // First pass: Do a simple check to see if any functions can have their "..."
921 // removed. We can do this if they never call va_start. This loop cannot be
922 // fused with the next loop, because deleting a function invalidates
923 // information computed while surveying other functions.
924 DOUT << "DAE - Deleting dead varargs\n";
925 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
926 Function &F = *I++;
927 if (F.getFunctionType()->isVarArg())
928 Changed |= DeleteDeadVarargs(F);
929 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000930
Chris Lattner701bc422007-11-15 06:10:55 +0000931 // Second phase:loop through the module, determining which arguments are live.
Chris Lattner08227e42003-06-17 22:21:05 +0000932 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000933 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner08227e42003-06-17 22:21:05 +0000934 //
Bill Wendling0a81aac2006-11-26 10:02:32 +0000935 DOUT << "DAE - Determining liveness\n";
Chris Lattner701bc422007-11-15 06:10:55 +0000936 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
937 SurveyFunction(*I);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000938
939 // Now, remove all dead arguments and return values from each function in
940 // turn
941 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
942 // Increment now, because the function will probably get removed (ie
943 // replaced by a new one).
944 Function *F = I++;
945 Changed |= RemoveDeadStuffFromFunction(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000946 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000947 return Changed;
Chris Lattner08227e42003-06-17 22:21:05 +0000948}