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