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