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