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