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