blob: 29053a09e0513b2de94e520dc5224f64046c5255 [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"
Alexey Samsonove97a3a42012-10-09 08:13:15 +000024#include "llvm/DebugInfo.h"
Chris Lattner92044ce2006-06-27 21:05:04 +000025#include "llvm/DerivedTypes.h"
Alexey Samsonove97a3a42012-10-09 08:13:15 +000026#include "llvm/DIBuilder.h"
Chris Lattner92044ce2006-06-27 21:05:04 +000027#include "llvm/Instructions.h"
Chris Lattner4af90ab2006-09-18 07:02:31 +000028#include "llvm/IntrinsicInst.h"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000029#include "llvm/LLVMContext.h"
Chris Lattner08227e42003-06-17 22:21:05 +000030#include "llvm/Module.h"
31#include "llvm/Pass.h"
Chris Lattner08227e42003-06-17 22:21:05 +000032#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner58d74912008-03-12 17:45:29 +000035#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/ADT/Statistic.h"
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000037#include "llvm/ADT/StringExtras.h"
Dan Gohmanc9235d22008-03-21 23:51:57 +000038#include <map>
Chris Lattner08227e42003-06-17 22:21:05 +000039#include <set>
Chris Lattner1e2385b2003-11-21 21:54:22 +000040using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000041
Nick Lewycky3715e452010-04-14 04:51:58 +000042STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
43STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
Anders Carlsson0599c6b2011-01-16 21:25:33 +000044STATISTIC(NumArgumentsReplacedWithUndef,
45 "Number of unread args replaced with undef");
Chris Lattner86453c52006-12-19 22:09:18 +000046namespace {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000047 /// DAE - The dead argument elimination pass.
48 ///
Nick Lewycky6726b6d2009-10-25 06:33:48 +000049 class DAE : public ModulePass {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000050 public:
51
52 /// Struct that represents (part of) either a return value or a function
53 /// argument. Used so that arguments and return values can be used
Chris Lattner7a2bdde2011-04-15 05:18:47 +000054 /// interchangeably.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000055 struct RetOrArg {
Nick Lewycky2d7820c2010-04-01 07:34:00 +000056 RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000057 IsArg(IsArg) {}
58 const Function *F;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +000059 unsigned Idx;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000060 bool IsArg;
61
62 /// Make RetOrArg comparable, so we can put it into a map.
63 bool operator<(const RetOrArg &O) const {
64 if (F != O.F)
65 return F < O.F;
66 else if (Idx != O.Idx)
67 return Idx < O.Idx;
68 else
69 return IsArg < O.IsArg;
70 }
71
72 /// Make RetOrArg comparable, so we can easily iterate the multimap.
73 bool operator==(const RetOrArg &O) const {
74 return F == O.F && Idx == O.Idx && IsArg == O.IsArg;
75 }
76
Matthijs Kooijman6cdd54b2008-07-15 08:56:49 +000077 std::string getDescription() const {
Gabor Greif6d6aaec2010-03-24 11:58:07 +000078 return std::string((IsArg ? "Argument #" : "Return value #"))
Benjamin Kramera7b0cb72011-11-15 16:27:03 +000079 + utostr(Idx) + " of function " + F->getName().str();
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 Kooijmand1d1de72008-07-15 14:39:36 +000091 RetOrArg CreateRet(const Function *F, unsigned Idx) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000092 return RetOrArg(F, Idx, false);
93 }
94 /// Convenience wrapper
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +000095 RetOrArg CreateArg(const Function *F, unsigned 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
Alexey Samsonove97a3a42012-10-09 08:13:15 +0000126 // Map each LLVM function to corresponding metadata with debug info. If
127 // the function is replaced with another one, we should patch the pointer
128 // to LLVM function in metadata.
129 // As the code generation for module is finished (and DIBuilder is
130 // finalized) we assume that subprogram descriptors won't be changed, and
131 // they are stored in map for short duration anyway.
132 typedef std::map<Function*, DISubprogram> FunctionDIMap;
133 FunctionDIMap FunctionDIs;
134
Dan Gohmanb9539742010-06-07 20:20:33 +0000135 protected:
136 // DAH uses this to specify a different ID.
Owen Anderson90c579d2010-08-06 18:33:48 +0000137 explicit DAE(char &ID) : ModulePass(ID) {}
Dan Gohmanb9539742010-06-07 20:20:33 +0000138
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000139 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000140 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000141 DAE() : ModulePass(ID) {
142 initializeDAEPass(*PassRegistry::getPassRegistry());
143 }
Dan Gohmanb9539742010-06-07 20:20:33 +0000144
Chris Lattnerb12914b2004-09-20 04:48:05 +0000145 bool runOnModule(Module &M);
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000146
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000147 virtual bool ShouldHackArguments() const { return false; }
148
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000149 private:
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000150 Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000151 Liveness SurveyUse(Value::const_use_iterator U, UseVector &MaybeLiveUses,
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000152 unsigned RetValNum = 0);
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000153 Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000154
Alexey Samsonove97a3a42012-10-09 08:13:15 +0000155 void CollectFunctionDIs(Module &M);
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000156 void SurveyFunction(const Function &F);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000157 void MarkValue(const RetOrArg &RA, Liveness L,
158 const UseVector &MaybeLiveUses);
Matthijs Kooijman6cdd54b2008-07-15 08:56:49 +0000159 void MarkLive(const RetOrArg &RA);
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000160 void MarkLive(const Function &F);
Matthijs Kooijman30156522008-07-15 09:00:17 +0000161 void PropagateLiveness(const RetOrArg &RA);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000162 bool RemoveDeadStuffFromFunction(Function *F);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000163 bool DeleteDeadVarargs(Function &Fn);
Anders Carlsson0599c6b2011-01-16 21:25:33 +0000164 bool RemoveDeadArgumentsFromCallers(Function &Fn);
Chris Lattner08227e42003-06-17 22:21:05 +0000165 };
Dan Gohman844731a2008-05-13 00:00:25 +0000166}
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000167
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000168
Dan Gohman844731a2008-05-13 00:00:25 +0000169char DAE::ID = 0;
Owen Andersonce665bd2010-10-07 22:25:06 +0000170INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000171
172namespace {
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000173 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
174 /// deletes arguments to functions which are external. This is only for use
175 /// by bugpoint.
176 struct DAH : public DAE {
Devang Patel19974732007-05-03 01:11:54 +0000177 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000178 DAH() : DAE(ID) {}
Dan Gohmanb9539742010-06-07 20:20:33 +0000179
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000180 virtual bool ShouldHackArguments() const { return true; }
181 };
Chris Lattner08227e42003-06-17 22:21:05 +0000182}
183
Dan Gohman844731a2008-05-13 00:00:25 +0000184char DAH::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000185INITIALIZE_PASS(DAH, "deadarghaX0r",
186 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
Owen Andersonce665bd2010-10-07 22:25:06 +0000187 false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000188
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000189/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000190/// which are not used by the body of the function.
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000191///
Chris Lattnerb12914b2004-09-20 04:48:05 +0000192ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
193ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner08227e42003-06-17 22:21:05 +0000194
Alexey Samsonove97a3a42012-10-09 08:13:15 +0000195/// CollectFunctionDIs - Map each function in the module to its debug info
196/// descriptor.
197void DAE::CollectFunctionDIs(Module &M) {
198 FunctionDIs.clear();
199
200 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
201 E = M.named_metadata_end(); I != E; ++I) {
202 NamedMDNode &NMD = *I;
203 for (unsigned i = 0, n = NMD.getNumOperands(); i < n; ++i) {
204 MDNode *Node = NMD.getOperand(i);
205 if (DIDescriptor(Node).isCompileUnit()) {
206 DICompileUnit CU(Node);
207 const DIArray &SPs = CU.getSubprograms();
208 for (unsigned i = 0, n = SPs.getNumElements(); i < n; ++i) {
209 DISubprogram SP(SPs.getElement(i));
210 if (SP.Verify()) {
211 if (Function *F = SP.getFunction())
212 FunctionDIs[F] = SP;
213 }
214 }
215 }
216 }
217 }
218}
219
Chris Lattner4af90ab2006-09-18 07:02:31 +0000220/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
221/// llvm.vastart is never called, the varargs list is dead for the function.
222bool DAE::DeleteDeadVarargs(Function &Fn) {
223 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
Rafael Espindolabb46f522009-01-15 20:18:42 +0000224 if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
Duncan Sands110c8352007-12-21 19:16:16 +0000225
Chris Lattner4af90ab2006-09-18 07:02:31 +0000226 // Ensure that the function is only directly called.
Jay Foad757068f2009-06-10 08:41:11 +0000227 if (Fn.hasAddressTaken())
228 return false;
Duncan Sands110c8352007-12-21 19:16:16 +0000229
Chris Lattner4af90ab2006-09-18 07:02:31 +0000230 // Okay, we know we can transform this function if safe. Scan its body
231 // looking for calls to llvm.vastart.
232 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
233 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
234 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
235 if (II->getIntrinsicID() == Intrinsic::vastart)
236 return false;
237 }
238 }
239 }
Duncan Sands110c8352007-12-21 19:16:16 +0000240
Chris Lattner4af90ab2006-09-18 07:02:31 +0000241 // If we get here, there are no calls to llvm.vastart in the function body,
242 // remove the "..." and adjust all the calls.
Duncan Sands110c8352007-12-21 19:16:16 +0000243
Chris Lattner4af90ab2006-09-18 07:02:31 +0000244 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000245 // the old function, but doesn't have isVarArg set.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000246 FunctionType *FTy = Fn.getFunctionType();
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000247
Jay Foad5fdd6c82011-07-12 14:06:48 +0000248 std::vector<Type*> Params(FTy->param_begin(), FTy->param_end());
Owen Andersondebcb012009-07-29 22:17:13 +0000249 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000250 Params, false);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000251 unsigned NumArgs = Params.size();
Duncan Sands110c8352007-12-21 19:16:16 +0000252
Chris Lattner4af90ab2006-09-18 07:02:31 +0000253 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000254 Function *NF = Function::Create(NFTy, Fn.getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000255 NF->copyAttributesFrom(&Fn);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000256 Fn.getParent()->getFunctionList().insert(&Fn, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000257 NF->takeName(&Fn);
Duncan Sands110c8352007-12-21 19:16:16 +0000258
Chris Lattner4af90ab2006-09-18 07:02:31 +0000259 // Loop over all of the callers of the function, transforming the call sites
260 // to pass in a smaller number of arguments into the new function.
261 //
262 std::vector<Value*> Args;
263 while (!Fn.use_empty()) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000264 CallSite CS(Fn.use_back());
Chris Lattner4af90ab2006-09-18 07:02:31 +0000265 Instruction *Call = CS.getInstruction();
Duncan Sands110c8352007-12-21 19:16:16 +0000266
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000267 // Pass all the same arguments.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000268 Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
Duncan Sands110c8352007-12-21 19:16:16 +0000269
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000270 // Drop any attributes that were on the vararg arguments.
Devang Patel05988662008-09-25 21:00:45 +0000271 AttrListPtr PAL = CS.getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +0000272 if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
Devang Patel05988662008-09-25 21:00:45 +0000273 SmallVector<AttributeWithIndex, 8> AttributesVec;
Chris Lattner58d74912008-03-12 17:45:29 +0000274 for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
Devang Patel05988662008-09-25 21:00:45 +0000275 AttributesVec.push_back(PAL.getSlot(i));
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000276 if (Attributes FnAttrs = PAL.getFnAttributes())
Devang Patel19c87462008-09-26 22:53:05 +0000277 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
Chris Lattnerd509d0b2012-05-28 01:47:44 +0000278 PAL = AttrListPtr::get(AttributesVec);
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000279 }
280
Chris Lattner4af90ab2006-09-18 07:02:31 +0000281 Instruction *New;
282 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000283 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
Jay Foada3efbb12011-07-15 08:37:34 +0000284 Args, "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000285 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000286 cast<InvokeInst>(New)->setAttributes(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000287 } else {
Jay Foada3efbb12011-07-15 08:37:34 +0000288 New = CallInst::Create(NF, Args, "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000289 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000290 cast<CallInst>(New)->setAttributes(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000291 if (cast<CallInst>(Call)->isTailCall())
292 cast<CallInst>(New)->setTailCall();
293 }
Dan Gohmanbda02522010-07-20 20:09:07 +0000294 New->setDebugLoc(Call->getDebugLoc());
Devang Patel0aa885d2010-04-30 20:23:54 +0000295
Chris Lattner4af90ab2006-09-18 07:02:31 +0000296 Args.clear();
Duncan Sands110c8352007-12-21 19:16:16 +0000297
Chris Lattner4af90ab2006-09-18 07:02:31 +0000298 if (!Call->use_empty())
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000299 Call->replaceAllUsesWith(New);
Duncan Sands110c8352007-12-21 19:16:16 +0000300
Chris Lattner046800a2007-02-11 01:08:35 +0000301 New->takeName(Call);
Duncan Sands110c8352007-12-21 19:16:16 +0000302
Chris Lattner4af90ab2006-09-18 07:02:31 +0000303 // Finally, remove the old call from the program, reducing the use-count of
304 // F.
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000305 Call->eraseFromParent();
Chris Lattner4af90ab2006-09-18 07:02:31 +0000306 }
Duncan Sands110c8352007-12-21 19:16:16 +0000307
Chris Lattner4af90ab2006-09-18 07:02:31 +0000308 // Since we have now created the new function, splice the body of the old
309 // function right into the new function, leaving the old rotting hulk of the
310 // function empty.
311 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
Duncan Sands110c8352007-12-21 19:16:16 +0000312
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000313 // Loop over the argument list, transferring uses of the old arguments over to
314 // the new arguments, also transferring over the names as well. While we're at
Chris Lattner4af90ab2006-09-18 07:02:31 +0000315 // it, remove the dead arguments from the DeadArguments list.
316 //
317 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
318 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
319 // Move the name and users over to the new version.
320 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000321 I2->takeName(I);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000322 }
Duncan Sands110c8352007-12-21 19:16:16 +0000323
Alexey Samsonove97a3a42012-10-09 08:13:15 +0000324 // Patch the pointer to LLVM function in debug info descriptor.
325 FunctionDIMap::iterator DI = FunctionDIs.find(&Fn);
326 if (DI != FunctionDIs.end())
327 DI->second.replaceFunction(NF);
328
Chris Lattner4af90ab2006-09-18 07:02:31 +0000329 // Finally, nuke the old function.
330 Fn.eraseFromParent();
331 return true;
332}
333
Anders Carlsson0599c6b2011-01-16 21:25:33 +0000334/// RemoveDeadArgumentsFromCallers - Checks if the given function has any
335/// arguments that are unused, and changes the caller parameters to be undefined
336/// instead.
337bool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
338{
Eli Friedmanf291ab22011-03-01 00:33:47 +0000339 if (Fn.isDeclaration() || Fn.mayBeOverridden())
Anders Carlsson0599c6b2011-01-16 21:25:33 +0000340 return false;
341
342 // Functions with local linkage should already have been handled.
343 if (Fn.hasLocalLinkage())
344 return false;
345
346 if (Fn.use_empty())
347 return false;
348
349 llvm::SmallVector<unsigned, 8> UnusedArgs;
350 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
351 I != E; ++I) {
352 Argument *Arg = I;
353
354 if (Arg->use_empty() && !Arg->hasByValAttr())
355 UnusedArgs.push_back(Arg->getArgNo());
356 }
357
358 if (UnusedArgs.empty())
359 return false;
360
361 bool Changed = false;
362
363 for (Function::use_iterator I = Fn.use_begin(), E = Fn.use_end();
364 I != E; ++I) {
365 CallSite CS(*I);
366 if (!CS || !CS.isCallee(I))
367 continue;
368
369 // Now go through all unused args and replace them with "undef".
370 for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
371 unsigned ArgNo = UnusedArgs[I];
372
373 Value *Arg = CS.getArgument(ArgNo);
374 CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
375 ++NumArgumentsReplacedWithUndef;
376 Changed = true;
377 }
378 }
379
380 return Changed;
381}
382
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000383/// Convenience function that returns the number of return values. It returns 0
384/// for void functions and 1 for functions not returning a struct. It returns
385/// the number of struct elements for functions returning a struct.
386static unsigned NumRetVals(const Function *F) {
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000387 if (F->getReturnType()->isVoidTy())
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000388 return 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000389 else if (StructType *STy = dyn_cast<StructType>(F->getReturnType()))
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000390 return STy->getNumElements();
391 else
392 return 1;
393}
394
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000395/// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
396/// live, it adds Use to the MaybeLiveUses argument. Returns the determined
397/// liveness of Use.
398DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000399 // We're live if our use or its Function is already marked as live.
400 if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
Chris Lattner92044ce2006-06-27 21:05:04 +0000401 return Live;
Chris Lattner08227e42003-06-17 22:21:05 +0000402
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000403 // We're maybe live otherwise, but remember that we must become live if
404 // Use becomes live.
405 MaybeLiveUses.push_back(Use);
406 return MaybeLive;
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000407}
408
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000409
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000410/// SurveyUse - This looks at a single use of an argument or return value
411/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000412/// if it causes the used value to become MaybeLive.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000413///
414/// RetValNum is the return value number to use when this use is used in a
415/// return instruction. This is used in the recursion, you should always leave
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000416/// it at 0.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000417DAE::Liveness DAE::SurveyUse(Value::const_use_iterator U,
418 UseVector &MaybeLiveUses, unsigned RetValNum) {
419 const User *V = *U;
420 if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000421 // The value is returned from a function. It's only live when the
422 // function's return value is live. We use RetValNum here, for the case
423 // that U is really a use of an insertvalue instruction that uses the
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000424 // original Use.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000425 RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
426 // We might be live, depending on the liveness of Use.
427 return MarkIfNotLive(Use, MaybeLiveUses);
428 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000429 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000430 if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
431 && IV->hasIndices())
432 // The use we are examining is inserted into an aggregate. Our liveness
433 // depends on all uses of that aggregate, but if it is used as a return
434 // value, only index at which we were inserted counts.
435 RetValNum = *IV->idx_begin();
436
437 // Note that if we are used as the aggregate operand to the insertvalue,
438 // we don't change RetValNum, but do survey all our uses.
439
440 Liveness Result = MaybeLive;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000441 for (Value::const_use_iterator I = IV->use_begin(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000442 E = V->use_end(); I != E; ++I) {
443 Result = SurveyUse(I, MaybeLiveUses, RetValNum);
444 if (Result == Live)
445 break;
446 }
447 return Result;
448 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000449
450 if (ImmutableCallSite CS = V) {
451 const Function *F = CS.getCalledFunction();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000452 if (F) {
453 // Used in a direct call.
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000454
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000455 // Find the argument number. We know for sure that this use is an
456 // argument, since if it was the function argument this would be an
457 // indirect call and the we know can't be looking at a value of the
458 // label type (for the invoke instruction).
Gabor Greifc9f75002010-03-24 13:21:49 +0000459 unsigned ArgNo = CS.getArgumentNo(U);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000460
461 if (ArgNo >= F->getFunctionType()->getNumParams())
462 // The value is passed in through a vararg! Must be live.
463 return Live;
464
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000465 assert(CS.getArgument(ArgNo)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000466 == CS->getOperand(U.getOperandNo())
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000467 && "Argument is not where we expected it");
468
469 // Value passed to a normal call. It's only live when the corresponding
470 // argument to the called function turns out live.
471 RetOrArg Use = CreateArg(F, ArgNo);
472 return MarkIfNotLive(Use, MaybeLiveUses);
473 }
474 }
475 // Used in any other way? Value must be live.
476 return Live;
477}
478
479/// SurveyUses - This looks at all the uses of the given value
480/// Returns the Liveness deduced from the uses of this value.
481///
482/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
483/// the result is Live, MaybeLiveUses might be modified but its content should
484/// be ignored (since it might not be complete).
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000485DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000486 // Assume it's dead (which will only hold if there are no uses at all..).
487 Liveness Result = MaybeLive;
488 // Check each use.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000489 for (Value::const_use_iterator I = V->use_begin(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000490 E = V->use_end(); I != E; ++I) {
491 Result = SurveyUse(I, MaybeLiveUses);
492 if (Result == Live)
493 break;
494 }
495 return Result;
496}
497
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000498// SurveyFunction - This performs the initial survey of the specified function,
499// checking out whether or not it uses any of its incoming arguments or whether
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000500// any callers use the return value. This fills in the LiveValues set and Uses
501// map.
Chris Lattner08227e42003-06-17 22:21:05 +0000502//
Nick Lewycky44540742010-01-23 20:32:12 +0000503// We consider arguments of non-internal functions to be intrinsically alive as
Nick Lewycky3715e452010-04-14 04:51:58 +0000504// well as arguments to functions which have their "address taken".
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000505//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000506void DAE::SurveyFunction(const Function &F) {
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000507 unsigned RetCount = NumRetVals(&F);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000508 // Assume all return values are dead
509 typedef SmallVector<Liveness, 5> RetVals;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000510 RetVals RetValLiveness(RetCount, MaybeLive);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000511
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000512 typedef SmallVector<UseVector, 5> RetUses;
513 // These vectors map each return value to the uses that make it MaybeLive, so
514 // we can add those to the Uses map if the return value really turns out to be
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000515 // MaybeLive. Initialized to a list of RetCount empty lists.
516 RetUses MaybeLiveRetUses(RetCount);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000517
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000518 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
519 if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000520 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
521 != F.getFunctionType()->getReturnType()) {
522 // We don't support old style multiple return values.
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000523 MarkLive(F);
524 return;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000525 }
526
Nick Lewycky3715e452010-04-14 04:51:58 +0000527 if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000528 MarkLive(F);
529 return;
530 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000531
David Greene3307e952010-01-05 01:28:29 +0000532 DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000533 // Keep track of the number of live retvals, so we can skip checks once all
534 // of them turn out to be live.
535 unsigned NumLiveRetVals = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000536 Type *STy = dyn_cast<StructType>(F.getReturnType());
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000537 // Loop all uses of the function.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000538 for (Value::const_use_iterator I = F.use_begin(), E = F.use_end();
539 I != E; ++I) {
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000540 // If the function is PASSED IN as an argument, its address has been
541 // taken.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000542 ImmutableCallSite CS(*I);
543 if (!CS || !CS.isCallee(I)) {
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000544 MarkLive(F);
545 return;
546 }
Matthijs Kooijman41335412008-06-05 08:34:25 +0000547
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000548 // If this use is anything other than a call site, the function is alive.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000549 const Instruction *TheCall = CS.getInstruction();
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000550 if (!TheCall) { // Not a direct call site?
551 MarkLive(F);
552 return;
553 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000554
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000555 // If we end up here, we are looking at a direct call to our function.
Evan Cheng890aaa82008-06-25 18:10:09 +0000556
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000557 // Now, check how our return value(s) is/are used in this caller. Don't
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000558 // bother checking return values if all of them are live already.
559 if (NumLiveRetVals != RetCount) {
560 if (STy) {
561 // Check all uses of the return value.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000562 for (Value::const_use_iterator I = TheCall->use_begin(),
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000563 E = TheCall->use_end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000564 const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000565 if (Ext && Ext->hasIndices()) {
566 // This use uses a part of our return value, survey the uses of
567 // that part and store the results for this index only.
568 unsigned Idx = *Ext->idx_begin();
569 if (RetValLiveness[Idx] != Live) {
570 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
571 if (RetValLiveness[Idx] == Live)
572 NumLiveRetVals++;
573 }
574 } else {
575 // Used by something else than extractvalue. Mark all return
576 // values as live.
577 for (unsigned i = 0; i != RetCount; ++i )
578 RetValLiveness[i] = Live;
579 NumLiveRetVals = RetCount;
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000580 break;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000581 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000582 }
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000583 } else {
584 // Single return value
585 RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
586 if (RetValLiveness[0] == Live)
587 NumLiveRetVals = RetCount;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000588 }
589 }
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000590 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000591
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000592 // Now we've inspected all callers, record the liveness of our return values.
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000593 for (unsigned i = 0; i != RetCount; ++i)
594 MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000595
David Greene3307e952010-01-05 01:28:29 +0000596 DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000597
598 // Now, check all of our arguments.
599 unsigned i = 0;
600 UseVector MaybeLiveArgUses;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000601 for (Function::const_arg_iterator AI = F.arg_begin(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000602 E = F.arg_end(); AI != E; ++AI, ++i) {
603 // See what the effect of this use is (recording any uses that cause
604 // MaybeLive in MaybeLiveArgUses).
605 Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
606 // Mark the result.
607 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
608 // Clear the vector again for the next iteration.
609 MaybeLiveArgUses.clear();
Matthijs Kooijmanca85d652008-06-18 11:12:53 +0000610 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000611}
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000612
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000613/// MarkValue - This function marks the liveness of RA depending on L. If L is
614/// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
615/// such that RA will be marked live if any use in MaybeLiveUses gets marked
616/// live later on.
617void DAE::MarkValue(const RetOrArg &RA, Liveness L,
618 const UseVector &MaybeLiveUses) {
619 switch (L) {
620 case Live: MarkLive(RA); break;
Evan Cheng890aaa82008-06-25 18:10:09 +0000621 case MaybeLive:
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000622 {
623 // Note any uses of this value, so this return value can be
624 // marked live whenever one of the uses becomes live.
625 for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
626 UE = MaybeLiveUses.end(); UI != UE; ++UI)
627 Uses.insert(std::make_pair(*UI, RA));
Evan Cheng890aaa82008-06-25 18:10:09 +0000628 break;
629 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000630 }
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000631}
Owen Andersonbb3761c2008-06-18 17:32:16 +0000632
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000633/// MarkLive - Mark the given Function as alive, meaning that it cannot be
634/// changed in any way. Additionally,
635/// mark any values that are used as this function's parameters or by its return
636/// values (according to Uses) live as well.
637void DAE::MarkLive(const Function &F) {
David Greene3307e952010-01-05 01:28:29 +0000638 DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
Nick Lewycky1462a9b2010-05-15 03:41:58 +0000639 // Mark the function as live.
640 LiveFunctions.insert(&F);
641 // Mark all arguments as live.
642 for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
643 PropagateLiveness(CreateArg(&F, i));
644 // Mark all return values as live.
645 for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
646 PropagateLiveness(CreateRet(&F, i));
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000647}
648
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000649/// MarkLive - Mark the given return value or argument as live. Additionally,
650/// mark any values that are used by this value (according to Uses) live as
651/// well.
Matthijs Kooijman6cdd54b2008-07-15 08:56:49 +0000652void DAE::MarkLive(const RetOrArg &RA) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000653 if (LiveFunctions.count(RA.F))
654 return; // Function was already marked Live.
655
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000656 if (!LiveValues.insert(RA).second)
657 return; // We were already marked Live.
658
David Greene3307e952010-01-05 01:28:29 +0000659 DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
Matthijs Kooijman30156522008-07-15 09:00:17 +0000660 PropagateLiveness(RA);
661}
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000662
Matthijs Kooijman30156522008-07-15 09:00:17 +0000663/// PropagateLiveness - Given that RA is a live value, propagate it's liveness
664/// to any other values it uses (according to Uses).
665void DAE::PropagateLiveness(const RetOrArg &RA) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000666 // We don't use upper_bound (or equal_range) here, because our recursive call
667 // to ourselves is likely to cause the upper_bound (which is the first value
668 // not belonging to RA) to become erased and the iterator invalidated.
669 UseMap::iterator Begin = Uses.lower_bound(RA);
670 UseMap::iterator E = Uses.end();
671 UseMap::iterator I;
672 for (I = Begin; I != E && I->first == RA; ++I)
673 MarkLive(I->second);
674
675 // Erase RA from the Uses map (from the lower bound to wherever we ended up
676 // after the loop).
677 Uses.erase(Begin, I);
678}
679
680// RemoveDeadStuffFromFunction - Remove any arguments and return values from F
681// that are not in LiveValues. Transform the function and all of the callees of
682// the function to not have these arguments and return values.
Evan Cheng890aaa82008-06-25 18:10:09 +0000683//
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000684bool DAE::RemoveDeadStuffFromFunction(Function *F) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000685 // Don't modify fully live functions
686 if (LiveFunctions.count(F))
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000687 return false;
Evan Cheng890aaa82008-06-25 18:10:09 +0000688
Chris Lattner08227e42003-06-17 22:21:05 +0000689 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000690 // the old function, but has fewer arguments and a different return type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000691 FunctionType *FTy = F->getFunctionType();
Jay Foad5fdd6c82011-07-12 14:06:48 +0000692 std::vector<Type*> Params;
Chris Lattner08227e42003-06-17 22:21:05 +0000693
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000694 // Set up to build a new list of parameter attributes.
Devang Patel05988662008-09-25 21:00:45 +0000695 SmallVector<AttributeWithIndex, 8> AttributesVec;
696 const AttrListPtr &PAL = F->getAttributes();
Chris Lattner08227e42003-06-17 22:21:05 +0000697
Duncan Sands110c8352007-12-21 19:16:16 +0000698 // The existing function return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000699 Attributes RAttrs = PAL.getRetAttributes();
700 Attributes FnAttrs = PAL.getFnAttributes();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000701
702 // Find out the new return value.
703
Jay Foad5fdd6c82011-07-12 14:06:48 +0000704 Type *RetTy = FTy->getReturnType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000705 Type *NRetTy = NULL;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000706 unsigned RetCount = NumRetVals(F);
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000707
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000708 // -1 means unused, other numbers are the new index
709 SmallVector<int, 5> NewRetIdxs(RetCount, -1);
Jay Foad5fdd6c82011-07-12 14:06:48 +0000710 std::vector<Type*> RetTypes;
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000711 if (RetTy->isVoidTy()) {
712 NRetTy = RetTy;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000713 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000714 StructType *STy = dyn_cast<StructType>(RetTy);
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000715 if (STy)
716 // Look at each of the original return values individually.
717 for (unsigned i = 0; i != RetCount; ++i) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000718 RetOrArg Ret = CreateRet(F, i);
719 if (LiveValues.erase(Ret)) {
720 RetTypes.push_back(STy->getElementType(i));
721 NewRetIdxs[i] = RetTypes.size() - 1;
722 } else {
723 ++NumRetValsEliminated;
David Greene3307e952010-01-05 01:28:29 +0000724 DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
Daniel Dunbar460f6562009-07-26 09:48:23 +0000725 << F->getName() << "\n");
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000726 }
727 }
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000728 else
729 // We used to return a single value.
730 if (LiveValues.erase(CreateRet(F, 0))) {
731 RetTypes.push_back(RetTy);
732 NewRetIdxs[0] = 0;
733 } else {
David Greene3307e952010-01-05 01:28:29 +0000734 DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
Daniel Dunbar460f6562009-07-26 09:48:23 +0000735 << "\n");
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000736 ++NumRetValsEliminated;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000737 }
Matthijs Kooijman4f723682008-07-15 14:42:31 +0000738 if (RetTypes.size() > 1)
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000739 // More than one return type? Return a struct with them. Also, if we used
740 // to return a struct and didn't change the number of return values,
741 // return a struct again. This prevents changing {something} into
742 // something and {} into void.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000743 // Make the new struct packed if we used to return a packed struct
744 // already.
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000745 NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000746 else if (RetTypes.size() == 1)
747 // One return type? Just a simple value then, but only if we didn't use to
748 // return a struct with that simple value before.
749 NRetTy = RetTypes.front();
750 else if (RetTypes.size() == 0)
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000751 // No return types? Make it void, but only if we didn't use to return {}.
Owen Anderson1d0be152009-08-13 21:58:54 +0000752 NRetTy = Type::getVoidTy(F->getContext());
Duncan Sands110c8352007-12-21 19:16:16 +0000753 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000754
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000755 assert(NRetTy && "No new return type found?");
756
757 // Remove any incompatible attributes, but only if we removed all return
758 // values. Otherwise, ensure that we don't have any conflicting attributes
759 // here. Currently, this should not be possible, but special handling might be
760 // required when new return value attributes are added.
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000761 if (NRetTy->isVoidTy())
Bill Wendling853a8c52012-09-25 20:38:59 +0000762 RAttrs &= ~Attributes::typeIncompatible(NRetTy);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000763 else
Bill Wendling853a8c52012-09-25 20:38:59 +0000764 assert((RAttrs & Attributes::typeIncompatible(NRetTy)) == 0
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000765 && "Return attributes no longer compatible?");
766
Duncan Sands110c8352007-12-21 19:16:16 +0000767 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +0000768 AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000769
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000770 // Remember which arguments are still alive.
771 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
Duncan Sandsdc024672007-11-27 13:23:08 +0000772 // Construct the new parameter list from non-dead arguments. Also construct
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000773 // a new set of parameter attributes to correspond. Skip the first parameter
774 // attribute, since that belongs to the return value.
775 unsigned i = 0;
776 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
777 I != E; ++I, ++i) {
778 RetOrArg Arg = CreateArg(F, i);
779 if (LiveValues.erase(Arg)) {
Duncan Sandsdc024672007-11-27 13:23:08 +0000780 Params.push_back(I->getType());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000781 ArgAlive[i] = true;
782
783 // Get the original parameter attributes (skipping the first one, that is
784 // for the return value.
Devang Patel19c87462008-09-26 22:53:05 +0000785 if (Attributes Attrs = PAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +0000786 AttributesVec.push_back(AttributeWithIndex::get(Params.size(), Attrs));
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000787 } else {
788 ++NumArgumentsEliminated;
David Greene3307e952010-01-05 01:28:29 +0000789 DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
Daniel Dunbar460f6562009-07-26 09:48:23 +0000790 << ") from " << F->getName() << "\n");
Duncan Sandsdc024672007-11-27 13:23:08 +0000791 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000792 }
Duncan Sandsdc024672007-11-27 13:23:08 +0000793
Bill Wendling9158eec2012-10-04 06:48:57 +0000794 if (FnAttrs.hasAttributes())
Devang Patel19c87462008-09-26 22:53:05 +0000795 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
796
Devang Patel05988662008-09-25 21:00:45 +0000797 // Reconstruct the AttributesList based on the vector we constructed.
Chris Lattnerd509d0b2012-05-28 01:47:44 +0000798 AttrListPtr NewPAL = AttrListPtr::get(AttributesVec);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000799
Duncan Sandsdc024672007-11-27 13:23:08 +0000800 // Create the new function type based on the recomputed parameters.
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000801 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000802
803 // No change?
804 if (NFTy == FTy)
805 return false;
806
Chris Lattner08227e42003-06-17 22:21:05 +0000807 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000808 Function *NF = Function::Create(NFTy, F->getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000809 NF->copyAttributesFrom(F);
Devang Patel05988662008-09-25 21:00:45 +0000810 NF->setAttributes(NewPAL);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000811 // Insert the new function before the old function, so we won't be processing
812 // it again.
Chris Lattner08227e42003-06-17 22:21:05 +0000813 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000814 NF->takeName(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000815
816 // Loop over all of the callers of the function, transforming the call sites
817 // to pass in a smaller number of arguments into the new function.
818 //
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000819 std::vector<Value*> Args;
Chris Lattner08227e42003-06-17 22:21:05 +0000820 while (!F->use_empty()) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000821 CallSite CS(F->use_back());
Chris Lattner08227e42003-06-17 22:21:05 +0000822 Instruction *Call = CS.getInstruction();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000823
Devang Patel05988662008-09-25 21:00:45 +0000824 AttributesVec.clear();
825 const AttrListPtr &CallPAL = CS.getAttributes();
Duncan Sands110c8352007-12-21 19:16:16 +0000826
827 // The call return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000828 Attributes RAttrs = CallPAL.getRetAttributes();
829 Attributes FnAttrs = CallPAL.getFnAttributes();
Duncan Sands110c8352007-12-21 19:16:16 +0000830 // Adjust in case the function was changed to return void.
Bill Wendling853a8c52012-09-25 20:38:59 +0000831 RAttrs &= ~Attributes::typeIncompatible(NF->getReturnType());
Duncan Sands110c8352007-12-21 19:16:16 +0000832 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +0000833 AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000834
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000835 // Declare these outside of the loops, so we can reuse them for the second
836 // loop, which loops the varargs.
837 CallSite::arg_iterator I = CS.arg_begin();
838 unsigned i = 0;
839 // Loop over those operands, corresponding to the normal arguments to the
840 // original function, and add those that are still alive.
841 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
842 if (ArgAlive[i]) {
843 Args.push_back(*I);
844 // Get original parameter attributes, but skip return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000845 if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +0000846 AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
Duncan Sands110c8352007-12-21 19:16:16 +0000847 }
848
Evan Chengb2fc2a32008-01-17 04:18:54 +0000849 // Push any varargs arguments on the list. Don't forget their attributes.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000850 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
851 Args.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +0000852 if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +0000853 AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
Evan Chengb2fc2a32008-01-17 04:18:54 +0000854 }
855
Bill Wendling9158eec2012-10-04 06:48:57 +0000856 if (FnAttrs.hasAttributes())
Devang Patel19c87462008-09-26 22:53:05 +0000857 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
858
Devang Patel05988662008-09-25 21:00:45 +0000859 // Reconstruct the AttributesList based on the vector we constructed.
Chris Lattnerd509d0b2012-05-28 01:47:44 +0000860 AttrListPtr NewCallPAL = AttrListPtr::get(AttributesVec);
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000861
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000862 Instruction *New;
863 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000864 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
Jay Foada3efbb12011-07-15 08:37:34 +0000865 Args, "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000866 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000867 cast<InvokeInst>(New)->setAttributes(NewCallPAL);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000868 } else {
Jay Foada3efbb12011-07-15 08:37:34 +0000869 New = CallInst::Create(NF, Args, "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000870 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000871 cast<CallInst>(New)->setAttributes(NewCallPAL);
Chris Lattner1430ef12005-05-06 06:46:58 +0000872 if (cast<CallInst>(Call)->isTailCall())
873 cast<CallInst>(New)->setTailCall();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000874 }
Dan Gohmanbda02522010-07-20 20:09:07 +0000875 New->setDebugLoc(Call->getDebugLoc());
Devang Patel0aa885d2010-04-30 20:23:54 +0000876
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000877 Args.clear();
878
879 if (!Call->use_empty()) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000880 if (New->getType() == Call->getType()) {
881 // Return type not changed? Just replace users then.
Evan Cheng890aaa82008-06-25 18:10:09 +0000882 Call->replaceAllUsesWith(New);
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000883 New->takeName(Call);
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000884 } else if (New->getType()->isVoidTy()) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000885 // Our return value has uses, but they will get removed later on.
886 // Replace by null for now.
Dale Johannesen0488fb62010-09-30 23:57:10 +0000887 if (!Call->getType()->isX86_MMXTy())
888 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000889 } else {
Duncan Sands1df98592010-02-16 11:11:14 +0000890 assert(RetTy->isStructTy() &&
Chris Lattnerbda07652009-03-18 00:31:45 +0000891 "Return type changed, but not into a void. The old return type"
892 " must have been a struct!");
893 Instruction *InsertPt = Call;
Chris Lattnerf023b542009-03-18 16:23:56 +0000894 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Chris Lattnera5affdc2009-03-18 16:48:45 +0000895 BasicBlock::iterator IP = II->getNormalDest()->begin();
896 while (isa<PHINode>(IP)) ++IP;
897 InsertPt = IP;
Chris Lattnerf023b542009-03-18 16:23:56 +0000898 }
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000899
Matthijs Kooijmaneb32b452008-07-15 14:03:10 +0000900 // We used to return a struct. Instead of doing smart stuff with all the
901 // uses of this struct, we will just rebuild it using
902 // extract/insertvalue chaining and let instcombine clean that up.
903 //
904 // Start out building up our return value from undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000905 Value *RetVal = UndefValue::get(RetTy);
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000906 for (unsigned i = 0; i != RetCount; ++i)
Matthijs Kooijmaneb32b452008-07-15 14:03:10 +0000907 if (NewRetIdxs[i] != -1) {
908 Value *V;
909 if (RetTypes.size() > 1)
910 // We are still returning a struct, so extract the value from our
911 // return value
Chris Lattnerbda07652009-03-18 00:31:45 +0000912 V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
913 InsertPt);
Matthijs Kooijmaneb32b452008-07-15 14:03:10 +0000914 else
915 // We are now returning a single element, so just insert that
916 V = New;
917 // Insert the value at the old position
Chris Lattnerbda07652009-03-18 00:31:45 +0000918 RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000919 }
Matthijs Kooijmaneb32b452008-07-15 14:03:10 +0000920 // Now, replace all uses of the old call instruction with the return
921 // struct we built
922 Call->replaceAllUsesWith(RetVal);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000923 New->takeName(Call);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000924 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000925 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000926
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000927 // Finally, remove the old call from the program, reducing the use-count of
928 // F.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000929 Call->eraseFromParent();
Chris Lattner08227e42003-06-17 22:21:05 +0000930 }
931
932 // Since we have now created the new function, splice the body of the old
933 // function right into the new function, leaving the old rotting hulk of the
934 // function empty.
935 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
936
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000937 // Loop over the argument list, transferring uses of the old arguments over to
938 // the new arguments, also transferring over the names as well.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000939 i = 0;
Chris Lattner19bdc032005-05-06 05:34:40 +0000940 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000941 I2 = NF->arg_begin(); I != E; ++I, ++i)
942 if (ArgAlive[i]) {
Chris Lattner08227e42003-06-17 22:21:05 +0000943 // If this is a live argument, move the name and users over to the new
944 // version.
945 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000946 I2->takeName(I);
Chris Lattner08227e42003-06-17 22:21:05 +0000947 ++I2;
948 } else {
949 // If this argument is dead, replace any uses of it with null constants
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000950 // (these are guaranteed to become unused later on).
Dale Johannesen0488fb62010-09-30 23:57:10 +0000951 if (!I->getType()->isX86_MMXTy())
952 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
Chris Lattner08227e42003-06-17 22:21:05 +0000953 }
954
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000955 // If we change the return value of the function we must rewrite any return
956 // instructions. Check this now.
957 if (F->getReturnType() != NF->getReturnType())
958 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
959 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000960 Value *RetVal;
961
Nick Lewycky1462a9b2010-05-15 03:41:58 +0000962 if (NFTy->getReturnType()->isVoidTy()) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000963 RetVal = 0;
964 } else {
Duncan Sands1df98592010-02-16 11:11:14 +0000965 assert (RetTy->isStructTy());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000966 // The original return value was a struct, insert
967 // extractvalue/insertvalue chains to extract only the values we need
968 // to return and insert them into our new result.
969 // This does generate messy code, but we'll let it to instcombine to
970 // clean that up.
971 Value *OldRet = RI->getOperand(0);
972 // Start out building up our return value from undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000973 RetVal = UndefValue::get(NRetTy);
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000974 for (unsigned i = 0; i != RetCount; ++i)
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000975 if (NewRetIdxs[i] != -1) {
976 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
977 "oldret", RI);
978 if (RetTypes.size() > 1) {
979 // We're still returning a struct, so reinsert the value into
980 // our new return value at the new index
981
982 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
983 "newret", RI);
984 } else {
985 // We are now only returning a simple value, so just return the
986 // extracted value.
987 RetVal = EV;
988 }
989 }
990 }
991 // Replace the return instruction with one returning the new return
992 // value (possibly 0 if we became void).
Owen Anderson1d0be152009-08-13 21:58:54 +0000993 ReturnInst::Create(F->getContext(), RetVal, RI);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000994 BB->getInstList().erase(RI);
995 }
996
Alexey Samsonove97a3a42012-10-09 08:13:15 +0000997 // Patch the pointer to LLVM function in debug info descriptor.
998 FunctionDIMap::iterator DI = FunctionDIs.find(F);
999 if (DI != FunctionDIs.end())
1000 DI->second.replaceFunction(NF);
1001
Chris Lattner08227e42003-06-17 22:21:05 +00001002 // Now that the old function is dead, delete it.
Matthijs Kooijman494661c2008-05-30 12:35:46 +00001003 F->eraseFromParent();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +00001004
1005 return true;
Chris Lattner08227e42003-06-17 22:21:05 +00001006}
1007
Chris Lattnerb12914b2004-09-20 04:48:05 +00001008bool DAE::runOnModule(Module &M) {
Chris Lattner701bc422007-11-15 06:10:55 +00001009 bool Changed = false;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +00001010
Alexey Samsonove97a3a42012-10-09 08:13:15 +00001011 // Collect debug info descriptors for functions.
1012 CollectFunctionDIs(M);
1013
Chris Lattner701bc422007-11-15 06:10:55 +00001014 // First pass: Do a simple check to see if any functions can have their "..."
1015 // removed. We can do this if they never call va_start. This loop cannot be
1016 // fused with the next loop, because deleting a function invalidates
1017 // information computed while surveying other functions.
David Greene3307e952010-01-05 01:28:29 +00001018 DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
Chris Lattner701bc422007-11-15 06:10:55 +00001019 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1020 Function &F = *I++;
1021 if (F.getFunctionType()->isVarArg())
1022 Changed |= DeleteDeadVarargs(F);
1023 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +00001024
Chris Lattner701bc422007-11-15 06:10:55 +00001025 // Second phase:loop through the module, determining which arguments are live.
Chris Lattner08227e42003-06-17 22:21:05 +00001026 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +00001027 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner08227e42003-06-17 22:21:05 +00001028 //
David Greene3307e952010-01-05 01:28:29 +00001029 DEBUG(dbgs() << "DAE - Determining liveness\n");
Chris Lattner701bc422007-11-15 06:10:55 +00001030 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1031 SurveyFunction(*I);
Gabor Greif6d6aaec2010-03-24 11:58:07 +00001032
Matthijs Kooijmand16918f2008-07-10 10:24:08 +00001033 // Now, remove all dead arguments and return values from each function in
Nick Lewycky2d7820c2010-04-01 07:34:00 +00001034 // turn.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +00001035 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
Nick Lewycky2d7820c2010-04-01 07:34:00 +00001036 // Increment now, because the function will probably get removed (ie.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +00001037 // replaced by a new one).
1038 Function *F = I++;
Nick Lewycky3715e452010-04-14 04:51:58 +00001039 Changed |= RemoveDeadStuffFromFunction(F);
Chris Lattner08227e42003-06-17 22:21:05 +00001040 }
Anders Carlsson0599c6b2011-01-16 21:25:33 +00001041
1042 // Finally, look for any unused parameters in functions with non-local
1043 // linkage and replace the passed in parameters with undef.
1044 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1045 Function& F = *I;
1046
1047 Changed |= RemoveDeadArgumentsFromCallers(F);
1048 }
1049
Matthijs Kooijmand16918f2008-07-10 10:24:08 +00001050 return Changed;
Chris Lattner08227e42003-06-17 22:21:05 +00001051}