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