1 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple interprocedural pass which walks the
11 // call-graph, turning invoke instructions into calls, iff the callee cannot
12 // throw an exception, and marking functions 'nounwind' if they cannot throw.
13 // It implements this as a bottom-up traversal of the call-graph.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/EHPersonalities.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Utils/Local.h"
34 #define DEBUG_TYPE "prune-eh"
36 STATISTIC(NumRemoved, "Number of invokes removed");
37 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
40 struct PruneEH : public CallGraphSCCPass {
41 static char ID; // Pass identification, replacement for typeid
42 PruneEH() : CallGraphSCCPass(ID) {
43 initializePruneEHPass(*PassRegistry::getPassRegistry());
46 // runOnSCC - Analyze the SCC, performing the transformation if possible.
47 bool runOnSCC(CallGraphSCC &SCC) override;
51 static bool SimplifyFunction(Function *F, CallGraph &CG);
52 static void DeleteBasicBlock(BasicBlock *BB, CallGraph &CG);
55 INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
56 "Remove unused exception handling info", false, false)
57 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
58 INITIALIZE_PASS_END(PruneEH, "prune-eh",
59 "Remove unused exception handling info", false, false)
61 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
63 static bool runImpl(CallGraphSCC &SCC, CallGraph &CG) {
64 SmallPtrSet<CallGraphNode *, 8> SCCNodes;
65 bool MadeChange = false;
67 // Fill SCCNodes with the elements of the SCC. Used for quickly
68 // looking up whether a given CallGraphNode is in this SCC.
69 for (CallGraphNode *I : SCC)
72 // First pass, scan all of the functions in the SCC, simplifying them
73 // according to what we know.
74 for (CallGraphNode *I : SCC)
75 if (Function *F = I->getFunction())
76 MadeChange |= SimplifyFunction(F, CG);
78 // Next, check to see if any callees might throw or if there are any external
79 // functions in this SCC: if so, we cannot prune any functions in this SCC.
80 // Definitions that are weak and not declared non-throwing might be
81 // overridden at linktime with something that throws, so assume that.
82 // If this SCC includes the unwind instruction, we KNOW it throws, so
83 // obviously the SCC might throw.
85 bool SCCMightUnwind = false, SCCMightReturn = false;
86 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end();
87 (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
88 Function *F = (*I)->getFunction();
90 SCCMightUnwind = true;
91 SCCMightReturn = true;
92 } else if (!F->hasExactDefinition()) {
93 SCCMightUnwind |= !F->doesNotThrow();
94 SCCMightReturn |= !F->doesNotReturn();
96 bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
97 bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
98 // Determine if we should scan for InlineAsm in a naked function as it
99 // is the only way to return without a ReturnInst. Only do this for
100 // no-inline functions as functions which may be inlined cannot
101 // meaningfully return via assembly.
102 bool CheckReturnViaAsm = CheckReturn &&
103 F->hasFnAttribute(Attribute::Naked) &&
104 F->hasFnAttribute(Attribute::NoInline);
106 if (!CheckUnwind && !CheckReturn)
109 for (const BasicBlock &BB : *F) {
110 const TerminatorInst *TI = BB.getTerminator();
111 if (CheckUnwind && TI->mayThrow()) {
112 SCCMightUnwind = true;
113 } else if (CheckReturn && isa<ReturnInst>(TI)) {
114 SCCMightReturn = true;
117 for (const Instruction &I : BB) {
118 if ((!CheckUnwind || SCCMightUnwind) &&
119 (!CheckReturnViaAsm || SCCMightReturn))
122 // Check to see if this function performs an unwind or calls an
123 // unwinding function.
124 if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
125 bool InstMightUnwind = true;
126 if (const auto *CI = dyn_cast<CallInst>(&I)) {
127 if (Function *Callee = CI->getCalledFunction()) {
128 CallGraphNode *CalleeNode = CG[Callee];
129 // If the callee is outside our current SCC then we may throw
130 // because it might. If it is inside, do nothing.
131 if (SCCNodes.count(CalleeNode) > 0)
132 InstMightUnwind = false;
135 SCCMightUnwind |= InstMightUnwind;
137 if (CheckReturnViaAsm && !SCCMightReturn)
138 if (auto ICS = ImmutableCallSite(&I))
139 if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
140 if (IA->hasSideEffects())
141 SCCMightReturn = true;
144 if (SCCMightUnwind && SCCMightReturn)
150 // If the SCC doesn't unwind or doesn't throw, note this fact.
151 if (!SCCMightUnwind || !SCCMightReturn)
152 for (CallGraphNode *I : SCC) {
153 Function *F = I->getFunction();
155 if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
156 F->addFnAttr(Attribute::NoUnwind);
160 if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
161 F->addFnAttr(Attribute::NoReturn);
166 for (CallGraphNode *I : SCC) {
167 // Convert any invoke instructions to non-throwing functions in this node
168 // into call instructions with a branch. This makes the exception blocks
170 if (Function *F = I->getFunction())
171 MadeChange |= SimplifyFunction(F, CG);
178 bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
181 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
182 return runImpl(SCC, CG);
186 // SimplifyFunction - Given information about callees, simplify the specified
187 // function if we have invokes to non-unwinding functions or code after calls to
188 // no-return functions.
189 static bool SimplifyFunction(Function *F, CallGraph &CG) {
190 bool MadeChange = false;
191 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
192 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
193 if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
194 BasicBlock *UnwindBlock = II->getUnwindDest();
195 removeUnwindEdge(&*BB);
197 // If the unwind block is now dead, nuke it.
198 if (pred_empty(UnwindBlock))
199 DeleteBasicBlock(UnwindBlock, CG); // Delete the new BB.
205 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
206 if (CallInst *CI = dyn_cast<CallInst>(I++))
207 if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
208 // This call calls a function that cannot return. Insert an
209 // unreachable instruction after it and simplify the code. Do this
210 // by splitting the BB, adding the unreachable, then deleting the
212 BasicBlock *New = BB->splitBasicBlock(I);
214 // Remove the uncond branch and add an unreachable.
215 BB->getInstList().pop_back();
216 new UnreachableInst(BB->getContext(), &*BB);
218 DeleteBasicBlock(New, CG); // Delete the new BB.
228 /// DeleteBasicBlock - remove the specified basic block from the program,
229 /// updating the callgraph to reflect any now-obsolete edges due to calls that
231 static void DeleteBasicBlock(BasicBlock *BB, CallGraph &CG) {
232 assert(pred_empty(BB) && "BB is not dead!");
234 Instruction *TokenInst = nullptr;
236 CallGraphNode *CGN = CG[BB->getParent()];
237 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
240 if (I->getType()->isTokenTy()) {
245 if (auto CS = CallSite (&*I)) {
246 const Function *Callee = CS.getCalledFunction();
247 if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
248 CGN->removeCallEdgeFor(CS);
249 else if (!Callee->isIntrinsic())
250 CGN->removeCallEdgeFor(CS);
254 I->replaceAllUsesWith(UndefValue::get(I->getType()));
258 if (!isa<TerminatorInst>(TokenInst))
259 changeToUnreachable(TokenInst->getNextNode(), /*UseLLVMTrap=*/false);
261 // Get the list of successors of this block.
262 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
264 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
265 Succs[i]->removePredecessor(BB);
267 BB->eraseFromParent();