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