1*9880d681SAndroid Build Coastguard Worker //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass deletes dead arguments from internal functions. Dead argument
11*9880d681SAndroid Build Coastguard Worker // elimination removes arguments which are directly dead, as well as arguments
12*9880d681SAndroid Build Coastguard Worker // only passed into function calls as dead arguments of other functions. This
13*9880d681SAndroid Build Coastguard Worker // pass also deletes dead return values in a similar way.
14*9880d681SAndroid Build Coastguard Worker //
15*9880d681SAndroid Build Coastguard Worker // This pass is often useful as a cleanup pass to run after aggressive
16*9880d681SAndroid Build Coastguard Worker // interprocedural passes, which add possibly-dead arguments or return values.
17*9880d681SAndroid Build Coastguard Worker //
18*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
19*9880d681SAndroid Build Coastguard Worker
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallVector.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/StringExtras.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CallSite.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CallingConv.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constant.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DIBuilder.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DebugInfo.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DerivedTypes.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/IPO.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39*9880d681SAndroid Build Coastguard Worker #include <set>
40*9880d681SAndroid Build Coastguard Worker #include <tuple>
41*9880d681SAndroid Build Coastguard Worker using namespace llvm;
42*9880d681SAndroid Build Coastguard Worker
43*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "deadargelim"
44*9880d681SAndroid Build Coastguard Worker
45*9880d681SAndroid Build Coastguard Worker STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
46*9880d681SAndroid Build Coastguard Worker STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
47*9880d681SAndroid Build Coastguard Worker STATISTIC(NumArgumentsReplacedWithUndef,
48*9880d681SAndroid Build Coastguard Worker "Number of unread args replaced with undef");
49*9880d681SAndroid Build Coastguard Worker namespace {
50*9880d681SAndroid Build Coastguard Worker /// DAE - The dead argument elimination pass.
51*9880d681SAndroid Build Coastguard Worker ///
52*9880d681SAndroid Build Coastguard Worker class DAE : public ModulePass {
53*9880d681SAndroid Build Coastguard Worker protected:
54*9880d681SAndroid Build Coastguard Worker // DAH uses this to specify a different ID.
DAE(char & ID)55*9880d681SAndroid Build Coastguard Worker explicit DAE(char &ID) : ModulePass(ID) {}
56*9880d681SAndroid Build Coastguard Worker
57*9880d681SAndroid Build Coastguard Worker public:
58*9880d681SAndroid Build Coastguard Worker static char ID; // Pass identification, replacement for typeid
DAE()59*9880d681SAndroid Build Coastguard Worker DAE() : ModulePass(ID) {
60*9880d681SAndroid Build Coastguard Worker initializeDAEPass(*PassRegistry::getPassRegistry());
61*9880d681SAndroid Build Coastguard Worker }
62*9880d681SAndroid Build Coastguard Worker
runOnModule(Module & M)63*9880d681SAndroid Build Coastguard Worker bool runOnModule(Module &M) override {
64*9880d681SAndroid Build Coastguard Worker if (skipModule(M))
65*9880d681SAndroid Build Coastguard Worker return false;
66*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass DAEP(ShouldHackArguments());
67*9880d681SAndroid Build Coastguard Worker ModuleAnalysisManager DummyMAM;
68*9880d681SAndroid Build Coastguard Worker PreservedAnalyses PA = DAEP.run(M, DummyMAM);
69*9880d681SAndroid Build Coastguard Worker return !PA.areAllPreserved();
70*9880d681SAndroid Build Coastguard Worker }
71*9880d681SAndroid Build Coastguard Worker
ShouldHackArguments() const72*9880d681SAndroid Build Coastguard Worker virtual bool ShouldHackArguments() const { return false; }
73*9880d681SAndroid Build Coastguard Worker };
74*9880d681SAndroid Build Coastguard Worker }
75*9880d681SAndroid Build Coastguard Worker
76*9880d681SAndroid Build Coastguard Worker
77*9880d681SAndroid Build Coastguard Worker char DAE::ID = 0;
78*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
79*9880d681SAndroid Build Coastguard Worker
80*9880d681SAndroid Build Coastguard Worker namespace {
81*9880d681SAndroid Build Coastguard Worker /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
82*9880d681SAndroid Build Coastguard Worker /// deletes arguments to functions which are external. This is only for use
83*9880d681SAndroid Build Coastguard Worker /// by bugpoint.
84*9880d681SAndroid Build Coastguard Worker struct DAH : public DAE {
85*9880d681SAndroid Build Coastguard Worker static char ID;
DAH__anonae6e3c070211::DAH86*9880d681SAndroid Build Coastguard Worker DAH() : DAE(ID) {}
87*9880d681SAndroid Build Coastguard Worker
ShouldHackArguments__anonae6e3c070211::DAH88*9880d681SAndroid Build Coastguard Worker bool ShouldHackArguments() const override { return true; }
89*9880d681SAndroid Build Coastguard Worker };
90*9880d681SAndroid Build Coastguard Worker }
91*9880d681SAndroid Build Coastguard Worker
92*9880d681SAndroid Build Coastguard Worker char DAH::ID = 0;
93*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS(DAH, "deadarghaX0r",
94*9880d681SAndroid Build Coastguard Worker "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
95*9880d681SAndroid Build Coastguard Worker false, false)
96*9880d681SAndroid Build Coastguard Worker
97*9880d681SAndroid Build Coastguard Worker /// createDeadArgEliminationPass - This pass removes arguments from functions
98*9880d681SAndroid Build Coastguard Worker /// which are not used by the body of the function.
99*9880d681SAndroid Build Coastguard Worker ///
createDeadArgEliminationPass()100*9880d681SAndroid Build Coastguard Worker ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
createDeadArgHackingPass()101*9880d681SAndroid Build Coastguard Worker ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
102*9880d681SAndroid Build Coastguard Worker
103*9880d681SAndroid Build Coastguard Worker /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
104*9880d681SAndroid Build Coastguard Worker /// llvm.vastart is never called, the varargs list is dead for the function.
DeleteDeadVarargs(Function & Fn)105*9880d681SAndroid Build Coastguard Worker bool DeadArgumentEliminationPass::DeleteDeadVarargs(Function &Fn) {
106*9880d681SAndroid Build Coastguard Worker assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
107*9880d681SAndroid Build Coastguard Worker if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
108*9880d681SAndroid Build Coastguard Worker
109*9880d681SAndroid Build Coastguard Worker // Ensure that the function is only directly called.
110*9880d681SAndroid Build Coastguard Worker if (Fn.hasAddressTaken())
111*9880d681SAndroid Build Coastguard Worker return false;
112*9880d681SAndroid Build Coastguard Worker
113*9880d681SAndroid Build Coastguard Worker // Don't touch naked functions. The assembly might be using an argument, or
114*9880d681SAndroid Build Coastguard Worker // otherwise rely on the frame layout in a way that this analysis will not
115*9880d681SAndroid Build Coastguard Worker // see.
116*9880d681SAndroid Build Coastguard Worker if (Fn.hasFnAttribute(Attribute::Naked)) {
117*9880d681SAndroid Build Coastguard Worker return false;
118*9880d681SAndroid Build Coastguard Worker }
119*9880d681SAndroid Build Coastguard Worker
120*9880d681SAndroid Build Coastguard Worker // Okay, we know we can transform this function if safe. Scan its body
121*9880d681SAndroid Build Coastguard Worker // looking for calls marked musttail or calls to llvm.vastart.
122*9880d681SAndroid Build Coastguard Worker for (BasicBlock &BB : Fn) {
123*9880d681SAndroid Build Coastguard Worker for (Instruction &I : BB) {
124*9880d681SAndroid Build Coastguard Worker CallInst *CI = dyn_cast<CallInst>(&I);
125*9880d681SAndroid Build Coastguard Worker if (!CI)
126*9880d681SAndroid Build Coastguard Worker continue;
127*9880d681SAndroid Build Coastguard Worker if (CI->isMustTailCall())
128*9880d681SAndroid Build Coastguard Worker return false;
129*9880d681SAndroid Build Coastguard Worker if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
130*9880d681SAndroid Build Coastguard Worker if (II->getIntrinsicID() == Intrinsic::vastart)
131*9880d681SAndroid Build Coastguard Worker return false;
132*9880d681SAndroid Build Coastguard Worker }
133*9880d681SAndroid Build Coastguard Worker }
134*9880d681SAndroid Build Coastguard Worker }
135*9880d681SAndroid Build Coastguard Worker
136*9880d681SAndroid Build Coastguard Worker // If we get here, there are no calls to llvm.vastart in the function body,
137*9880d681SAndroid Build Coastguard Worker // remove the "..." and adjust all the calls.
138*9880d681SAndroid Build Coastguard Worker
139*9880d681SAndroid Build Coastguard Worker // Start by computing a new prototype for the function, which is the same as
140*9880d681SAndroid Build Coastguard Worker // the old function, but doesn't have isVarArg set.
141*9880d681SAndroid Build Coastguard Worker FunctionType *FTy = Fn.getFunctionType();
142*9880d681SAndroid Build Coastguard Worker
143*9880d681SAndroid Build Coastguard Worker std::vector<Type*> Params(FTy->param_begin(), FTy->param_end());
144*9880d681SAndroid Build Coastguard Worker FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
145*9880d681SAndroid Build Coastguard Worker Params, false);
146*9880d681SAndroid Build Coastguard Worker unsigned NumArgs = Params.size();
147*9880d681SAndroid Build Coastguard Worker
148*9880d681SAndroid Build Coastguard Worker // Create the new function body and insert it into the module...
149*9880d681SAndroid Build Coastguard Worker Function *NF = Function::Create(NFTy, Fn.getLinkage());
150*9880d681SAndroid Build Coastguard Worker NF->copyAttributesFrom(&Fn);
151*9880d681SAndroid Build Coastguard Worker NF->setComdat(Fn.getComdat());
152*9880d681SAndroid Build Coastguard Worker Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF);
153*9880d681SAndroid Build Coastguard Worker NF->takeName(&Fn);
154*9880d681SAndroid Build Coastguard Worker
155*9880d681SAndroid Build Coastguard Worker // Loop over all of the callers of the function, transforming the call sites
156*9880d681SAndroid Build Coastguard Worker // to pass in a smaller number of arguments into the new function.
157*9880d681SAndroid Build Coastguard Worker //
158*9880d681SAndroid Build Coastguard Worker std::vector<Value*> Args;
159*9880d681SAndroid Build Coastguard Worker for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) {
160*9880d681SAndroid Build Coastguard Worker CallSite CS(*I++);
161*9880d681SAndroid Build Coastguard Worker if (!CS)
162*9880d681SAndroid Build Coastguard Worker continue;
163*9880d681SAndroid Build Coastguard Worker Instruction *Call = CS.getInstruction();
164*9880d681SAndroid Build Coastguard Worker
165*9880d681SAndroid Build Coastguard Worker // Pass all the same arguments.
166*9880d681SAndroid Build Coastguard Worker Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
167*9880d681SAndroid Build Coastguard Worker
168*9880d681SAndroid Build Coastguard Worker // Drop any attributes that were on the vararg arguments.
169*9880d681SAndroid Build Coastguard Worker AttributeSet PAL = CS.getAttributes();
170*9880d681SAndroid Build Coastguard Worker if (!PAL.isEmpty() && PAL.getSlotIndex(PAL.getNumSlots() - 1) > NumArgs) {
171*9880d681SAndroid Build Coastguard Worker SmallVector<AttributeSet, 8> AttributesVec;
172*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; PAL.getSlotIndex(i) <= NumArgs; ++i)
173*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(PAL.getSlotAttributes(i));
174*9880d681SAndroid Build Coastguard Worker if (PAL.hasAttributes(AttributeSet::FunctionIndex))
175*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(Fn.getContext(),
176*9880d681SAndroid Build Coastguard Worker PAL.getFnAttributes()));
177*9880d681SAndroid Build Coastguard Worker PAL = AttributeSet::get(Fn.getContext(), AttributesVec);
178*9880d681SAndroid Build Coastguard Worker }
179*9880d681SAndroid Build Coastguard Worker
180*9880d681SAndroid Build Coastguard Worker SmallVector<OperandBundleDef, 1> OpBundles;
181*9880d681SAndroid Build Coastguard Worker CS.getOperandBundlesAsDefs(OpBundles);
182*9880d681SAndroid Build Coastguard Worker
183*9880d681SAndroid Build Coastguard Worker Instruction *New;
184*9880d681SAndroid Build Coastguard Worker if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
185*9880d681SAndroid Build Coastguard Worker New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
186*9880d681SAndroid Build Coastguard Worker Args, OpBundles, "", Call);
187*9880d681SAndroid Build Coastguard Worker cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
188*9880d681SAndroid Build Coastguard Worker cast<InvokeInst>(New)->setAttributes(PAL);
189*9880d681SAndroid Build Coastguard Worker } else {
190*9880d681SAndroid Build Coastguard Worker New = CallInst::Create(NF, Args, OpBundles, "", Call);
191*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
192*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setAttributes(PAL);
193*9880d681SAndroid Build Coastguard Worker if (cast<CallInst>(Call)->isTailCall())
194*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setTailCall();
195*9880d681SAndroid Build Coastguard Worker }
196*9880d681SAndroid Build Coastguard Worker New->setDebugLoc(Call->getDebugLoc());
197*9880d681SAndroid Build Coastguard Worker
198*9880d681SAndroid Build Coastguard Worker Args.clear();
199*9880d681SAndroid Build Coastguard Worker
200*9880d681SAndroid Build Coastguard Worker if (!Call->use_empty())
201*9880d681SAndroid Build Coastguard Worker Call->replaceAllUsesWith(New);
202*9880d681SAndroid Build Coastguard Worker
203*9880d681SAndroid Build Coastguard Worker New->takeName(Call);
204*9880d681SAndroid Build Coastguard Worker
205*9880d681SAndroid Build Coastguard Worker // Finally, remove the old call from the program, reducing the use-count of
206*9880d681SAndroid Build Coastguard Worker // F.
207*9880d681SAndroid Build Coastguard Worker Call->eraseFromParent();
208*9880d681SAndroid Build Coastguard Worker }
209*9880d681SAndroid Build Coastguard Worker
210*9880d681SAndroid Build Coastguard Worker // Since we have now created the new function, splice the body of the old
211*9880d681SAndroid Build Coastguard Worker // function right into the new function, leaving the old rotting hulk of the
212*9880d681SAndroid Build Coastguard Worker // function empty.
213*9880d681SAndroid Build Coastguard Worker NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
214*9880d681SAndroid Build Coastguard Worker
215*9880d681SAndroid Build Coastguard Worker // Loop over the argument list, transferring uses of the old arguments over to
216*9880d681SAndroid Build Coastguard Worker // the new arguments, also transferring over the names as well. While we're at
217*9880d681SAndroid Build Coastguard Worker // it, remove the dead arguments from the DeadArguments list.
218*9880d681SAndroid Build Coastguard Worker //
219*9880d681SAndroid Build Coastguard Worker for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
220*9880d681SAndroid Build Coastguard Worker I2 = NF->arg_begin(); I != E; ++I, ++I2) {
221*9880d681SAndroid Build Coastguard Worker // Move the name and users over to the new version.
222*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(&*I2);
223*9880d681SAndroid Build Coastguard Worker I2->takeName(&*I);
224*9880d681SAndroid Build Coastguard Worker }
225*9880d681SAndroid Build Coastguard Worker
226*9880d681SAndroid Build Coastguard Worker // Patch the pointer to LLVM function in debug info descriptor.
227*9880d681SAndroid Build Coastguard Worker NF->setSubprogram(Fn.getSubprogram());
228*9880d681SAndroid Build Coastguard Worker
229*9880d681SAndroid Build Coastguard Worker // Fix up any BlockAddresses that refer to the function.
230*9880d681SAndroid Build Coastguard Worker Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType()));
231*9880d681SAndroid Build Coastguard Worker // Delete the bitcast that we just created, so that NF does not
232*9880d681SAndroid Build Coastguard Worker // appear to be address-taken.
233*9880d681SAndroid Build Coastguard Worker NF->removeDeadConstantUsers();
234*9880d681SAndroid Build Coastguard Worker // Finally, nuke the old function.
235*9880d681SAndroid Build Coastguard Worker Fn.eraseFromParent();
236*9880d681SAndroid Build Coastguard Worker return true;
237*9880d681SAndroid Build Coastguard Worker }
238*9880d681SAndroid Build Coastguard Worker
239*9880d681SAndroid Build Coastguard Worker /// RemoveDeadArgumentsFromCallers - Checks if the given function has any
240*9880d681SAndroid Build Coastguard Worker /// arguments that are unused, and changes the caller parameters to be undefined
241*9880d681SAndroid Build Coastguard Worker /// instead.
RemoveDeadArgumentsFromCallers(Function & Fn)242*9880d681SAndroid Build Coastguard Worker bool DeadArgumentEliminationPass::RemoveDeadArgumentsFromCallers(Function &Fn) {
243*9880d681SAndroid Build Coastguard Worker // We cannot change the arguments if this TU does not define the function or
244*9880d681SAndroid Build Coastguard Worker // if the linker may choose a function body from another TU, even if the
245*9880d681SAndroid Build Coastguard Worker // nominal linkage indicates that other copies of the function have the same
246*9880d681SAndroid Build Coastguard Worker // semantics. In the below example, the dead load from %p may not have been
247*9880d681SAndroid Build Coastguard Worker // eliminated from the linker-chosen copy of f, so replacing %p with undef
248*9880d681SAndroid Build Coastguard Worker // in callers may introduce undefined behavior.
249*9880d681SAndroid Build Coastguard Worker //
250*9880d681SAndroid Build Coastguard Worker // define linkonce_odr void @f(i32* %p) {
251*9880d681SAndroid Build Coastguard Worker // %v = load i32 %p
252*9880d681SAndroid Build Coastguard Worker // ret void
253*9880d681SAndroid Build Coastguard Worker // }
254*9880d681SAndroid Build Coastguard Worker if (!Fn.hasExactDefinition())
255*9880d681SAndroid Build Coastguard Worker return false;
256*9880d681SAndroid Build Coastguard Worker
257*9880d681SAndroid Build Coastguard Worker // Functions with local linkage should already have been handled, except the
258*9880d681SAndroid Build Coastguard Worker // fragile (variadic) ones which we can improve here.
259*9880d681SAndroid Build Coastguard Worker if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg())
260*9880d681SAndroid Build Coastguard Worker return false;
261*9880d681SAndroid Build Coastguard Worker
262*9880d681SAndroid Build Coastguard Worker // Don't touch naked functions. The assembly might be using an argument, or
263*9880d681SAndroid Build Coastguard Worker // otherwise rely on the frame layout in a way that this analysis will not
264*9880d681SAndroid Build Coastguard Worker // see.
265*9880d681SAndroid Build Coastguard Worker if (Fn.hasFnAttribute(Attribute::Naked))
266*9880d681SAndroid Build Coastguard Worker return false;
267*9880d681SAndroid Build Coastguard Worker
268*9880d681SAndroid Build Coastguard Worker if (Fn.use_empty())
269*9880d681SAndroid Build Coastguard Worker return false;
270*9880d681SAndroid Build Coastguard Worker
271*9880d681SAndroid Build Coastguard Worker SmallVector<unsigned, 8> UnusedArgs;
272*9880d681SAndroid Build Coastguard Worker for (Argument &Arg : Fn.args()) {
273*9880d681SAndroid Build Coastguard Worker if (Arg.use_empty() && !Arg.hasByValOrInAllocaAttr())
274*9880d681SAndroid Build Coastguard Worker UnusedArgs.push_back(Arg.getArgNo());
275*9880d681SAndroid Build Coastguard Worker }
276*9880d681SAndroid Build Coastguard Worker
277*9880d681SAndroid Build Coastguard Worker if (UnusedArgs.empty())
278*9880d681SAndroid Build Coastguard Worker return false;
279*9880d681SAndroid Build Coastguard Worker
280*9880d681SAndroid Build Coastguard Worker bool Changed = false;
281*9880d681SAndroid Build Coastguard Worker
282*9880d681SAndroid Build Coastguard Worker for (Use &U : Fn.uses()) {
283*9880d681SAndroid Build Coastguard Worker CallSite CS(U.getUser());
284*9880d681SAndroid Build Coastguard Worker if (!CS || !CS.isCallee(&U))
285*9880d681SAndroid Build Coastguard Worker continue;
286*9880d681SAndroid Build Coastguard Worker
287*9880d681SAndroid Build Coastguard Worker // Now go through all unused args and replace them with "undef".
288*9880d681SAndroid Build Coastguard Worker for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
289*9880d681SAndroid Build Coastguard Worker unsigned ArgNo = UnusedArgs[I];
290*9880d681SAndroid Build Coastguard Worker
291*9880d681SAndroid Build Coastguard Worker Value *Arg = CS.getArgument(ArgNo);
292*9880d681SAndroid Build Coastguard Worker CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
293*9880d681SAndroid Build Coastguard Worker ++NumArgumentsReplacedWithUndef;
294*9880d681SAndroid Build Coastguard Worker Changed = true;
295*9880d681SAndroid Build Coastguard Worker }
296*9880d681SAndroid Build Coastguard Worker }
297*9880d681SAndroid Build Coastguard Worker
298*9880d681SAndroid Build Coastguard Worker return Changed;
299*9880d681SAndroid Build Coastguard Worker }
300*9880d681SAndroid Build Coastguard Worker
301*9880d681SAndroid Build Coastguard Worker /// Convenience function that returns the number of return values. It returns 0
302*9880d681SAndroid Build Coastguard Worker /// for void functions and 1 for functions not returning a struct. It returns
303*9880d681SAndroid Build Coastguard Worker /// the number of struct elements for functions returning a struct.
NumRetVals(const Function * F)304*9880d681SAndroid Build Coastguard Worker static unsigned NumRetVals(const Function *F) {
305*9880d681SAndroid Build Coastguard Worker Type *RetTy = F->getReturnType();
306*9880d681SAndroid Build Coastguard Worker if (RetTy->isVoidTy())
307*9880d681SAndroid Build Coastguard Worker return 0;
308*9880d681SAndroid Build Coastguard Worker else if (StructType *STy = dyn_cast<StructType>(RetTy))
309*9880d681SAndroid Build Coastguard Worker return STy->getNumElements();
310*9880d681SAndroid Build Coastguard Worker else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
311*9880d681SAndroid Build Coastguard Worker return ATy->getNumElements();
312*9880d681SAndroid Build Coastguard Worker else
313*9880d681SAndroid Build Coastguard Worker return 1;
314*9880d681SAndroid Build Coastguard Worker }
315*9880d681SAndroid Build Coastguard Worker
316*9880d681SAndroid Build Coastguard Worker /// Returns the sub-type a function will return at a given Idx. Should
317*9880d681SAndroid Build Coastguard Worker /// correspond to the result type of an ExtractValue instruction executed with
318*9880d681SAndroid Build Coastguard Worker /// just that one Idx (i.e. only top-level structure is considered).
getRetComponentType(const Function * F,unsigned Idx)319*9880d681SAndroid Build Coastguard Worker static Type *getRetComponentType(const Function *F, unsigned Idx) {
320*9880d681SAndroid Build Coastguard Worker Type *RetTy = F->getReturnType();
321*9880d681SAndroid Build Coastguard Worker assert(!RetTy->isVoidTy() && "void type has no subtype");
322*9880d681SAndroid Build Coastguard Worker
323*9880d681SAndroid Build Coastguard Worker if (StructType *STy = dyn_cast<StructType>(RetTy))
324*9880d681SAndroid Build Coastguard Worker return STy->getElementType(Idx);
325*9880d681SAndroid Build Coastguard Worker else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
326*9880d681SAndroid Build Coastguard Worker return ATy->getElementType();
327*9880d681SAndroid Build Coastguard Worker else
328*9880d681SAndroid Build Coastguard Worker return RetTy;
329*9880d681SAndroid Build Coastguard Worker }
330*9880d681SAndroid Build Coastguard Worker
331*9880d681SAndroid Build Coastguard Worker /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
332*9880d681SAndroid Build Coastguard Worker /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
333*9880d681SAndroid Build Coastguard Worker /// liveness of Use.
334*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass::Liveness
MarkIfNotLive(RetOrArg Use,UseVector & MaybeLiveUses)335*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass::MarkIfNotLive(RetOrArg Use,
336*9880d681SAndroid Build Coastguard Worker UseVector &MaybeLiveUses) {
337*9880d681SAndroid Build Coastguard Worker // We're live if our use or its Function is already marked as live.
338*9880d681SAndroid Build Coastguard Worker if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
339*9880d681SAndroid Build Coastguard Worker return Live;
340*9880d681SAndroid Build Coastguard Worker
341*9880d681SAndroid Build Coastguard Worker // We're maybe live otherwise, but remember that we must become live if
342*9880d681SAndroid Build Coastguard Worker // Use becomes live.
343*9880d681SAndroid Build Coastguard Worker MaybeLiveUses.push_back(Use);
344*9880d681SAndroid Build Coastguard Worker return MaybeLive;
345*9880d681SAndroid Build Coastguard Worker }
346*9880d681SAndroid Build Coastguard Worker
347*9880d681SAndroid Build Coastguard Worker
348*9880d681SAndroid Build Coastguard Worker /// SurveyUse - This looks at a single use of an argument or return value
349*9880d681SAndroid Build Coastguard Worker /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
350*9880d681SAndroid Build Coastguard Worker /// if it causes the used value to become MaybeLive.
351*9880d681SAndroid Build Coastguard Worker ///
352*9880d681SAndroid Build Coastguard Worker /// RetValNum is the return value number to use when this use is used in a
353*9880d681SAndroid Build Coastguard Worker /// return instruction. This is used in the recursion, you should always leave
354*9880d681SAndroid Build Coastguard Worker /// it at 0.
355*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass::Liveness
SurveyUse(const Use * U,UseVector & MaybeLiveUses,unsigned RetValNum)356*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass::SurveyUse(const Use *U, UseVector &MaybeLiveUses,
357*9880d681SAndroid Build Coastguard Worker unsigned RetValNum) {
358*9880d681SAndroid Build Coastguard Worker const User *V = U->getUser();
359*9880d681SAndroid Build Coastguard Worker if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
360*9880d681SAndroid Build Coastguard Worker // The value is returned from a function. It's only live when the
361*9880d681SAndroid Build Coastguard Worker // function's return value is live. We use RetValNum here, for the case
362*9880d681SAndroid Build Coastguard Worker // that U is really a use of an insertvalue instruction that uses the
363*9880d681SAndroid Build Coastguard Worker // original Use.
364*9880d681SAndroid Build Coastguard Worker const Function *F = RI->getParent()->getParent();
365*9880d681SAndroid Build Coastguard Worker if (RetValNum != -1U) {
366*9880d681SAndroid Build Coastguard Worker RetOrArg Use = CreateRet(F, RetValNum);
367*9880d681SAndroid Build Coastguard Worker // We might be live, depending on the liveness of Use.
368*9880d681SAndroid Build Coastguard Worker return MarkIfNotLive(Use, MaybeLiveUses);
369*9880d681SAndroid Build Coastguard Worker } else {
370*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass::Liveness Result = MaybeLive;
371*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i < NumRetVals(F); ++i) {
372*9880d681SAndroid Build Coastguard Worker RetOrArg Use = CreateRet(F, i);
373*9880d681SAndroid Build Coastguard Worker // We might be live, depending on the liveness of Use. If any
374*9880d681SAndroid Build Coastguard Worker // sub-value is live, then the entire value is considered live. This
375*9880d681SAndroid Build Coastguard Worker // is a conservative choice, and better tracking is possible.
376*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass::Liveness SubResult =
377*9880d681SAndroid Build Coastguard Worker MarkIfNotLive(Use, MaybeLiveUses);
378*9880d681SAndroid Build Coastguard Worker if (Result != Live)
379*9880d681SAndroid Build Coastguard Worker Result = SubResult;
380*9880d681SAndroid Build Coastguard Worker }
381*9880d681SAndroid Build Coastguard Worker return Result;
382*9880d681SAndroid Build Coastguard Worker }
383*9880d681SAndroid Build Coastguard Worker }
384*9880d681SAndroid Build Coastguard Worker if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
385*9880d681SAndroid Build Coastguard Worker if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex()
386*9880d681SAndroid Build Coastguard Worker && IV->hasIndices())
387*9880d681SAndroid Build Coastguard Worker // The use we are examining is inserted into an aggregate. Our liveness
388*9880d681SAndroid Build Coastguard Worker // depends on all uses of that aggregate, but if it is used as a return
389*9880d681SAndroid Build Coastguard Worker // value, only index at which we were inserted counts.
390*9880d681SAndroid Build Coastguard Worker RetValNum = *IV->idx_begin();
391*9880d681SAndroid Build Coastguard Worker
392*9880d681SAndroid Build Coastguard Worker // Note that if we are used as the aggregate operand to the insertvalue,
393*9880d681SAndroid Build Coastguard Worker // we don't change RetValNum, but do survey all our uses.
394*9880d681SAndroid Build Coastguard Worker
395*9880d681SAndroid Build Coastguard Worker Liveness Result = MaybeLive;
396*9880d681SAndroid Build Coastguard Worker for (const Use &UU : IV->uses()) {
397*9880d681SAndroid Build Coastguard Worker Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
398*9880d681SAndroid Build Coastguard Worker if (Result == Live)
399*9880d681SAndroid Build Coastguard Worker break;
400*9880d681SAndroid Build Coastguard Worker }
401*9880d681SAndroid Build Coastguard Worker return Result;
402*9880d681SAndroid Build Coastguard Worker }
403*9880d681SAndroid Build Coastguard Worker
404*9880d681SAndroid Build Coastguard Worker if (auto CS = ImmutableCallSite(V)) {
405*9880d681SAndroid Build Coastguard Worker const Function *F = CS.getCalledFunction();
406*9880d681SAndroid Build Coastguard Worker if (F) {
407*9880d681SAndroid Build Coastguard Worker // Used in a direct call.
408*9880d681SAndroid Build Coastguard Worker
409*9880d681SAndroid Build Coastguard Worker // The function argument is live if it is used as a bundle operand.
410*9880d681SAndroid Build Coastguard Worker if (CS.isBundleOperand(U))
411*9880d681SAndroid Build Coastguard Worker return Live;
412*9880d681SAndroid Build Coastguard Worker
413*9880d681SAndroid Build Coastguard Worker // Find the argument number. We know for sure that this use is an
414*9880d681SAndroid Build Coastguard Worker // argument, since if it was the function argument this would be an
415*9880d681SAndroid Build Coastguard Worker // indirect call and the we know can't be looking at a value of the
416*9880d681SAndroid Build Coastguard Worker // label type (for the invoke instruction).
417*9880d681SAndroid Build Coastguard Worker unsigned ArgNo = CS.getArgumentNo(U);
418*9880d681SAndroid Build Coastguard Worker
419*9880d681SAndroid Build Coastguard Worker if (ArgNo >= F->getFunctionType()->getNumParams())
420*9880d681SAndroid Build Coastguard Worker // The value is passed in through a vararg! Must be live.
421*9880d681SAndroid Build Coastguard Worker return Live;
422*9880d681SAndroid Build Coastguard Worker
423*9880d681SAndroid Build Coastguard Worker assert(CS.getArgument(ArgNo)
424*9880d681SAndroid Build Coastguard Worker == CS->getOperand(U->getOperandNo())
425*9880d681SAndroid Build Coastguard Worker && "Argument is not where we expected it");
426*9880d681SAndroid Build Coastguard Worker
427*9880d681SAndroid Build Coastguard Worker // Value passed to a normal call. It's only live when the corresponding
428*9880d681SAndroid Build Coastguard Worker // argument to the called function turns out live.
429*9880d681SAndroid Build Coastguard Worker RetOrArg Use = CreateArg(F, ArgNo);
430*9880d681SAndroid Build Coastguard Worker return MarkIfNotLive(Use, MaybeLiveUses);
431*9880d681SAndroid Build Coastguard Worker }
432*9880d681SAndroid Build Coastguard Worker }
433*9880d681SAndroid Build Coastguard Worker // Used in any other way? Value must be live.
434*9880d681SAndroid Build Coastguard Worker return Live;
435*9880d681SAndroid Build Coastguard Worker }
436*9880d681SAndroid Build Coastguard Worker
437*9880d681SAndroid Build Coastguard Worker /// SurveyUses - This looks at all the uses of the given value
438*9880d681SAndroid Build Coastguard Worker /// Returns the Liveness deduced from the uses of this value.
439*9880d681SAndroid Build Coastguard Worker ///
440*9880d681SAndroid Build Coastguard Worker /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
441*9880d681SAndroid Build Coastguard Worker /// the result is Live, MaybeLiveUses might be modified but its content should
442*9880d681SAndroid Build Coastguard Worker /// be ignored (since it might not be complete).
443*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass::Liveness
SurveyUses(const Value * V,UseVector & MaybeLiveUses)444*9880d681SAndroid Build Coastguard Worker DeadArgumentEliminationPass::SurveyUses(const Value *V,
445*9880d681SAndroid Build Coastguard Worker UseVector &MaybeLiveUses) {
446*9880d681SAndroid Build Coastguard Worker // Assume it's dead (which will only hold if there are no uses at all..).
447*9880d681SAndroid Build Coastguard Worker Liveness Result = MaybeLive;
448*9880d681SAndroid Build Coastguard Worker // Check each use.
449*9880d681SAndroid Build Coastguard Worker for (const Use &U : V->uses()) {
450*9880d681SAndroid Build Coastguard Worker Result = SurveyUse(&U, MaybeLiveUses);
451*9880d681SAndroid Build Coastguard Worker if (Result == Live)
452*9880d681SAndroid Build Coastguard Worker break;
453*9880d681SAndroid Build Coastguard Worker }
454*9880d681SAndroid Build Coastguard Worker return Result;
455*9880d681SAndroid Build Coastguard Worker }
456*9880d681SAndroid Build Coastguard Worker
457*9880d681SAndroid Build Coastguard Worker // SurveyFunction - This performs the initial survey of the specified function,
458*9880d681SAndroid Build Coastguard Worker // checking out whether or not it uses any of its incoming arguments or whether
459*9880d681SAndroid Build Coastguard Worker // any callers use the return value. This fills in the LiveValues set and Uses
460*9880d681SAndroid Build Coastguard Worker // map.
461*9880d681SAndroid Build Coastguard Worker //
462*9880d681SAndroid Build Coastguard Worker // We consider arguments of non-internal functions to be intrinsically alive as
463*9880d681SAndroid Build Coastguard Worker // well as arguments to functions which have their "address taken".
464*9880d681SAndroid Build Coastguard Worker //
SurveyFunction(const Function & F)465*9880d681SAndroid Build Coastguard Worker void DeadArgumentEliminationPass::SurveyFunction(const Function &F) {
466*9880d681SAndroid Build Coastguard Worker // Functions with inalloca parameters are expecting args in a particular
467*9880d681SAndroid Build Coastguard Worker // register and memory layout.
468*9880d681SAndroid Build Coastguard Worker if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) {
469*9880d681SAndroid Build Coastguard Worker MarkLive(F);
470*9880d681SAndroid Build Coastguard Worker return;
471*9880d681SAndroid Build Coastguard Worker }
472*9880d681SAndroid Build Coastguard Worker
473*9880d681SAndroid Build Coastguard Worker // Don't touch naked functions. The assembly might be using an argument, or
474*9880d681SAndroid Build Coastguard Worker // otherwise rely on the frame layout in a way that this analysis will not
475*9880d681SAndroid Build Coastguard Worker // see.
476*9880d681SAndroid Build Coastguard Worker if (F.hasFnAttribute(Attribute::Naked)) {
477*9880d681SAndroid Build Coastguard Worker MarkLive(F);
478*9880d681SAndroid Build Coastguard Worker return;
479*9880d681SAndroid Build Coastguard Worker }
480*9880d681SAndroid Build Coastguard Worker
481*9880d681SAndroid Build Coastguard Worker unsigned RetCount = NumRetVals(&F);
482*9880d681SAndroid Build Coastguard Worker // Assume all return values are dead
483*9880d681SAndroid Build Coastguard Worker typedef SmallVector<Liveness, 5> RetVals;
484*9880d681SAndroid Build Coastguard Worker RetVals RetValLiveness(RetCount, MaybeLive);
485*9880d681SAndroid Build Coastguard Worker
486*9880d681SAndroid Build Coastguard Worker typedef SmallVector<UseVector, 5> RetUses;
487*9880d681SAndroid Build Coastguard Worker // These vectors map each return value to the uses that make it MaybeLive, so
488*9880d681SAndroid Build Coastguard Worker // we can add those to the Uses map if the return value really turns out to be
489*9880d681SAndroid Build Coastguard Worker // MaybeLive. Initialized to a list of RetCount empty lists.
490*9880d681SAndroid Build Coastguard Worker RetUses MaybeLiveRetUses(RetCount);
491*9880d681SAndroid Build Coastguard Worker
492*9880d681SAndroid Build Coastguard Worker for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
493*9880d681SAndroid Build Coastguard Worker if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
494*9880d681SAndroid Build Coastguard Worker if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
495*9880d681SAndroid Build Coastguard Worker != F.getFunctionType()->getReturnType()) {
496*9880d681SAndroid Build Coastguard Worker // We don't support old style multiple return values.
497*9880d681SAndroid Build Coastguard Worker MarkLive(F);
498*9880d681SAndroid Build Coastguard Worker return;
499*9880d681SAndroid Build Coastguard Worker }
500*9880d681SAndroid Build Coastguard Worker
501*9880d681SAndroid Build Coastguard Worker if (!F.hasLocalLinkage() && (!ShouldHackArguments || F.isIntrinsic())) {
502*9880d681SAndroid Build Coastguard Worker MarkLive(F);
503*9880d681SAndroid Build Coastguard Worker return;
504*9880d681SAndroid Build Coastguard Worker }
505*9880d681SAndroid Build Coastguard Worker
506*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "DeadArgumentEliminationPass - Inspecting callers for fn: "
507*9880d681SAndroid Build Coastguard Worker << F.getName() << "\n");
508*9880d681SAndroid Build Coastguard Worker // Keep track of the number of live retvals, so we can skip checks once all
509*9880d681SAndroid Build Coastguard Worker // of them turn out to be live.
510*9880d681SAndroid Build Coastguard Worker unsigned NumLiveRetVals = 0;
511*9880d681SAndroid Build Coastguard Worker // Loop all uses of the function.
512*9880d681SAndroid Build Coastguard Worker for (const Use &U : F.uses()) {
513*9880d681SAndroid Build Coastguard Worker // If the function is PASSED IN as an argument, its address has been
514*9880d681SAndroid Build Coastguard Worker // taken.
515*9880d681SAndroid Build Coastguard Worker ImmutableCallSite CS(U.getUser());
516*9880d681SAndroid Build Coastguard Worker if (!CS || !CS.isCallee(&U)) {
517*9880d681SAndroid Build Coastguard Worker MarkLive(F);
518*9880d681SAndroid Build Coastguard Worker return;
519*9880d681SAndroid Build Coastguard Worker }
520*9880d681SAndroid Build Coastguard Worker
521*9880d681SAndroid Build Coastguard Worker // If this use is anything other than a call site, the function is alive.
522*9880d681SAndroid Build Coastguard Worker const Instruction *TheCall = CS.getInstruction();
523*9880d681SAndroid Build Coastguard Worker if (!TheCall) { // Not a direct call site?
524*9880d681SAndroid Build Coastguard Worker MarkLive(F);
525*9880d681SAndroid Build Coastguard Worker return;
526*9880d681SAndroid Build Coastguard Worker }
527*9880d681SAndroid Build Coastguard Worker
528*9880d681SAndroid Build Coastguard Worker // If we end up here, we are looking at a direct call to our function.
529*9880d681SAndroid Build Coastguard Worker
530*9880d681SAndroid Build Coastguard Worker // Now, check how our return value(s) is/are used in this caller. Don't
531*9880d681SAndroid Build Coastguard Worker // bother checking return values if all of them are live already.
532*9880d681SAndroid Build Coastguard Worker if (NumLiveRetVals == RetCount)
533*9880d681SAndroid Build Coastguard Worker continue;
534*9880d681SAndroid Build Coastguard Worker
535*9880d681SAndroid Build Coastguard Worker // Check all uses of the return value.
536*9880d681SAndroid Build Coastguard Worker for (const Use &U : TheCall->uses()) {
537*9880d681SAndroid Build Coastguard Worker if (ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U.getUser())) {
538*9880d681SAndroid Build Coastguard Worker // This use uses a part of our return value, survey the uses of
539*9880d681SAndroid Build Coastguard Worker // that part and store the results for this index only.
540*9880d681SAndroid Build Coastguard Worker unsigned Idx = *Ext->idx_begin();
541*9880d681SAndroid Build Coastguard Worker if (RetValLiveness[Idx] != Live) {
542*9880d681SAndroid Build Coastguard Worker RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
543*9880d681SAndroid Build Coastguard Worker if (RetValLiveness[Idx] == Live)
544*9880d681SAndroid Build Coastguard Worker NumLiveRetVals++;
545*9880d681SAndroid Build Coastguard Worker }
546*9880d681SAndroid Build Coastguard Worker } else {
547*9880d681SAndroid Build Coastguard Worker // Used by something else than extractvalue. Survey, but assume that the
548*9880d681SAndroid Build Coastguard Worker // result applies to all sub-values.
549*9880d681SAndroid Build Coastguard Worker UseVector MaybeLiveAggregateUses;
550*9880d681SAndroid Build Coastguard Worker if (SurveyUse(&U, MaybeLiveAggregateUses) == Live) {
551*9880d681SAndroid Build Coastguard Worker NumLiveRetVals = RetCount;
552*9880d681SAndroid Build Coastguard Worker RetValLiveness.assign(RetCount, Live);
553*9880d681SAndroid Build Coastguard Worker break;
554*9880d681SAndroid Build Coastguard Worker } else {
555*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != RetCount; ++i) {
556*9880d681SAndroid Build Coastguard Worker if (RetValLiveness[i] != Live)
557*9880d681SAndroid Build Coastguard Worker MaybeLiveRetUses[i].append(MaybeLiveAggregateUses.begin(),
558*9880d681SAndroid Build Coastguard Worker MaybeLiveAggregateUses.end());
559*9880d681SAndroid Build Coastguard Worker }
560*9880d681SAndroid Build Coastguard Worker }
561*9880d681SAndroid Build Coastguard Worker }
562*9880d681SAndroid Build Coastguard Worker }
563*9880d681SAndroid Build Coastguard Worker }
564*9880d681SAndroid Build Coastguard Worker
565*9880d681SAndroid Build Coastguard Worker // Now we've inspected all callers, record the liveness of our return values.
566*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != RetCount; ++i)
567*9880d681SAndroid Build Coastguard Worker MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
568*9880d681SAndroid Build Coastguard Worker
569*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "DeadArgumentEliminationPass - Inspecting args for fn: "
570*9880d681SAndroid Build Coastguard Worker << F.getName() << "\n");
571*9880d681SAndroid Build Coastguard Worker
572*9880d681SAndroid Build Coastguard Worker // Now, check all of our arguments.
573*9880d681SAndroid Build Coastguard Worker unsigned i = 0;
574*9880d681SAndroid Build Coastguard Worker UseVector MaybeLiveArgUses;
575*9880d681SAndroid Build Coastguard Worker for (Function::const_arg_iterator AI = F.arg_begin(),
576*9880d681SAndroid Build Coastguard Worker E = F.arg_end(); AI != E; ++AI, ++i) {
577*9880d681SAndroid Build Coastguard Worker Liveness Result;
578*9880d681SAndroid Build Coastguard Worker if (F.getFunctionType()->isVarArg()) {
579*9880d681SAndroid Build Coastguard Worker // Variadic functions will already have a va_arg function expanded inside
580*9880d681SAndroid Build Coastguard Worker // them, making them potentially very sensitive to ABI changes resulting
581*9880d681SAndroid Build Coastguard Worker // from removing arguments entirely, so don't. For example AArch64 handles
582*9880d681SAndroid Build Coastguard Worker // register and stack HFAs very differently, and this is reflected in the
583*9880d681SAndroid Build Coastguard Worker // IR which has already been generated.
584*9880d681SAndroid Build Coastguard Worker Result = Live;
585*9880d681SAndroid Build Coastguard Worker } else {
586*9880d681SAndroid Build Coastguard Worker // See what the effect of this use is (recording any uses that cause
587*9880d681SAndroid Build Coastguard Worker // MaybeLive in MaybeLiveArgUses).
588*9880d681SAndroid Build Coastguard Worker Result = SurveyUses(&*AI, MaybeLiveArgUses);
589*9880d681SAndroid Build Coastguard Worker }
590*9880d681SAndroid Build Coastguard Worker
591*9880d681SAndroid Build Coastguard Worker // Mark the result.
592*9880d681SAndroid Build Coastguard Worker MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
593*9880d681SAndroid Build Coastguard Worker // Clear the vector again for the next iteration.
594*9880d681SAndroid Build Coastguard Worker MaybeLiveArgUses.clear();
595*9880d681SAndroid Build Coastguard Worker }
596*9880d681SAndroid Build Coastguard Worker }
597*9880d681SAndroid Build Coastguard Worker
598*9880d681SAndroid Build Coastguard Worker /// MarkValue - This function marks the liveness of RA depending on L. If L is
599*9880d681SAndroid Build Coastguard Worker /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
600*9880d681SAndroid Build Coastguard Worker /// such that RA will be marked live if any use in MaybeLiveUses gets marked
601*9880d681SAndroid Build Coastguard Worker /// live later on.
MarkValue(const RetOrArg & RA,Liveness L,const UseVector & MaybeLiveUses)602*9880d681SAndroid Build Coastguard Worker void DeadArgumentEliminationPass::MarkValue(const RetOrArg &RA, Liveness L,
603*9880d681SAndroid Build Coastguard Worker const UseVector &MaybeLiveUses) {
604*9880d681SAndroid Build Coastguard Worker switch (L) {
605*9880d681SAndroid Build Coastguard Worker case Live: MarkLive(RA); break;
606*9880d681SAndroid Build Coastguard Worker case MaybeLive:
607*9880d681SAndroid Build Coastguard Worker {
608*9880d681SAndroid Build Coastguard Worker // Note any uses of this value, so this return value can be
609*9880d681SAndroid Build Coastguard Worker // marked live whenever one of the uses becomes live.
610*9880d681SAndroid Build Coastguard Worker for (const auto &MaybeLiveUse : MaybeLiveUses)
611*9880d681SAndroid Build Coastguard Worker Uses.insert(std::make_pair(MaybeLiveUse, RA));
612*9880d681SAndroid Build Coastguard Worker break;
613*9880d681SAndroid Build Coastguard Worker }
614*9880d681SAndroid Build Coastguard Worker }
615*9880d681SAndroid Build Coastguard Worker }
616*9880d681SAndroid Build Coastguard Worker
617*9880d681SAndroid Build Coastguard Worker /// MarkLive - Mark the given Function as alive, meaning that it cannot be
618*9880d681SAndroid Build Coastguard Worker /// changed in any way. Additionally,
619*9880d681SAndroid Build Coastguard Worker /// mark any values that are used as this function's parameters or by its return
620*9880d681SAndroid Build Coastguard Worker /// values (according to Uses) live as well.
MarkLive(const Function & F)621*9880d681SAndroid Build Coastguard Worker void DeadArgumentEliminationPass::MarkLive(const Function &F) {
622*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "DeadArgumentEliminationPass - Intrinsically live fn: "
623*9880d681SAndroid Build Coastguard Worker << F.getName() << "\n");
624*9880d681SAndroid Build Coastguard Worker // Mark the function as live.
625*9880d681SAndroid Build Coastguard Worker LiveFunctions.insert(&F);
626*9880d681SAndroid Build Coastguard Worker // Mark all arguments as live.
627*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
628*9880d681SAndroid Build Coastguard Worker PropagateLiveness(CreateArg(&F, i));
629*9880d681SAndroid Build Coastguard Worker // Mark all return values as live.
630*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
631*9880d681SAndroid Build Coastguard Worker PropagateLiveness(CreateRet(&F, i));
632*9880d681SAndroid Build Coastguard Worker }
633*9880d681SAndroid Build Coastguard Worker
634*9880d681SAndroid Build Coastguard Worker /// MarkLive - Mark the given return value or argument as live. Additionally,
635*9880d681SAndroid Build Coastguard Worker /// mark any values that are used by this value (according to Uses) live as
636*9880d681SAndroid Build Coastguard Worker /// well.
MarkLive(const RetOrArg & RA)637*9880d681SAndroid Build Coastguard Worker void DeadArgumentEliminationPass::MarkLive(const RetOrArg &RA) {
638*9880d681SAndroid Build Coastguard Worker if (LiveFunctions.count(RA.F))
639*9880d681SAndroid Build Coastguard Worker return; // Function was already marked Live.
640*9880d681SAndroid Build Coastguard Worker
641*9880d681SAndroid Build Coastguard Worker if (!LiveValues.insert(RA).second)
642*9880d681SAndroid Build Coastguard Worker return; // We were already marked Live.
643*9880d681SAndroid Build Coastguard Worker
644*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "DeadArgumentEliminationPass - Marking "
645*9880d681SAndroid Build Coastguard Worker << RA.getDescription() << " live\n");
646*9880d681SAndroid Build Coastguard Worker PropagateLiveness(RA);
647*9880d681SAndroid Build Coastguard Worker }
648*9880d681SAndroid Build Coastguard Worker
649*9880d681SAndroid Build Coastguard Worker /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
650*9880d681SAndroid Build Coastguard Worker /// to any other values it uses (according to Uses).
PropagateLiveness(const RetOrArg & RA)651*9880d681SAndroid Build Coastguard Worker void DeadArgumentEliminationPass::PropagateLiveness(const RetOrArg &RA) {
652*9880d681SAndroid Build Coastguard Worker // We don't use upper_bound (or equal_range) here, because our recursive call
653*9880d681SAndroid Build Coastguard Worker // to ourselves is likely to cause the upper_bound (which is the first value
654*9880d681SAndroid Build Coastguard Worker // not belonging to RA) to become erased and the iterator invalidated.
655*9880d681SAndroid Build Coastguard Worker UseMap::iterator Begin = Uses.lower_bound(RA);
656*9880d681SAndroid Build Coastguard Worker UseMap::iterator E = Uses.end();
657*9880d681SAndroid Build Coastguard Worker UseMap::iterator I;
658*9880d681SAndroid Build Coastguard Worker for (I = Begin; I != E && I->first == RA; ++I)
659*9880d681SAndroid Build Coastguard Worker MarkLive(I->second);
660*9880d681SAndroid Build Coastguard Worker
661*9880d681SAndroid Build Coastguard Worker // Erase RA from the Uses map (from the lower bound to wherever we ended up
662*9880d681SAndroid Build Coastguard Worker // after the loop).
663*9880d681SAndroid Build Coastguard Worker Uses.erase(Begin, I);
664*9880d681SAndroid Build Coastguard Worker }
665*9880d681SAndroid Build Coastguard Worker
666*9880d681SAndroid Build Coastguard Worker // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
667*9880d681SAndroid Build Coastguard Worker // that are not in LiveValues. Transform the function and all of the callees of
668*9880d681SAndroid Build Coastguard Worker // the function to not have these arguments and return values.
669*9880d681SAndroid Build Coastguard Worker //
RemoveDeadStuffFromFunction(Function * F)670*9880d681SAndroid Build Coastguard Worker bool DeadArgumentEliminationPass::RemoveDeadStuffFromFunction(Function *F) {
671*9880d681SAndroid Build Coastguard Worker // Don't modify fully live functions
672*9880d681SAndroid Build Coastguard Worker if (LiveFunctions.count(F))
673*9880d681SAndroid Build Coastguard Worker return false;
674*9880d681SAndroid Build Coastguard Worker
675*9880d681SAndroid Build Coastguard Worker // Start by computing a new prototype for the function, which is the same as
676*9880d681SAndroid Build Coastguard Worker // the old function, but has fewer arguments and a different return type.
677*9880d681SAndroid Build Coastguard Worker FunctionType *FTy = F->getFunctionType();
678*9880d681SAndroid Build Coastguard Worker std::vector<Type*> Params;
679*9880d681SAndroid Build Coastguard Worker
680*9880d681SAndroid Build Coastguard Worker // Keep track of if we have a live 'returned' argument
681*9880d681SAndroid Build Coastguard Worker bool HasLiveReturnedArg = false;
682*9880d681SAndroid Build Coastguard Worker
683*9880d681SAndroid Build Coastguard Worker // Set up to build a new list of parameter attributes.
684*9880d681SAndroid Build Coastguard Worker SmallVector<AttributeSet, 8> AttributesVec;
685*9880d681SAndroid Build Coastguard Worker const AttributeSet &PAL = F->getAttributes();
686*9880d681SAndroid Build Coastguard Worker
687*9880d681SAndroid Build Coastguard Worker // Remember which arguments are still alive.
688*9880d681SAndroid Build Coastguard Worker SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
689*9880d681SAndroid Build Coastguard Worker // Construct the new parameter list from non-dead arguments. Also construct
690*9880d681SAndroid Build Coastguard Worker // a new set of parameter attributes to correspond. Skip the first parameter
691*9880d681SAndroid Build Coastguard Worker // attribute, since that belongs to the return value.
692*9880d681SAndroid Build Coastguard Worker unsigned i = 0;
693*9880d681SAndroid Build Coastguard Worker for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
694*9880d681SAndroid Build Coastguard Worker I != E; ++I, ++i) {
695*9880d681SAndroid Build Coastguard Worker RetOrArg Arg = CreateArg(F, i);
696*9880d681SAndroid Build Coastguard Worker if (LiveValues.erase(Arg)) {
697*9880d681SAndroid Build Coastguard Worker Params.push_back(I->getType());
698*9880d681SAndroid Build Coastguard Worker ArgAlive[i] = true;
699*9880d681SAndroid Build Coastguard Worker
700*9880d681SAndroid Build Coastguard Worker // Get the original parameter attributes (skipping the first one, that is
701*9880d681SAndroid Build Coastguard Worker // for the return value.
702*9880d681SAndroid Build Coastguard Worker if (PAL.hasAttributes(i + 1)) {
703*9880d681SAndroid Build Coastguard Worker AttrBuilder B(PAL, i + 1);
704*9880d681SAndroid Build Coastguard Worker if (B.contains(Attribute::Returned))
705*9880d681SAndroid Build Coastguard Worker HasLiveReturnedArg = true;
706*9880d681SAndroid Build Coastguard Worker AttributesVec.
707*9880d681SAndroid Build Coastguard Worker push_back(AttributeSet::get(F->getContext(), Params.size(), B));
708*9880d681SAndroid Build Coastguard Worker }
709*9880d681SAndroid Build Coastguard Worker } else {
710*9880d681SAndroid Build Coastguard Worker ++NumArgumentsEliminated;
711*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "DeadArgumentEliminationPass - Removing argument " << i
712*9880d681SAndroid Build Coastguard Worker << " (" << I->getName() << ") from " << F->getName()
713*9880d681SAndroid Build Coastguard Worker << "\n");
714*9880d681SAndroid Build Coastguard Worker }
715*9880d681SAndroid Build Coastguard Worker }
716*9880d681SAndroid Build Coastguard Worker
717*9880d681SAndroid Build Coastguard Worker // Find out the new return value.
718*9880d681SAndroid Build Coastguard Worker Type *RetTy = FTy->getReturnType();
719*9880d681SAndroid Build Coastguard Worker Type *NRetTy = nullptr;
720*9880d681SAndroid Build Coastguard Worker unsigned RetCount = NumRetVals(F);
721*9880d681SAndroid Build Coastguard Worker
722*9880d681SAndroid Build Coastguard Worker // -1 means unused, other numbers are the new index
723*9880d681SAndroid Build Coastguard Worker SmallVector<int, 5> NewRetIdxs(RetCount, -1);
724*9880d681SAndroid Build Coastguard Worker std::vector<Type*> RetTypes;
725*9880d681SAndroid Build Coastguard Worker
726*9880d681SAndroid Build Coastguard Worker // If there is a function with a live 'returned' argument but a dead return
727*9880d681SAndroid Build Coastguard Worker // value, then there are two possible actions:
728*9880d681SAndroid Build Coastguard Worker // 1) Eliminate the return value and take off the 'returned' attribute on the
729*9880d681SAndroid Build Coastguard Worker // argument.
730*9880d681SAndroid Build Coastguard Worker // 2) Retain the 'returned' attribute and treat the return value (but not the
731*9880d681SAndroid Build Coastguard Worker // entire function) as live so that it is not eliminated.
732*9880d681SAndroid Build Coastguard Worker //
733*9880d681SAndroid Build Coastguard Worker // It's not clear in the general case which option is more profitable because,
734*9880d681SAndroid Build Coastguard Worker // even in the absence of explicit uses of the return value, code generation
735*9880d681SAndroid Build Coastguard Worker // is free to use the 'returned' attribute to do things like eliding
736*9880d681SAndroid Build Coastguard Worker // save/restores of registers across calls. Whether or not this happens is
737*9880d681SAndroid Build Coastguard Worker // target and ABI-specific as well as depending on the amount of register
738*9880d681SAndroid Build Coastguard Worker // pressure, so there's no good way for an IR-level pass to figure this out.
739*9880d681SAndroid Build Coastguard Worker //
740*9880d681SAndroid Build Coastguard Worker // Fortunately, the only places where 'returned' is currently generated by
741*9880d681SAndroid Build Coastguard Worker // the FE are places where 'returned' is basically free and almost always a
742*9880d681SAndroid Build Coastguard Worker // performance win, so the second option can just be used always for now.
743*9880d681SAndroid Build Coastguard Worker //
744*9880d681SAndroid Build Coastguard Worker // This should be revisited if 'returned' is ever applied more liberally.
745*9880d681SAndroid Build Coastguard Worker if (RetTy->isVoidTy() || HasLiveReturnedArg) {
746*9880d681SAndroid Build Coastguard Worker NRetTy = RetTy;
747*9880d681SAndroid Build Coastguard Worker } else {
748*9880d681SAndroid Build Coastguard Worker // Look at each of the original return values individually.
749*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != RetCount; ++i) {
750*9880d681SAndroid Build Coastguard Worker RetOrArg Ret = CreateRet(F, i);
751*9880d681SAndroid Build Coastguard Worker if (LiveValues.erase(Ret)) {
752*9880d681SAndroid Build Coastguard Worker RetTypes.push_back(getRetComponentType(F, i));
753*9880d681SAndroid Build Coastguard Worker NewRetIdxs[i] = RetTypes.size() - 1;
754*9880d681SAndroid Build Coastguard Worker } else {
755*9880d681SAndroid Build Coastguard Worker ++NumRetValsEliminated;
756*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "DeadArgumentEliminationPass - Removing return value "
757*9880d681SAndroid Build Coastguard Worker << i << " from " << F->getName() << "\n");
758*9880d681SAndroid Build Coastguard Worker }
759*9880d681SAndroid Build Coastguard Worker }
760*9880d681SAndroid Build Coastguard Worker if (RetTypes.size() > 1) {
761*9880d681SAndroid Build Coastguard Worker // More than one return type? Reduce it down to size.
762*9880d681SAndroid Build Coastguard Worker if (StructType *STy = dyn_cast<StructType>(RetTy)) {
763*9880d681SAndroid Build Coastguard Worker // Make the new struct packed if we used to return a packed struct
764*9880d681SAndroid Build Coastguard Worker // already.
765*9880d681SAndroid Build Coastguard Worker NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
766*9880d681SAndroid Build Coastguard Worker } else {
767*9880d681SAndroid Build Coastguard Worker assert(isa<ArrayType>(RetTy) && "unexpected multi-value return");
768*9880d681SAndroid Build Coastguard Worker NRetTy = ArrayType::get(RetTypes[0], RetTypes.size());
769*9880d681SAndroid Build Coastguard Worker }
770*9880d681SAndroid Build Coastguard Worker } else if (RetTypes.size() == 1)
771*9880d681SAndroid Build Coastguard Worker // One return type? Just a simple value then, but only if we didn't use to
772*9880d681SAndroid Build Coastguard Worker // return a struct with that simple value before.
773*9880d681SAndroid Build Coastguard Worker NRetTy = RetTypes.front();
774*9880d681SAndroid Build Coastguard Worker else if (RetTypes.size() == 0)
775*9880d681SAndroid Build Coastguard Worker // No return types? Make it void, but only if we didn't use to return {}.
776*9880d681SAndroid Build Coastguard Worker NRetTy = Type::getVoidTy(F->getContext());
777*9880d681SAndroid Build Coastguard Worker }
778*9880d681SAndroid Build Coastguard Worker
779*9880d681SAndroid Build Coastguard Worker assert(NRetTy && "No new return type found?");
780*9880d681SAndroid Build Coastguard Worker
781*9880d681SAndroid Build Coastguard Worker // The existing function return attributes.
782*9880d681SAndroid Build Coastguard Worker AttributeSet RAttrs = PAL.getRetAttributes();
783*9880d681SAndroid Build Coastguard Worker
784*9880d681SAndroid Build Coastguard Worker // Remove any incompatible attributes, but only if we removed all return
785*9880d681SAndroid Build Coastguard Worker // values. Otherwise, ensure that we don't have any conflicting attributes
786*9880d681SAndroid Build Coastguard Worker // here. Currently, this should not be possible, but special handling might be
787*9880d681SAndroid Build Coastguard Worker // required when new return value attributes are added.
788*9880d681SAndroid Build Coastguard Worker if (NRetTy->isVoidTy())
789*9880d681SAndroid Build Coastguard Worker RAttrs = RAttrs.removeAttributes(NRetTy->getContext(),
790*9880d681SAndroid Build Coastguard Worker AttributeSet::ReturnIndex,
791*9880d681SAndroid Build Coastguard Worker AttributeFuncs::typeIncompatible(NRetTy));
792*9880d681SAndroid Build Coastguard Worker else
793*9880d681SAndroid Build Coastguard Worker assert(!AttrBuilder(RAttrs, AttributeSet::ReturnIndex).
794*9880d681SAndroid Build Coastguard Worker overlaps(AttributeFuncs::typeIncompatible(NRetTy)) &&
795*9880d681SAndroid Build Coastguard Worker "Return attributes no longer compatible?");
796*9880d681SAndroid Build Coastguard Worker
797*9880d681SAndroid Build Coastguard Worker if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
798*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(NRetTy->getContext(), RAttrs));
799*9880d681SAndroid Build Coastguard Worker
800*9880d681SAndroid Build Coastguard Worker if (PAL.hasAttributes(AttributeSet::FunctionIndex))
801*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(F->getContext(),
802*9880d681SAndroid Build Coastguard Worker PAL.getFnAttributes()));
803*9880d681SAndroid Build Coastguard Worker
804*9880d681SAndroid Build Coastguard Worker // Reconstruct the AttributesList based on the vector we constructed.
805*9880d681SAndroid Build Coastguard Worker AttributeSet NewPAL = AttributeSet::get(F->getContext(), AttributesVec);
806*9880d681SAndroid Build Coastguard Worker
807*9880d681SAndroid Build Coastguard Worker // Create the new function type based on the recomputed parameters.
808*9880d681SAndroid Build Coastguard Worker FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
809*9880d681SAndroid Build Coastguard Worker
810*9880d681SAndroid Build Coastguard Worker // No change?
811*9880d681SAndroid Build Coastguard Worker if (NFTy == FTy)
812*9880d681SAndroid Build Coastguard Worker return false;
813*9880d681SAndroid Build Coastguard Worker
814*9880d681SAndroid Build Coastguard Worker // Create the new function body and insert it into the module...
815*9880d681SAndroid Build Coastguard Worker Function *NF = Function::Create(NFTy, F->getLinkage());
816*9880d681SAndroid Build Coastguard Worker NF->copyAttributesFrom(F);
817*9880d681SAndroid Build Coastguard Worker NF->setComdat(F->getComdat());
818*9880d681SAndroid Build Coastguard Worker NF->setAttributes(NewPAL);
819*9880d681SAndroid Build Coastguard Worker // Insert the new function before the old function, so we won't be processing
820*9880d681SAndroid Build Coastguard Worker // it again.
821*9880d681SAndroid Build Coastguard Worker F->getParent()->getFunctionList().insert(F->getIterator(), NF);
822*9880d681SAndroid Build Coastguard Worker NF->takeName(F);
823*9880d681SAndroid Build Coastguard Worker
824*9880d681SAndroid Build Coastguard Worker // Loop over all of the callers of the function, transforming the call sites
825*9880d681SAndroid Build Coastguard Worker // to pass in a smaller number of arguments into the new function.
826*9880d681SAndroid Build Coastguard Worker //
827*9880d681SAndroid Build Coastguard Worker std::vector<Value*> Args;
828*9880d681SAndroid Build Coastguard Worker while (!F->use_empty()) {
829*9880d681SAndroid Build Coastguard Worker CallSite CS(F->user_back());
830*9880d681SAndroid Build Coastguard Worker Instruction *Call = CS.getInstruction();
831*9880d681SAndroid Build Coastguard Worker
832*9880d681SAndroid Build Coastguard Worker AttributesVec.clear();
833*9880d681SAndroid Build Coastguard Worker const AttributeSet &CallPAL = CS.getAttributes();
834*9880d681SAndroid Build Coastguard Worker
835*9880d681SAndroid Build Coastguard Worker // The call return attributes.
836*9880d681SAndroid Build Coastguard Worker AttributeSet RAttrs = CallPAL.getRetAttributes();
837*9880d681SAndroid Build Coastguard Worker
838*9880d681SAndroid Build Coastguard Worker // Adjust in case the function was changed to return void.
839*9880d681SAndroid Build Coastguard Worker RAttrs = RAttrs.removeAttributes(NRetTy->getContext(),
840*9880d681SAndroid Build Coastguard Worker AttributeSet::ReturnIndex,
841*9880d681SAndroid Build Coastguard Worker AttributeFuncs::typeIncompatible(NF->getReturnType()));
842*9880d681SAndroid Build Coastguard Worker if (RAttrs.hasAttributes(AttributeSet::ReturnIndex))
843*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(NF->getContext(), RAttrs));
844*9880d681SAndroid Build Coastguard Worker
845*9880d681SAndroid Build Coastguard Worker // Declare these outside of the loops, so we can reuse them for the second
846*9880d681SAndroid Build Coastguard Worker // loop, which loops the varargs.
847*9880d681SAndroid Build Coastguard Worker CallSite::arg_iterator I = CS.arg_begin();
848*9880d681SAndroid Build Coastguard Worker unsigned i = 0;
849*9880d681SAndroid Build Coastguard Worker // Loop over those operands, corresponding to the normal arguments to the
850*9880d681SAndroid Build Coastguard Worker // original function, and add those that are still alive.
851*9880d681SAndroid Build Coastguard Worker for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
852*9880d681SAndroid Build Coastguard Worker if (ArgAlive[i]) {
853*9880d681SAndroid Build Coastguard Worker Args.push_back(*I);
854*9880d681SAndroid Build Coastguard Worker // Get original parameter attributes, but skip return attributes.
855*9880d681SAndroid Build Coastguard Worker if (CallPAL.hasAttributes(i + 1)) {
856*9880d681SAndroid Build Coastguard Worker AttrBuilder B(CallPAL, i + 1);
857*9880d681SAndroid Build Coastguard Worker // If the return type has changed, then get rid of 'returned' on the
858*9880d681SAndroid Build Coastguard Worker // call site. The alternative is to make all 'returned' attributes on
859*9880d681SAndroid Build Coastguard Worker // call sites keep the return value alive just like 'returned'
860*9880d681SAndroid Build Coastguard Worker // attributes on function declaration but it's less clearly a win
861*9880d681SAndroid Build Coastguard Worker // and this is not an expected case anyway
862*9880d681SAndroid Build Coastguard Worker if (NRetTy != RetTy && B.contains(Attribute::Returned))
863*9880d681SAndroid Build Coastguard Worker B.removeAttribute(Attribute::Returned);
864*9880d681SAndroid Build Coastguard Worker AttributesVec.
865*9880d681SAndroid Build Coastguard Worker push_back(AttributeSet::get(F->getContext(), Args.size(), B));
866*9880d681SAndroid Build Coastguard Worker }
867*9880d681SAndroid Build Coastguard Worker }
868*9880d681SAndroid Build Coastguard Worker
869*9880d681SAndroid Build Coastguard Worker // Push any varargs arguments on the list. Don't forget their attributes.
870*9880d681SAndroid Build Coastguard Worker for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
871*9880d681SAndroid Build Coastguard Worker Args.push_back(*I);
872*9880d681SAndroid Build Coastguard Worker if (CallPAL.hasAttributes(i + 1)) {
873*9880d681SAndroid Build Coastguard Worker AttrBuilder B(CallPAL, i + 1);
874*9880d681SAndroid Build Coastguard Worker AttributesVec.
875*9880d681SAndroid Build Coastguard Worker push_back(AttributeSet::get(F->getContext(), Args.size(), B));
876*9880d681SAndroid Build Coastguard Worker }
877*9880d681SAndroid Build Coastguard Worker }
878*9880d681SAndroid Build Coastguard Worker
879*9880d681SAndroid Build Coastguard Worker if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
880*9880d681SAndroid Build Coastguard Worker AttributesVec.push_back(AttributeSet::get(Call->getContext(),
881*9880d681SAndroid Build Coastguard Worker CallPAL.getFnAttributes()));
882*9880d681SAndroid Build Coastguard Worker
883*9880d681SAndroid Build Coastguard Worker // Reconstruct the AttributesList based on the vector we constructed.
884*9880d681SAndroid Build Coastguard Worker AttributeSet NewCallPAL = AttributeSet::get(F->getContext(), AttributesVec);
885*9880d681SAndroid Build Coastguard Worker
886*9880d681SAndroid Build Coastguard Worker SmallVector<OperandBundleDef, 1> OpBundles;
887*9880d681SAndroid Build Coastguard Worker CS.getOperandBundlesAsDefs(OpBundles);
888*9880d681SAndroid Build Coastguard Worker
889*9880d681SAndroid Build Coastguard Worker Instruction *New;
890*9880d681SAndroid Build Coastguard Worker if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
891*9880d681SAndroid Build Coastguard Worker New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
892*9880d681SAndroid Build Coastguard Worker Args, OpBundles, "", Call->getParent());
893*9880d681SAndroid Build Coastguard Worker cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
894*9880d681SAndroid Build Coastguard Worker cast<InvokeInst>(New)->setAttributes(NewCallPAL);
895*9880d681SAndroid Build Coastguard Worker } else {
896*9880d681SAndroid Build Coastguard Worker New = CallInst::Create(NF, Args, OpBundles, "", Call);
897*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
898*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setAttributes(NewCallPAL);
899*9880d681SAndroid Build Coastguard Worker if (cast<CallInst>(Call)->isTailCall())
900*9880d681SAndroid Build Coastguard Worker cast<CallInst>(New)->setTailCall();
901*9880d681SAndroid Build Coastguard Worker }
902*9880d681SAndroid Build Coastguard Worker New->setDebugLoc(Call->getDebugLoc());
903*9880d681SAndroid Build Coastguard Worker
904*9880d681SAndroid Build Coastguard Worker Args.clear();
905*9880d681SAndroid Build Coastguard Worker
906*9880d681SAndroid Build Coastguard Worker if (!Call->use_empty()) {
907*9880d681SAndroid Build Coastguard Worker if (New->getType() == Call->getType()) {
908*9880d681SAndroid Build Coastguard Worker // Return type not changed? Just replace users then.
909*9880d681SAndroid Build Coastguard Worker Call->replaceAllUsesWith(New);
910*9880d681SAndroid Build Coastguard Worker New->takeName(Call);
911*9880d681SAndroid Build Coastguard Worker } else if (New->getType()->isVoidTy()) {
912*9880d681SAndroid Build Coastguard Worker // Our return value has uses, but they will get removed later on.
913*9880d681SAndroid Build Coastguard Worker // Replace by null for now.
914*9880d681SAndroid Build Coastguard Worker if (!Call->getType()->isX86_MMXTy())
915*9880d681SAndroid Build Coastguard Worker Call->replaceAllUsesWith(Constant::getNullValue(Call->getType()));
916*9880d681SAndroid Build Coastguard Worker } else {
917*9880d681SAndroid Build Coastguard Worker assert((RetTy->isStructTy() || RetTy->isArrayTy()) &&
918*9880d681SAndroid Build Coastguard Worker "Return type changed, but not into a void. The old return type"
919*9880d681SAndroid Build Coastguard Worker " must have been a struct or an array!");
920*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt = Call;
921*9880d681SAndroid Build Coastguard Worker if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
922*9880d681SAndroid Build Coastguard Worker BasicBlock *NewEdge = SplitEdge(New->getParent(), II->getNormalDest());
923*9880d681SAndroid Build Coastguard Worker InsertPt = &*NewEdge->getFirstInsertionPt();
924*9880d681SAndroid Build Coastguard Worker }
925*9880d681SAndroid Build Coastguard Worker
926*9880d681SAndroid Build Coastguard Worker // We used to return a struct or array. Instead of doing smart stuff
927*9880d681SAndroid Build Coastguard Worker // with all the uses, we will just rebuild it using extract/insertvalue
928*9880d681SAndroid Build Coastguard Worker // chaining and let instcombine clean that up.
929*9880d681SAndroid Build Coastguard Worker //
930*9880d681SAndroid Build Coastguard Worker // Start out building up our return value from undef
931*9880d681SAndroid Build Coastguard Worker Value *RetVal = UndefValue::get(RetTy);
932*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != RetCount; ++i)
933*9880d681SAndroid Build Coastguard Worker if (NewRetIdxs[i] != -1) {
934*9880d681SAndroid Build Coastguard Worker Value *V;
935*9880d681SAndroid Build Coastguard Worker if (RetTypes.size() > 1)
936*9880d681SAndroid Build Coastguard Worker // We are still returning a struct, so extract the value from our
937*9880d681SAndroid Build Coastguard Worker // return value
938*9880d681SAndroid Build Coastguard Worker V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
939*9880d681SAndroid Build Coastguard Worker InsertPt);
940*9880d681SAndroid Build Coastguard Worker else
941*9880d681SAndroid Build Coastguard Worker // We are now returning a single element, so just insert that
942*9880d681SAndroid Build Coastguard Worker V = New;
943*9880d681SAndroid Build Coastguard Worker // Insert the value at the old position
944*9880d681SAndroid Build Coastguard Worker RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
945*9880d681SAndroid Build Coastguard Worker }
946*9880d681SAndroid Build Coastguard Worker // Now, replace all uses of the old call instruction with the return
947*9880d681SAndroid Build Coastguard Worker // struct we built
948*9880d681SAndroid Build Coastguard Worker Call->replaceAllUsesWith(RetVal);
949*9880d681SAndroid Build Coastguard Worker New->takeName(Call);
950*9880d681SAndroid Build Coastguard Worker }
951*9880d681SAndroid Build Coastguard Worker }
952*9880d681SAndroid Build Coastguard Worker
953*9880d681SAndroid Build Coastguard Worker // Finally, remove the old call from the program, reducing the use-count of
954*9880d681SAndroid Build Coastguard Worker // F.
955*9880d681SAndroid Build Coastguard Worker Call->eraseFromParent();
956*9880d681SAndroid Build Coastguard Worker }
957*9880d681SAndroid Build Coastguard Worker
958*9880d681SAndroid Build Coastguard Worker // Since we have now created the new function, splice the body of the old
959*9880d681SAndroid Build Coastguard Worker // function right into the new function, leaving the old rotting hulk of the
960*9880d681SAndroid Build Coastguard Worker // function empty.
961*9880d681SAndroid Build Coastguard Worker NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
962*9880d681SAndroid Build Coastguard Worker
963*9880d681SAndroid Build Coastguard Worker // Loop over the argument list, transferring uses of the old arguments over to
964*9880d681SAndroid Build Coastguard Worker // the new arguments, also transferring over the names as well.
965*9880d681SAndroid Build Coastguard Worker i = 0;
966*9880d681SAndroid Build Coastguard Worker for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
967*9880d681SAndroid Build Coastguard Worker I2 = NF->arg_begin(); I != E; ++I, ++i)
968*9880d681SAndroid Build Coastguard Worker if (ArgAlive[i]) {
969*9880d681SAndroid Build Coastguard Worker // If this is a live argument, move the name and users over to the new
970*9880d681SAndroid Build Coastguard Worker // version.
971*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(&*I2);
972*9880d681SAndroid Build Coastguard Worker I2->takeName(&*I);
973*9880d681SAndroid Build Coastguard Worker ++I2;
974*9880d681SAndroid Build Coastguard Worker } else {
975*9880d681SAndroid Build Coastguard Worker // If this argument is dead, replace any uses of it with null constants
976*9880d681SAndroid Build Coastguard Worker // (these are guaranteed to become unused later on).
977*9880d681SAndroid Build Coastguard Worker if (!I->getType()->isX86_MMXTy())
978*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
979*9880d681SAndroid Build Coastguard Worker }
980*9880d681SAndroid Build Coastguard Worker
981*9880d681SAndroid Build Coastguard Worker // If we change the return value of the function we must rewrite any return
982*9880d681SAndroid Build Coastguard Worker // instructions. Check this now.
983*9880d681SAndroid Build Coastguard Worker if (F->getReturnType() != NF->getReturnType())
984*9880d681SAndroid Build Coastguard Worker for (BasicBlock &BB : *NF)
985*9880d681SAndroid Build Coastguard Worker if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
986*9880d681SAndroid Build Coastguard Worker Value *RetVal;
987*9880d681SAndroid Build Coastguard Worker
988*9880d681SAndroid Build Coastguard Worker if (NFTy->getReturnType()->isVoidTy()) {
989*9880d681SAndroid Build Coastguard Worker RetVal = nullptr;
990*9880d681SAndroid Build Coastguard Worker } else {
991*9880d681SAndroid Build Coastguard Worker assert(RetTy->isStructTy() || RetTy->isArrayTy());
992*9880d681SAndroid Build Coastguard Worker // The original return value was a struct or array, insert
993*9880d681SAndroid Build Coastguard Worker // extractvalue/insertvalue chains to extract only the values we need
994*9880d681SAndroid Build Coastguard Worker // to return and insert them into our new result.
995*9880d681SAndroid Build Coastguard Worker // This does generate messy code, but we'll let it to instcombine to
996*9880d681SAndroid Build Coastguard Worker // clean that up.
997*9880d681SAndroid Build Coastguard Worker Value *OldRet = RI->getOperand(0);
998*9880d681SAndroid Build Coastguard Worker // Start out building up our return value from undef
999*9880d681SAndroid Build Coastguard Worker RetVal = UndefValue::get(NRetTy);
1000*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0; i != RetCount; ++i)
1001*9880d681SAndroid Build Coastguard Worker if (NewRetIdxs[i] != -1) {
1002*9880d681SAndroid Build Coastguard Worker ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
1003*9880d681SAndroid Build Coastguard Worker "oldret", RI);
1004*9880d681SAndroid Build Coastguard Worker if (RetTypes.size() > 1) {
1005*9880d681SAndroid Build Coastguard Worker // We're still returning a struct, so reinsert the value into
1006*9880d681SAndroid Build Coastguard Worker // our new return value at the new index
1007*9880d681SAndroid Build Coastguard Worker
1008*9880d681SAndroid Build Coastguard Worker RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
1009*9880d681SAndroid Build Coastguard Worker "newret", RI);
1010*9880d681SAndroid Build Coastguard Worker } else {
1011*9880d681SAndroid Build Coastguard Worker // We are now only returning a simple value, so just return the
1012*9880d681SAndroid Build Coastguard Worker // extracted value.
1013*9880d681SAndroid Build Coastguard Worker RetVal = EV;
1014*9880d681SAndroid Build Coastguard Worker }
1015*9880d681SAndroid Build Coastguard Worker }
1016*9880d681SAndroid Build Coastguard Worker }
1017*9880d681SAndroid Build Coastguard Worker // Replace the return instruction with one returning the new return
1018*9880d681SAndroid Build Coastguard Worker // value (possibly 0 if we became void).
1019*9880d681SAndroid Build Coastguard Worker ReturnInst::Create(F->getContext(), RetVal, RI);
1020*9880d681SAndroid Build Coastguard Worker BB.getInstList().erase(RI);
1021*9880d681SAndroid Build Coastguard Worker }
1022*9880d681SAndroid Build Coastguard Worker
1023*9880d681SAndroid Build Coastguard Worker // Patch the pointer to LLVM function in debug info descriptor.
1024*9880d681SAndroid Build Coastguard Worker NF->setSubprogram(F->getSubprogram());
1025*9880d681SAndroid Build Coastguard Worker
1026*9880d681SAndroid Build Coastguard Worker // Now that the old function is dead, delete it.
1027*9880d681SAndroid Build Coastguard Worker F->eraseFromParent();
1028*9880d681SAndroid Build Coastguard Worker
1029*9880d681SAndroid Build Coastguard Worker return true;
1030*9880d681SAndroid Build Coastguard Worker }
1031*9880d681SAndroid Build Coastguard Worker
run(Module & M,ModuleAnalysisManager &)1032*9880d681SAndroid Build Coastguard Worker PreservedAnalyses DeadArgumentEliminationPass::run(Module &M,
1033*9880d681SAndroid Build Coastguard Worker ModuleAnalysisManager &) {
1034*9880d681SAndroid Build Coastguard Worker bool Changed = false;
1035*9880d681SAndroid Build Coastguard Worker
1036*9880d681SAndroid Build Coastguard Worker // First pass: Do a simple check to see if any functions can have their "..."
1037*9880d681SAndroid Build Coastguard Worker // removed. We can do this if they never call va_start. This loop cannot be
1038*9880d681SAndroid Build Coastguard Worker // fused with the next loop, because deleting a function invalidates
1039*9880d681SAndroid Build Coastguard Worker // information computed while surveying other functions.
1040*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "DeadArgumentEliminationPass - Deleting dead varargs\n");
1041*9880d681SAndroid Build Coastguard Worker for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1042*9880d681SAndroid Build Coastguard Worker Function &F = *I++;
1043*9880d681SAndroid Build Coastguard Worker if (F.getFunctionType()->isVarArg())
1044*9880d681SAndroid Build Coastguard Worker Changed |= DeleteDeadVarargs(F);
1045*9880d681SAndroid Build Coastguard Worker }
1046*9880d681SAndroid Build Coastguard Worker
1047*9880d681SAndroid Build Coastguard Worker // Second phase:loop through the module, determining which arguments are live.
1048*9880d681SAndroid Build Coastguard Worker // We assume all arguments are dead unless proven otherwise (allowing us to
1049*9880d681SAndroid Build Coastguard Worker // determine that dead arguments passed into recursive functions are dead).
1050*9880d681SAndroid Build Coastguard Worker //
1051*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "DeadArgumentEliminationPass - Determining liveness\n");
1052*9880d681SAndroid Build Coastguard Worker for (auto &F : M)
1053*9880d681SAndroid Build Coastguard Worker SurveyFunction(F);
1054*9880d681SAndroid Build Coastguard Worker
1055*9880d681SAndroid Build Coastguard Worker // Now, remove all dead arguments and return values from each function in
1056*9880d681SAndroid Build Coastguard Worker // turn.
1057*9880d681SAndroid Build Coastguard Worker for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1058*9880d681SAndroid Build Coastguard Worker // Increment now, because the function will probably get removed (ie.
1059*9880d681SAndroid Build Coastguard Worker // replaced by a new one).
1060*9880d681SAndroid Build Coastguard Worker Function *F = &*I++;
1061*9880d681SAndroid Build Coastguard Worker Changed |= RemoveDeadStuffFromFunction(F);
1062*9880d681SAndroid Build Coastguard Worker }
1063*9880d681SAndroid Build Coastguard Worker
1064*9880d681SAndroid Build Coastguard Worker // Finally, look for any unused parameters in functions with non-local
1065*9880d681SAndroid Build Coastguard Worker // linkage and replace the passed in parameters with undef.
1066*9880d681SAndroid Build Coastguard Worker for (auto &F : M)
1067*9880d681SAndroid Build Coastguard Worker Changed |= RemoveDeadArgumentsFromCallers(F);
1068*9880d681SAndroid Build Coastguard Worker
1069*9880d681SAndroid Build Coastguard Worker if (!Changed)
1070*9880d681SAndroid Build Coastguard Worker return PreservedAnalyses::all();
1071*9880d681SAndroid Build Coastguard Worker return PreservedAnalyses::none();
1072*9880d681SAndroid Build Coastguard Worker }
1073