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