blob: b42322116a98fc860a68265904cca009bb217212 [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"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000027#include "llvm/LLVMContext.h"
Chris Lattner08227e42003-06-17 22:21:05 +000028#include "llvm/Module.h"
29#include "llvm/Pass.h"
Chris Lattner08227e42003-06-17 22:21:05 +000030#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000032#include "llvm/Support/raw_ostream.h"
Chris Lattner58d74912008-03-12 17:45:29 +000033#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/ADT/Statistic.h"
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000035#include "llvm/ADT/StringExtras.h"
Dan Gohmanc9235d22008-03-21 23:51:57 +000036#include <map>
Chris Lattner08227e42003-06-17 22:21:05 +000037#include <set>
Chris Lattner1e2385b2003-11-21 21:54:22 +000038using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000039
Nick Lewycky3715e452010-04-14 04:51:58 +000040STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
41STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
Anders Carlsson0599c6b2011-01-16 21:25:33 +000042STATISTIC(NumArgumentsReplacedWithUndef,
43 "Number of unread args replaced with undef");
Chris Lattner86453c52006-12-19 22:09:18 +000044namespace {
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000045 /// DAE - The dead argument elimination pass.
46 ///
Nick Lewycky6726b6d2009-10-25 06:33:48 +000047 class DAE : public ModulePass {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000048 public:
49
50 /// Struct that represents (part of) either a return value or a function
51 /// argument. Used so that arguments and return values can be used
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +000052 /// interchangably.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000053 struct RetOrArg {
Nick Lewycky2d7820c2010-04-01 07:34:00 +000054 RetOrArg(const Function *F, unsigned Idx, bool IsArg) : F(F), Idx(Idx),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000055 IsArg(IsArg) {}
56 const Function *F;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +000057 unsigned 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 {
Gabor Greif6d6aaec2010-03-24 11:58:07 +000076 return std::string((IsArg ? "Argument #" : "Return value #"))
Daniel Dunbarf6ccee52009-07-24 08:24:36 +000077 + utostr(Idx) + " of function " + F->getNameStr();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000078 }
79 };
80
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000081 /// Liveness enum - During our initial pass over the program, we determine
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000082 /// that things are either alive or maybe alive. We don't mark anything
83 /// explicitly dead (even if we know they are), since anything not alive
84 /// with no registered uses (in Uses) will never be marked alive and will
85 /// thus become dead in the end.
86 enum Liveness { Live, MaybeLive };
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000087
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000088 /// Convenience wrapper
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +000089 RetOrArg CreateRet(const Function *F, unsigned Idx) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000090 return RetOrArg(F, Idx, false);
91 }
92 /// Convenience wrapper
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +000093 RetOrArg CreateArg(const Function *F, unsigned Idx) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000094 return RetOrArg(F, Idx, true);
95 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +000096
Matthijs Kooijmand16918f2008-07-10 10:24:08 +000097 typedef std::multimap<RetOrArg, RetOrArg> UseMap;
98 /// This maps a return value or argument to any MaybeLive return values or
99 /// arguments it uses. This allows the MaybeLive values to be marked live
100 /// when any of its users is marked live.
101 /// For example (indices are left out for clarity):
102 /// - Uses[ret F] = ret G
103 /// This means that F calls G, and F returns the value returned by G.
104 /// - Uses[arg F] = ret G
105 /// This means that some function calls G and passes its result as an
106 /// argument to F.
107 /// - Uses[ret F] = arg F
108 /// This means that F returns one of its own arguments.
109 /// - Uses[arg F] = arg G
110 /// This means that G calls F and passes one of its own (G's) arguments
111 /// directly to F.
112 UseMap Uses;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000113
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000114 typedef std::set<RetOrArg> LiveSet;
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000115 typedef std::set<const Function*> LiveFuncSet;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000116
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000117 /// This set contains all values that have been determined to be live.
118 LiveSet LiveValues;
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000119 /// This set contains all values that are cannot be changed in any way.
120 LiveFuncSet LiveFunctions;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000121
122 typedef SmallVector<RetOrArg, 5> UseVector;
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000123
Dan Gohmanb9539742010-06-07 20:20:33 +0000124 protected:
125 // DAH uses this to specify a different ID.
Owen Anderson90c579d2010-08-06 18:33:48 +0000126 explicit DAE(char &ID) : ModulePass(ID) {}
Dan Gohmanb9539742010-06-07 20:20:33 +0000127
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000128 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000129 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000130 DAE() : ModulePass(ID) {
131 initializeDAEPass(*PassRegistry::getPassRegistry());
132 }
Dan Gohmanb9539742010-06-07 20:20:33 +0000133
Chris Lattnerb12914b2004-09-20 04:48:05 +0000134 bool runOnModule(Module &M);
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000135
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000136 virtual bool ShouldHackArguments() const { return false; }
137
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000138 private:
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000139 Liveness MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses);
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000140 Liveness SurveyUse(Value::const_use_iterator U, UseVector &MaybeLiveUses,
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000141 unsigned RetValNum = 0);
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000142 Liveness SurveyUses(const Value *V, UseVector &MaybeLiveUses);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000143
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000144 void SurveyFunction(const Function &F);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000145 void MarkValue(const RetOrArg &RA, Liveness L,
146 const UseVector &MaybeLiveUses);
Matthijs Kooijman6cdd54b2008-07-15 08:56:49 +0000147 void MarkLive(const RetOrArg &RA);
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000148 void MarkLive(const Function &F);
Matthijs Kooijman30156522008-07-15 09:00:17 +0000149 void PropagateLiveness(const RetOrArg &RA);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000150 bool RemoveDeadStuffFromFunction(Function *F);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000151 bool DeleteDeadVarargs(Function &Fn);
Anders Carlsson0599c6b2011-01-16 21:25:33 +0000152 bool RemoveDeadArgumentsFromCallers(Function &Fn);
Chris Lattner08227e42003-06-17 22:21:05 +0000153 };
Dan Gohman844731a2008-05-13 00:00:25 +0000154}
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000155
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000156
Dan Gohman844731a2008-05-13 00:00:25 +0000157char DAE::ID = 0;
Owen Andersonce665bd2010-10-07 22:25:06 +0000158INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000159
160namespace {
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000161 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
162 /// deletes arguments to functions which are external. This is only for use
163 /// by bugpoint.
164 struct DAH : public DAE {
Devang Patel19974732007-05-03 01:11:54 +0000165 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +0000166 DAH() : DAE(ID) {}
Dan Gohmanb9539742010-06-07 20:20:33 +0000167
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000168 virtual bool ShouldHackArguments() const { return true; }
169 };
Chris Lattner08227e42003-06-17 22:21:05 +0000170}
171
Dan Gohman844731a2008-05-13 00:00:25 +0000172char DAH::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000173INITIALIZE_PASS(DAH, "deadarghaX0r",
174 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
Owen Andersonce665bd2010-10-07 22:25:06 +0000175 false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000176
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000177/// createDeadArgEliminationPass - This pass removes arguments from functions
Chris Lattnerfdcc3ac2003-11-05 21:43:02 +0000178/// which are not used by the body of the function.
Chris Lattner9b2a14b2003-06-25 04:12:49 +0000179///
Chris Lattnerb12914b2004-09-20 04:48:05 +0000180ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
181ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
Chris Lattner08227e42003-06-17 22:21:05 +0000182
Chris Lattner4af90ab2006-09-18 07:02:31 +0000183/// DeleteDeadVarargs - If this is an function that takes a ... list, and if
184/// llvm.vastart is never called, the varargs list is dead for the function.
185bool DAE::DeleteDeadVarargs(Function &Fn) {
186 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
Rafael Espindolabb46f522009-01-15 20:18:42 +0000187 if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
Duncan Sands110c8352007-12-21 19:16:16 +0000188
Chris Lattner4af90ab2006-09-18 07:02:31 +0000189 // Ensure that the function is only directly called.
Jay Foad757068f2009-06-10 08:41:11 +0000190 if (Fn.hasAddressTaken())
191 return false;
Duncan Sands110c8352007-12-21 19:16:16 +0000192
Chris Lattner4af90ab2006-09-18 07:02:31 +0000193 // Okay, we know we can transform this function if safe. Scan its body
194 // looking for calls to llvm.vastart.
195 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
196 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
197 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
198 if (II->getIntrinsicID() == Intrinsic::vastart)
199 return false;
200 }
201 }
202 }
Duncan Sands110c8352007-12-21 19:16:16 +0000203
Chris Lattner4af90ab2006-09-18 07:02:31 +0000204 // If we get here, there are no calls to llvm.vastart in the function body,
205 // remove the "..." and adjust all the calls.
Duncan Sands110c8352007-12-21 19:16:16 +0000206
Chris Lattner4af90ab2006-09-18 07:02:31 +0000207 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000208 // the old function, but doesn't have isVarArg set.
Chris Lattner4af90ab2006-09-18 07:02:31 +0000209 const FunctionType *FTy = Fn.getFunctionType();
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000210
Chris Lattner4af90ab2006-09-18 07:02:31 +0000211 std::vector<const Type*> Params(FTy->param_begin(), FTy->param_end());
Owen Andersondebcb012009-07-29 22:17:13 +0000212 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000213 Params, false);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000214 unsigned NumArgs = Params.size();
Duncan Sands110c8352007-12-21 19:16:16 +0000215
Chris Lattner4af90ab2006-09-18 07:02:31 +0000216 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000217 Function *NF = Function::Create(NFTy, Fn.getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000218 NF->copyAttributesFrom(&Fn);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000219 Fn.getParent()->getFunctionList().insert(&Fn, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000220 NF->takeName(&Fn);
Duncan Sands110c8352007-12-21 19:16:16 +0000221
Chris Lattner4af90ab2006-09-18 07:02:31 +0000222 // Loop over all of the callers of the function, transforming the call sites
223 // to pass in a smaller number of arguments into the new function.
224 //
225 std::vector<Value*> Args;
226 while (!Fn.use_empty()) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000227 CallSite CS(Fn.use_back());
Chris Lattner4af90ab2006-09-18 07:02:31 +0000228 Instruction *Call = CS.getInstruction();
Duncan Sands110c8352007-12-21 19:16:16 +0000229
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000230 // Pass all the same arguments.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000231 Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
Duncan Sands110c8352007-12-21 19:16:16 +0000232
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000233 // Drop any attributes that were on the vararg arguments.
Devang Patel05988662008-09-25 21:00:45 +0000234 AttrListPtr PAL = CS.getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +0000235 if (!PAL.isEmpty() && PAL.getSlot(PAL.getNumSlots() - 1).Index > NumArgs) {
Devang Patel05988662008-09-25 21:00:45 +0000236 SmallVector<AttributeWithIndex, 8> AttributesVec;
Chris Lattner58d74912008-03-12 17:45:29 +0000237 for (unsigned i = 0; PAL.getSlot(i).Index <= NumArgs; ++i)
Devang Patel05988662008-09-25 21:00:45 +0000238 AttributesVec.push_back(PAL.getSlot(i));
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000239 if (Attributes FnAttrs = PAL.getFnAttributes())
Devang Patel19c87462008-09-26 22:53:05 +0000240 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
Devang Patel05988662008-09-25 21:00:45 +0000241 PAL = AttrListPtr::get(AttributesVec.begin(), AttributesVec.end());
Duncan Sandsbfc5ae62008-01-11 23:13:45 +0000242 }
243
Chris Lattner4af90ab2006-09-18 07:02:31 +0000244 Instruction *New;
245 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000246 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
247 Args.begin(), Args.end(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000248 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000249 cast<InvokeInst>(New)->setAttributes(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000250 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000251 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000252 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000253 cast<CallInst>(New)->setAttributes(PAL);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000254 if (cast<CallInst>(Call)->isTailCall())
255 cast<CallInst>(New)->setTailCall();
256 }
Dan Gohmanbda02522010-07-20 20:09:07 +0000257 New->setDebugLoc(Call->getDebugLoc());
Devang Patel0aa885d2010-04-30 20:23:54 +0000258
Chris Lattner4af90ab2006-09-18 07:02:31 +0000259 Args.clear();
Duncan Sands110c8352007-12-21 19:16:16 +0000260
Chris Lattner4af90ab2006-09-18 07:02:31 +0000261 if (!Call->use_empty())
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000262 Call->replaceAllUsesWith(New);
Duncan Sands110c8352007-12-21 19:16:16 +0000263
Chris Lattner046800a2007-02-11 01:08:35 +0000264 New->takeName(Call);
Duncan Sands110c8352007-12-21 19:16:16 +0000265
Chris Lattner4af90ab2006-09-18 07:02:31 +0000266 // Finally, remove the old call from the program, reducing the use-count of
267 // F.
Chris Lattnera0bc7fc2007-10-18 18:49:29 +0000268 Call->eraseFromParent();
Chris Lattner4af90ab2006-09-18 07:02:31 +0000269 }
Duncan Sands110c8352007-12-21 19:16:16 +0000270
Chris Lattner4af90ab2006-09-18 07:02:31 +0000271 // Since we have now created the new function, splice the body of the old
272 // function right into the new function, leaving the old rotting hulk of the
273 // function empty.
274 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
Duncan Sands110c8352007-12-21 19:16:16 +0000275
Chris Lattner4af90ab2006-09-18 07:02:31 +0000276 // Loop over the argument list, transfering uses of the old arguments over to
277 // the new arguments, also transfering over the names as well. While we're at
278 // it, remove the dead arguments from the DeadArguments list.
279 //
280 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
281 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
282 // Move the name and users over to the new version.
283 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000284 I2->takeName(I);
Chris Lattner4af90ab2006-09-18 07:02:31 +0000285 }
Duncan Sands110c8352007-12-21 19:16:16 +0000286
Chris Lattner4af90ab2006-09-18 07:02:31 +0000287 // Finally, nuke the old function.
288 Fn.eraseFromParent();
289 return true;
290}
291
Anders Carlsson0599c6b2011-01-16 21:25:33 +0000292/// RemoveDeadArgumentsFromCallers - Checks if the given function has any
293/// arguments that are unused, and changes the caller parameters to be undefined
294/// instead.
295bool DAE::RemoveDeadArgumentsFromCallers(Function &Fn)
296{
297 if (Fn.isDeclaration())
298 return false;
299
300 // Functions with local linkage should already have been handled.
301 if (Fn.hasLocalLinkage())
302 return false;
303
304 if (Fn.use_empty())
305 return false;
306
307 llvm::SmallVector<unsigned, 8> UnusedArgs;
308 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
309 I != E; ++I) {
310 Argument *Arg = I;
311
312 if (Arg->use_empty() && !Arg->hasByValAttr())
313 UnusedArgs.push_back(Arg->getArgNo());
314 }
315
316 if (UnusedArgs.empty())
317 return false;
318
319 bool Changed = false;
320
321 for (Function::use_iterator I = Fn.use_begin(), E = Fn.use_end();
322 I != E; ++I) {
323 CallSite CS(*I);
324 if (!CS || !CS.isCallee(I))
325 continue;
326
327 // Now go through all unused args and replace them with "undef".
328 for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
329 unsigned ArgNo = UnusedArgs[I];
330
331 Value *Arg = CS.getArgument(ArgNo);
332 CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
333 ++NumArgumentsReplacedWithUndef;
334 Changed = true;
335 }
336 }
337
338 return Changed;
339}
340
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000341/// Convenience function that returns the number of return values. It returns 0
342/// for void functions and 1 for functions not returning a struct. It returns
343/// the number of struct elements for functions returning a struct.
344static unsigned NumRetVals(const Function *F) {
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000345 if (F->getReturnType()->isVoidTy())
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000346 return 0;
347 else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType()))
348 return STy->getNumElements();
349 else
350 return 1;
351}
352
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000353/// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
354/// live, it adds Use to the MaybeLiveUses argument. Returns the determined
355/// liveness of Use.
356DAE::Liveness DAE::MarkIfNotLive(RetOrArg Use, UseVector &MaybeLiveUses) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000357 // We're live if our use or its Function is already marked as live.
358 if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
Chris Lattner92044ce2006-06-27 21:05:04 +0000359 return Live;
Chris Lattner08227e42003-06-17 22:21:05 +0000360
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000361 // We're maybe live otherwise, but remember that we must become live if
362 // Use becomes live.
363 MaybeLiveUses.push_back(Use);
364 return MaybeLive;
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000365}
366
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000367
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000368/// SurveyUse - This looks at a single use of an argument or return value
369/// and determines if it should be alive or not. Adds this use to MaybeLiveUses
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000370/// if it causes the used value to become MaybeLive.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000371///
372/// RetValNum is the return value number to use when this use is used in a
373/// return instruction. This is used in the recursion, you should always leave
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000374/// it at 0.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000375DAE::Liveness DAE::SurveyUse(Value::const_use_iterator U,
376 UseVector &MaybeLiveUses, unsigned RetValNum) {
377 const User *V = *U;
378 if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000379 // The value is returned from a function. It's only live when the
380 // function's return value is live. We use RetValNum here, for the case
381 // that U is really a use of an insertvalue instruction that uses the
382 // orginal Use.
383 RetOrArg Use = CreateRet(RI->getParent()->getParent(), RetValNum);
384 // We might be live, depending on the liveness of Use.
385 return MarkIfNotLive(Use, MaybeLiveUses);
386 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000387 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000388 if (U.getOperandNo() != InsertValueInst::getAggregateOperandIndex()
389 && IV->hasIndices())
390 // The use we are examining is inserted into an aggregate. Our liveness
391 // depends on all uses of that aggregate, but if it is used as a return
392 // value, only index at which we were inserted counts.
393 RetValNum = *IV->idx_begin();
394
395 // Note that if we are used as the aggregate operand to the insertvalue,
396 // we don't change RetValNum, but do survey all our uses.
397
398 Liveness Result = MaybeLive;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000399 for (Value::const_use_iterator I = IV->use_begin(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000400 E = V->use_end(); I != E; ++I) {
401 Result = SurveyUse(I, MaybeLiveUses, RetValNum);
402 if (Result == Live)
403 break;
404 }
405 return Result;
406 }
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000407
408 if (ImmutableCallSite CS = V) {
409 const Function *F = CS.getCalledFunction();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000410 if (F) {
411 // Used in a direct call.
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000412
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000413 // Find the argument number. We know for sure that this use is an
414 // argument, since if it was the function argument this would be an
415 // indirect call and the we know can't be looking at a value of the
416 // label type (for the invoke instruction).
Gabor Greifc9f75002010-03-24 13:21:49 +0000417 unsigned ArgNo = CS.getArgumentNo(U);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000418
419 if (ArgNo >= F->getFunctionType()->getNumParams())
420 // The value is passed in through a vararg! Must be live.
421 return Live;
422
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000423 assert(CS.getArgument(ArgNo)
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000424 == CS->getOperand(U.getOperandNo())
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000425 && "Argument is not where we expected it");
426
427 // Value passed to a normal call. It's only live when the corresponding
428 // argument to the called function turns out live.
429 RetOrArg Use = CreateArg(F, ArgNo);
430 return MarkIfNotLive(Use, MaybeLiveUses);
431 }
432 }
433 // Used in any other way? Value must be live.
434 return Live;
435}
436
437/// SurveyUses - This looks at all the uses of the given value
438/// Returns the Liveness deduced from the uses of this value.
439///
440/// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
441/// the result is Live, MaybeLiveUses might be modified but its content should
442/// be ignored (since it might not be complete).
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000443DAE::Liveness DAE::SurveyUses(const Value *V, UseVector &MaybeLiveUses) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000444 // Assume it's dead (which will only hold if there are no uses at all..).
445 Liveness Result = MaybeLive;
446 // Check each use.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000447 for (Value::const_use_iterator I = V->use_begin(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000448 E = V->use_end(); I != E; ++I) {
449 Result = SurveyUse(I, MaybeLiveUses);
450 if (Result == Live)
451 break;
452 }
453 return Result;
454}
455
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000456// SurveyFunction - This performs the initial survey of the specified function,
457// checking out whether or not it uses any of its incoming arguments or whether
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000458// any callers use the return value. This fills in the LiveValues set and Uses
459// map.
Chris Lattner08227e42003-06-17 22:21:05 +0000460//
Nick Lewycky44540742010-01-23 20:32:12 +0000461// We consider arguments of non-internal functions to be intrinsically alive as
Nick Lewycky3715e452010-04-14 04:51:58 +0000462// well as arguments to functions which have their "address taken".
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000463//
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000464void DAE::SurveyFunction(const Function &F) {
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000465 unsigned RetCount = NumRetVals(&F);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000466 // Assume all return values are dead
467 typedef SmallVector<Liveness, 5> RetVals;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000468 RetVals RetValLiveness(RetCount, MaybeLive);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000469
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000470 typedef SmallVector<UseVector, 5> RetUses;
471 // These vectors map each return value to the uses that make it MaybeLive, so
472 // we can add those to the Uses map if the return value really turns out to be
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000473 // MaybeLive. Initialized to a list of RetCount empty lists.
474 RetUses MaybeLiveRetUses(RetCount);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000475
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000476 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
477 if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000478 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
479 != F.getFunctionType()->getReturnType()) {
480 // We don't support old style multiple return values.
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000481 MarkLive(F);
482 return;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000483 }
484
Nick Lewycky3715e452010-04-14 04:51:58 +0000485 if (!F.hasLocalLinkage() && (!ShouldHackArguments() || F.isIntrinsic())) {
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000486 MarkLive(F);
487 return;
488 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000489
David Greene3307e952010-01-05 01:28:29 +0000490 DEBUG(dbgs() << "DAE - Inspecting callers for fn: " << F.getName() << "\n");
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000491 // Keep track of the number of live retvals, so we can skip checks once all
492 // of them turn out to be live.
493 unsigned NumLiveRetVals = 0;
494 const Type *STy = dyn_cast<StructType>(F.getReturnType());
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000495 // Loop all uses of the function.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000496 for (Value::const_use_iterator I = F.use_begin(), E = F.use_end();
497 I != E; ++I) {
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000498 // If the function is PASSED IN as an argument, its address has been
499 // taken.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000500 ImmutableCallSite CS(*I);
501 if (!CS || !CS.isCallee(I)) {
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000502 MarkLive(F);
503 return;
504 }
Matthijs Kooijman41335412008-06-05 08:34:25 +0000505
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000506 // If this use is anything other than a call site, the function is alive.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000507 const Instruction *TheCall = CS.getInstruction();
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000508 if (!TheCall) { // Not a direct call site?
509 MarkLive(F);
510 return;
511 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000512
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000513 // If we end up here, we are looking at a direct call to our function.
Evan Cheng890aaa82008-06-25 18:10:09 +0000514
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000515 // Now, check how our return value(s) is/are used in this caller. Don't
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000516 // bother checking return values if all of them are live already.
517 if (NumLiveRetVals != RetCount) {
518 if (STy) {
519 // Check all uses of the return value.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000520 for (Value::const_use_iterator I = TheCall->use_begin(),
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000521 E = TheCall->use_end(); I != E; ++I) {
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000522 const ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(*I);
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000523 if (Ext && Ext->hasIndices()) {
524 // This use uses a part of our return value, survey the uses of
525 // that part and store the results for this index only.
526 unsigned Idx = *Ext->idx_begin();
527 if (RetValLiveness[Idx] != Live) {
528 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
529 if (RetValLiveness[Idx] == Live)
530 NumLiveRetVals++;
531 }
532 } else {
533 // Used by something else than extractvalue. Mark all return
534 // values as live.
535 for (unsigned i = 0; i != RetCount; ++i )
536 RetValLiveness[i] = Live;
537 NumLiveRetVals = RetCount;
Matthijs Kooijmanddd1a792008-07-15 13:36:06 +0000538 break;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000539 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000540 }
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000541 } else {
542 // Single return value
543 RetValLiveness[0] = SurveyUses(TheCall, MaybeLiveRetUses[0]);
544 if (RetValLiveness[0] == Live)
545 NumLiveRetVals = RetCount;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000546 }
547 }
Matthijs Kooijman0d1730a2008-07-15 08:47:32 +0000548 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000549
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000550 // Now we've inspected all callers, record the liveness of our return values.
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000551 for (unsigned i = 0; i != RetCount; ++i)
552 MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000553
David Greene3307e952010-01-05 01:28:29 +0000554 DEBUG(dbgs() << "DAE - Inspecting args for fn: " << F.getName() << "\n");
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000555
556 // Now, check all of our arguments.
557 unsigned i = 0;
558 UseVector MaybeLiveArgUses;
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000559 for (Function::const_arg_iterator AI = F.arg_begin(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000560 E = F.arg_end(); AI != E; ++AI, ++i) {
561 // See what the effect of this use is (recording any uses that cause
562 // MaybeLive in MaybeLiveArgUses).
563 Liveness Result = SurveyUses(AI, MaybeLiveArgUses);
564 // Mark the result.
565 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
566 // Clear the vector again for the next iteration.
567 MaybeLiveArgUses.clear();
Matthijs Kooijmanca85d652008-06-18 11:12:53 +0000568 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000569}
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000570
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000571/// MarkValue - This function marks the liveness of RA depending on L. If L is
572/// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
573/// such that RA will be marked live if any use in MaybeLiveUses gets marked
574/// live later on.
575void DAE::MarkValue(const RetOrArg &RA, Liveness L,
576 const UseVector &MaybeLiveUses) {
577 switch (L) {
578 case Live: MarkLive(RA); break;
Evan Cheng890aaa82008-06-25 18:10:09 +0000579 case MaybeLive:
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000580 {
581 // Note any uses of this value, so this return value can be
582 // marked live whenever one of the uses becomes live.
583 for (UseVector::const_iterator UI = MaybeLiveUses.begin(),
584 UE = MaybeLiveUses.end(); UI != UE; ++UI)
585 Uses.insert(std::make_pair(*UI, RA));
Evan Cheng890aaa82008-06-25 18:10:09 +0000586 break;
587 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000588 }
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000589}
Owen Andersonbb3761c2008-06-18 17:32:16 +0000590
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000591/// MarkLive - Mark the given Function as alive, meaning that it cannot be
592/// changed in any way. Additionally,
593/// mark any values that are used as this function's parameters or by its return
594/// values (according to Uses) live as well.
595void DAE::MarkLive(const Function &F) {
David Greene3307e952010-01-05 01:28:29 +0000596 DEBUG(dbgs() << "DAE - Intrinsically live fn: " << F.getName() << "\n");
Nick Lewycky1462a9b2010-05-15 03:41:58 +0000597 // Mark the function as live.
598 LiveFunctions.insert(&F);
599 // Mark all arguments as live.
600 for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
601 PropagateLiveness(CreateArg(&F, i));
602 // Mark all return values as live.
603 for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
604 PropagateLiveness(CreateRet(&F, i));
Matthijs Kooijmana3ec5d62008-07-15 08:45:12 +0000605}
606
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000607/// MarkLive - Mark the given return value or argument as live. Additionally,
608/// mark any values that are used by this value (according to Uses) live as
609/// well.
Matthijs Kooijman6cdd54b2008-07-15 08:56:49 +0000610void DAE::MarkLive(const RetOrArg &RA) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000611 if (LiveFunctions.count(RA.F))
612 return; // Function was already marked Live.
613
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000614 if (!LiveValues.insert(RA).second)
615 return; // We were already marked Live.
616
David Greene3307e952010-01-05 01:28:29 +0000617 DEBUG(dbgs() << "DAE - Marking " << RA.getDescription() << " live\n");
Matthijs Kooijman30156522008-07-15 09:00:17 +0000618 PropagateLiveness(RA);
619}
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000620
Matthijs Kooijman30156522008-07-15 09:00:17 +0000621/// PropagateLiveness - Given that RA is a live value, propagate it's liveness
622/// to any other values it uses (according to Uses).
623void DAE::PropagateLiveness(const RetOrArg &RA) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000624 // We don't use upper_bound (or equal_range) here, because our recursive call
625 // to ourselves is likely to cause the upper_bound (which is the first value
626 // not belonging to RA) to become erased and the iterator invalidated.
627 UseMap::iterator Begin = Uses.lower_bound(RA);
628 UseMap::iterator E = Uses.end();
629 UseMap::iterator I;
630 for (I = Begin; I != E && I->first == RA; ++I)
631 MarkLive(I->second);
632
633 // Erase RA from the Uses map (from the lower bound to wherever we ended up
634 // after the loop).
635 Uses.erase(Begin, I);
636}
637
638// RemoveDeadStuffFromFunction - Remove any arguments and return values from F
639// that are not in LiveValues. Transform the function and all of the callees of
640// the function to not have these arguments and return values.
Evan Cheng890aaa82008-06-25 18:10:09 +0000641//
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000642bool DAE::RemoveDeadStuffFromFunction(Function *F) {
Matthijs Kooijman2bf53722008-07-15 09:11:16 +0000643 // Don't modify fully live functions
644 if (LiveFunctions.count(F))
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000645 return false;
Evan Cheng890aaa82008-06-25 18:10:09 +0000646
Chris Lattner08227e42003-06-17 22:21:05 +0000647 // Start by computing a new prototype for the function, which is the same as
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000648 // the old function, but has fewer arguments and a different return type.
Chris Lattner08227e42003-06-17 22:21:05 +0000649 const FunctionType *FTy = F->getFunctionType();
650 std::vector<const Type*> Params;
651
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000652 // Set up to build a new list of parameter attributes.
Devang Patel05988662008-09-25 21:00:45 +0000653 SmallVector<AttributeWithIndex, 8> AttributesVec;
654 const AttrListPtr &PAL = F->getAttributes();
Chris Lattner08227e42003-06-17 22:21:05 +0000655
Duncan Sands110c8352007-12-21 19:16:16 +0000656 // The existing function return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000657 Attributes RAttrs = PAL.getRetAttributes();
658 Attributes FnAttrs = PAL.getFnAttributes();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000659
660 // Find out the new return value.
661
Duncan Sands110c8352007-12-21 19:16:16 +0000662 const Type *RetTy = FTy->getReturnType();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000663 const Type *NRetTy = NULL;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000664 unsigned RetCount = NumRetVals(F);
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000665
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000666 // -1 means unused, other numbers are the new index
667 SmallVector<int, 5> NewRetIdxs(RetCount, -1);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000668 std::vector<const Type*> RetTypes;
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000669 if (RetTy->isVoidTy()) {
670 NRetTy = RetTy;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000671 } else {
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000672 const StructType *STy = dyn_cast<StructType>(RetTy);
673 if (STy)
674 // Look at each of the original return values individually.
675 for (unsigned i = 0; i != RetCount; ++i) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000676 RetOrArg Ret = CreateRet(F, i);
677 if (LiveValues.erase(Ret)) {
678 RetTypes.push_back(STy->getElementType(i));
679 NewRetIdxs[i] = RetTypes.size() - 1;
680 } else {
681 ++NumRetValsEliminated;
David Greene3307e952010-01-05 01:28:29 +0000682 DEBUG(dbgs() << "DAE - Removing return value " << i << " from "
Daniel Dunbar460f6562009-07-26 09:48:23 +0000683 << F->getName() << "\n");
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000684 }
685 }
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000686 else
687 // We used to return a single value.
688 if (LiveValues.erase(CreateRet(F, 0))) {
689 RetTypes.push_back(RetTy);
690 NewRetIdxs[0] = 0;
691 } else {
David Greene3307e952010-01-05 01:28:29 +0000692 DEBUG(dbgs() << "DAE - Removing return value from " << F->getName()
Daniel Dunbar460f6562009-07-26 09:48:23 +0000693 << "\n");
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000694 ++NumRetValsEliminated;
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000695 }
Matthijs Kooijman4f723682008-07-15 14:42:31 +0000696 if (RetTypes.size() > 1)
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000697 // More than one return type? Return a struct with them. Also, if we used
698 // to return a struct and didn't change the number of return values,
699 // return a struct again. This prevents changing {something} into
700 // something and {} into void.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000701 // Make the new struct packed if we used to return a packed struct
702 // already.
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000703 NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000704 else if (RetTypes.size() == 1)
705 // One return type? Just a simple value then, but only if we didn't use to
706 // return a struct with that simple value before.
707 NRetTy = RetTypes.front();
708 else if (RetTypes.size() == 0)
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000709 // No return types? Make it void, but only if we didn't use to return {}.
Owen Anderson1d0be152009-08-13 21:58:54 +0000710 NRetTy = Type::getVoidTy(F->getContext());
Duncan Sands110c8352007-12-21 19:16:16 +0000711 }
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000712
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000713 assert(NRetTy && "No new return type found?");
714
715 // Remove any incompatible attributes, but only if we removed all return
716 // values. Otherwise, ensure that we don't have any conflicting attributes
717 // here. Currently, this should not be possible, but special handling might be
718 // required when new return value attributes are added.
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000719 if (NRetTy->isVoidTy())
Devang Patel05988662008-09-25 21:00:45 +0000720 RAttrs &= ~Attribute::typeIncompatible(NRetTy);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000721 else
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000722 assert((RAttrs & Attribute::typeIncompatible(NRetTy)) == 0
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000723 && "Return attributes no longer compatible?");
724
Duncan Sands110c8352007-12-21 19:16:16 +0000725 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +0000726 AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000727
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000728 // Remember which arguments are still alive.
729 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
Duncan Sandsdc024672007-11-27 13:23:08 +0000730 // Construct the new parameter list from non-dead arguments. Also construct
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000731 // a new set of parameter attributes to correspond. Skip the first parameter
732 // attribute, since that belongs to the return value.
733 unsigned i = 0;
734 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
735 I != E; ++I, ++i) {
736 RetOrArg Arg = CreateArg(F, i);
737 if (LiveValues.erase(Arg)) {
Duncan Sandsdc024672007-11-27 13:23:08 +0000738 Params.push_back(I->getType());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000739 ArgAlive[i] = true;
740
741 // Get the original parameter attributes (skipping the first one, that is
742 // for the return value.
Devang Patel19c87462008-09-26 22:53:05 +0000743 if (Attributes Attrs = PAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +0000744 AttributesVec.push_back(AttributeWithIndex::get(Params.size(), Attrs));
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000745 } else {
746 ++NumArgumentsEliminated;
David Greene3307e952010-01-05 01:28:29 +0000747 DEBUG(dbgs() << "DAE - Removing argument " << i << " (" << I->getName()
Daniel Dunbar460f6562009-07-26 09:48:23 +0000748 << ") from " << F->getName() << "\n");
Duncan Sandsdc024672007-11-27 13:23:08 +0000749 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000750 }
Duncan Sandsdc024672007-11-27 13:23:08 +0000751
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000752 if (FnAttrs != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000753 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
754
Devang Patel05988662008-09-25 21:00:45 +0000755 // Reconstruct the AttributesList based on the vector we constructed.
Gabor Greifc8b82cc2010-04-01 08:21:08 +0000756 AttrListPtr NewPAL = AttrListPtr::get(AttributesVec.begin(),
757 AttributesVec.end());
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000758
Duncan Sandsdc024672007-11-27 13:23:08 +0000759 // Create the new function type based on the recomputed parameters.
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000760 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000761
762 // No change?
763 if (NFTy == FTy)
764 return false;
765
Chris Lattner08227e42003-06-17 22:21:05 +0000766 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000767 Function *NF = Function::Create(NFTy, F->getLinkage());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000768 NF->copyAttributesFrom(F);
Devang Patel05988662008-09-25 21:00:45 +0000769 NF->setAttributes(NewPAL);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000770 // Insert the new function before the old function, so we won't be processing
771 // it again.
Chris Lattner08227e42003-06-17 22:21:05 +0000772 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner046800a2007-02-11 01:08:35 +0000773 NF->takeName(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000774
775 // Loop over all of the callers of the function, transforming the call sites
776 // to pass in a smaller number of arguments into the new function.
777 //
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000778 std::vector<Value*> Args;
Chris Lattner08227e42003-06-17 22:21:05 +0000779 while (!F->use_empty()) {
Gabor Greif7d3056b2010-07-28 22:50:26 +0000780 CallSite CS(F->use_back());
Chris Lattner08227e42003-06-17 22:21:05 +0000781 Instruction *Call = CS.getInstruction();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000782
Devang Patel05988662008-09-25 21:00:45 +0000783 AttributesVec.clear();
784 const AttrListPtr &CallPAL = CS.getAttributes();
Duncan Sands110c8352007-12-21 19:16:16 +0000785
786 // The call return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000787 Attributes RAttrs = CallPAL.getRetAttributes();
788 Attributes FnAttrs = CallPAL.getFnAttributes();
Duncan Sands110c8352007-12-21 19:16:16 +0000789 // Adjust in case the function was changed to return void.
Devang Patel05988662008-09-25 21:00:45 +0000790 RAttrs &= ~Attribute::typeIncompatible(NF->getReturnType());
Duncan Sands110c8352007-12-21 19:16:16 +0000791 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +0000792 AttributesVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000793
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000794 // Declare these outside of the loops, so we can reuse them for the second
795 // loop, which loops the varargs.
796 CallSite::arg_iterator I = CS.arg_begin();
797 unsigned i = 0;
798 // Loop over those operands, corresponding to the normal arguments to the
799 // original function, and add those that are still alive.
800 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
801 if (ArgAlive[i]) {
802 Args.push_back(*I);
803 // Get original parameter attributes, but skip return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000804 if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +0000805 AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
Duncan Sands110c8352007-12-21 19:16:16 +0000806 }
807
Evan Chengb2fc2a32008-01-17 04:18:54 +0000808 // Push any varargs arguments on the list. Don't forget their attributes.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000809 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
810 Args.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +0000811 if (Attributes Attrs = CallPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +0000812 AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
Evan Chengb2fc2a32008-01-17 04:18:54 +0000813 }
814
Devang Patel19c87462008-09-26 22:53:05 +0000815 if (FnAttrs != Attribute::None)
816 AttributesVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
817
Devang Patel05988662008-09-25 21:00:45 +0000818 // Reconstruct the AttributesList based on the vector we constructed.
819 AttrListPtr NewCallPAL = AttrListPtr::get(AttributesVec.begin(),
Devang Patel19c87462008-09-26 22:53:05 +0000820 AttributesVec.end());
Chris Lattnerff5bf9c2003-10-23 17:44:53 +0000821
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000822 Instruction *New;
823 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000824 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
825 Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000826 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000827 cast<InvokeInst>(New)->setAttributes(NewCallPAL);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000828 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000829 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000830 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000831 cast<CallInst>(New)->setAttributes(NewCallPAL);
Chris Lattner1430ef12005-05-06 06:46:58 +0000832 if (cast<CallInst>(Call)->isTailCall())
833 cast<CallInst>(New)->setTailCall();
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000834 }
Dan Gohmanbda02522010-07-20 20:09:07 +0000835 New->setDebugLoc(Call->getDebugLoc());
Devang Patel0aa885d2010-04-30 20:23:54 +0000836
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000837 Args.clear();
838
839 if (!Call->use_empty()) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000840 if (New->getType() == Call->getType()) {
841 // Return type not changed? Just replace users then.
Evan Cheng890aaa82008-06-25 18:10:09 +0000842 Call->replaceAllUsesWith(New);
Matthijs Kooijman1d9a2772008-06-24 16:30:26 +0000843 New->takeName(Call);
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000844 } else if (New->getType()->isVoidTy()) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000845 // Our return value has uses, but they will get removed later on.
846 // Replace by null for now.
Dale Johannesen0488fb62010-09-30 23:57:10 +0000847 if (!Call->getType()->isX86_MMXTy())
848 Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000849 } else {
Duncan Sands1df98592010-02-16 11:11:14 +0000850 assert(RetTy->isStructTy() &&
Chris Lattnerbda07652009-03-18 00:31:45 +0000851 "Return type changed, but not into a void. The old return type"
852 " must have been a struct!");
853 Instruction *InsertPt = Call;
Chris Lattnerf023b542009-03-18 16:23:56 +0000854 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Chris Lattnera5affdc2009-03-18 16:48:45 +0000855 BasicBlock::iterator IP = II->getNormalDest()->begin();
856 while (isa<PHINode>(IP)) ++IP;
857 InsertPt = IP;
Chris Lattnerf023b542009-03-18 16:23:56 +0000858 }
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000859
Matthijs Kooijmaneb32b452008-07-15 14:03:10 +0000860 // We used to return a struct. Instead of doing smart stuff with all the
861 // uses of this struct, we will just rebuild it using
862 // extract/insertvalue chaining and let instcombine clean that up.
863 //
864 // Start out building up our return value from undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000865 Value *RetVal = UndefValue::get(RetTy);
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000866 for (unsigned i = 0; i != RetCount; ++i)
Matthijs Kooijmaneb32b452008-07-15 14:03:10 +0000867 if (NewRetIdxs[i] != -1) {
868 Value *V;
869 if (RetTypes.size() > 1)
870 // We are still returning a struct, so extract the value from our
871 // return value
Chris Lattnerbda07652009-03-18 00:31:45 +0000872 V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
873 InsertPt);
Matthijs Kooijmaneb32b452008-07-15 14:03:10 +0000874 else
875 // We are now returning a single element, so just insert that
876 V = New;
877 // Insert the value at the old position
Chris Lattnerbda07652009-03-18 00:31:45 +0000878 RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000879 }
Matthijs Kooijmaneb32b452008-07-15 14:03:10 +0000880 // Now, replace all uses of the old call instruction with the return
881 // struct we built
882 Call->replaceAllUsesWith(RetVal);
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000883 New->takeName(Call);
Matthijs Kooijman7e43b3b2008-06-20 15:34:07 +0000884 }
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000885 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000886
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000887 // Finally, remove the old call from the program, reducing the use-count of
888 // F.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000889 Call->eraseFromParent();
Chris Lattner08227e42003-06-17 22:21:05 +0000890 }
891
892 // Since we have now created the new function, splice the body of the old
893 // function right into the new function, leaving the old rotting hulk of the
894 // function empty.
895 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
896
897 // Loop over the argument list, transfering uses of the old arguments over to
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000898 // the new arguments, also transfering over the names as well.
899 i = 0;
Chris Lattner19bdc032005-05-06 05:34:40 +0000900 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000901 I2 = NF->arg_begin(); I != E; ++I, ++i)
902 if (ArgAlive[i]) {
Chris Lattner08227e42003-06-17 22:21:05 +0000903 // If this is a live argument, move the name and users over to the new
904 // version.
905 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000906 I2->takeName(I);
Chris Lattner08227e42003-06-17 22:21:05 +0000907 ++I2;
908 } else {
909 // If this argument is dead, replace any uses of it with null constants
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000910 // (these are guaranteed to become unused later on).
Dale Johannesen0488fb62010-09-30 23:57:10 +0000911 if (!I->getType()->isX86_MMXTy())
912 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
Chris Lattner08227e42003-06-17 22:21:05 +0000913 }
914
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000915 // If we change the return value of the function we must rewrite any return
916 // instructions. Check this now.
917 if (F->getReturnType() != NF->getReturnType())
918 for (Function::iterator BB = NF->begin(), E = NF->end(); BB != E; ++BB)
919 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000920 Value *RetVal;
921
Nick Lewycky1462a9b2010-05-15 03:41:58 +0000922 if (NFTy->getReturnType()->isVoidTy()) {
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000923 RetVal = 0;
924 } else {
Duncan Sands1df98592010-02-16 11:11:14 +0000925 assert (RetTy->isStructTy());
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000926 // The original return value was a struct, insert
927 // extractvalue/insertvalue chains to extract only the values we need
928 // to return and insert them into our new result.
929 // This does generate messy code, but we'll let it to instcombine to
930 // clean that up.
931 Value *OldRet = RI->getOperand(0);
932 // Start out building up our return value from undef
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000933 RetVal = UndefValue::get(NRetTy);
Matthijs Kooijmand1d1de72008-07-15 14:39:36 +0000934 for (unsigned i = 0; i != RetCount; ++i)
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000935 if (NewRetIdxs[i] != -1) {
936 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
937 "oldret", RI);
938 if (RetTypes.size() > 1) {
939 // We're still returning a struct, so reinsert the value into
940 // our new return value at the new index
941
942 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
943 "newret", RI);
944 } else {
945 // We are now only returning a simple value, so just return the
946 // extracted value.
947 RetVal = EV;
948 }
949 }
950 }
951 // Replace the return instruction with one returning the new return
952 // value (possibly 0 if we became void).
Owen Anderson1d0be152009-08-13 21:58:54 +0000953 ReturnInst::Create(F->getContext(), RetVal, RI);
Chris Lattnerc3afd9b2003-10-23 03:48:17 +0000954 BB->getInstList().erase(RI);
955 }
956
Chris Lattner08227e42003-06-17 22:21:05 +0000957 // Now that the old function is dead, delete it.
Matthijs Kooijman494661c2008-05-30 12:35:46 +0000958 F->eraseFromParent();
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000959
960 return true;
Chris Lattner08227e42003-06-17 22:21:05 +0000961}
962
Chris Lattnerb12914b2004-09-20 04:48:05 +0000963bool DAE::runOnModule(Module &M) {
Chris Lattner701bc422007-11-15 06:10:55 +0000964 bool Changed = false;
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000965
Chris Lattner701bc422007-11-15 06:10:55 +0000966 // First pass: Do a simple check to see if any functions can have their "..."
967 // removed. We can do this if they never call va_start. This loop cannot be
968 // fused with the next loop, because deleting a function invalidates
969 // information computed while surveying other functions.
David Greene3307e952010-01-05 01:28:29 +0000970 DEBUG(dbgs() << "DAE - Deleting dead varargs\n");
Chris Lattner701bc422007-11-15 06:10:55 +0000971 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
972 Function &F = *I++;
973 if (F.getFunctionType()->isVarArg())
974 Changed |= DeleteDeadVarargs(F);
975 }
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000976
Chris Lattner701bc422007-11-15 06:10:55 +0000977 // Second phase:loop through the module, determining which arguments are live.
Chris Lattner08227e42003-06-17 22:21:05 +0000978 // We assume all arguments are dead unless proven otherwise (allowing us to
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000979 // determine that dead arguments passed into recursive functions are dead).
Chris Lattner08227e42003-06-17 22:21:05 +0000980 //
David Greene3307e952010-01-05 01:28:29 +0000981 DEBUG(dbgs() << "DAE - Determining liveness\n");
Chris Lattner701bc422007-11-15 06:10:55 +0000982 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
983 SurveyFunction(*I);
Gabor Greif6d6aaec2010-03-24 11:58:07 +0000984
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000985 // Now, remove all dead arguments and return values from each function in
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000986 // turn.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000987 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
Nick Lewycky2d7820c2010-04-01 07:34:00 +0000988 // Increment now, because the function will probably get removed (ie.
Matthijs Kooijmand16918f2008-07-10 10:24:08 +0000989 // replaced by a new one).
990 Function *F = I++;
Nick Lewycky3715e452010-04-14 04:51:58 +0000991 Changed |= RemoveDeadStuffFromFunction(F);
Chris Lattner08227e42003-06-17 22:21:05 +0000992 }
Anders Carlsson0599c6b2011-01-16 21:25:33 +0000993
994 // Finally, look for any unused parameters in functions with non-local
995 // linkage and replace the passed in parameters with undef.
996 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
997 Function& F = *I;
998
999 Changed |= RemoveDeadArgumentsFromCallers(F);
1000 }
1001
Matthijs Kooijmand16918f2008-07-10 10:24:08 +00001002 return Changed;
Chris Lattner08227e42003-06-17 22:21:05 +00001003}