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/Transforms/IPO.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/Analysis/CallGraphSCCPass.h"
23 #include "llvm/Analysis/EHPersonalities.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Transforms/Utils/Local.h"
35 #define DEBUG_TYPE "prune-eh"
37 STATISTIC(NumRemoved, "Number of invokes removed");
38 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
41 struct PruneEH : public CallGraphSCCPass {
42 static char ID; // Pass identification, replacement for typeid
43 PruneEH() : CallGraphSCCPass(ID) {
44 initializePruneEHPass(*PassRegistry::getPassRegistry());
47 // runOnSCC - Analyze the SCC, performing the transformation if possible.
48 bool runOnSCC(CallGraphSCC &SCC) override;
52 static bool SimplifyFunction(Function *F, CallGraph &CG);
53 static void DeleteBasicBlock(BasicBlock *BB, CallGraph &CG);
56 INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
57 "Remove unused exception handling info", false, false)
58 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
59 INITIALIZE_PASS_END(PruneEH, "prune-eh",
60 "Remove unused exception handling info", false, false)
62 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
64 static bool runImpl(CallGraphSCC &SCC, CallGraph &CG) {
65 SmallPtrSet<CallGraphNode *, 8> SCCNodes;
66 bool MadeChange = false;
68 // Fill SCCNodes with the elements of the SCC. Used for quickly
69 // looking up whether a given CallGraphNode is in this SCC.
70 for (CallGraphNode *I : SCC)
73 // First pass, scan all of the functions in the SCC, simplifying them
74 // according to what we know.
75 for (CallGraphNode *I : SCC)
76 if (Function *F = I->getFunction())
77 MadeChange |= SimplifyFunction(F, CG);
79 // Next, check to see if any callees might throw or if there are any external
80 // functions in this SCC: if so, we cannot prune any functions in this SCC.
81 // Definitions that are weak and not declared non-throwing might be
82 // overridden at linktime with something that throws, so assume that.
83 // If this SCC includes the unwind instruction, we KNOW it throws, so
84 // obviously the SCC might throw.
86 bool SCCMightUnwind = false, SCCMightReturn = false;
87 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end();
88 (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
89 Function *F = (*I)->getFunction();
91 SCCMightUnwind = true;
92 SCCMightReturn = true;
93 } else if (!F->hasExactDefinition()) {
94 SCCMightUnwind |= !F->doesNotThrow();
95 SCCMightReturn |= !F->doesNotReturn();
97 bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
98 bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
99 // Determine if we should scan for InlineAsm in a naked function as it
100 // is the only way to return without a ReturnInst. Only do this for
101 // no-inline functions as functions which may be inlined cannot
102 // meaningfully return via assembly.
103 bool CheckReturnViaAsm = CheckReturn &&
104 F->hasFnAttribute(Attribute::Naked) &&
105 F->hasFnAttribute(Attribute::NoInline);
107 if (!CheckUnwind && !CheckReturn)
110 for (const BasicBlock &BB : *F) {
111 const TerminatorInst *TI = BB.getTerminator();
112 if (CheckUnwind && TI->mayThrow()) {
113 SCCMightUnwind = true;
114 } else if (CheckReturn && isa<ReturnInst>(TI)) {
115 SCCMightReturn = true;
118 for (const Instruction &I : BB) {
119 if ((!CheckUnwind || SCCMightUnwind) &&
120 (!CheckReturnViaAsm || SCCMightReturn))
123 // Check to see if this function performs an unwind or calls an
124 // unwinding function.
125 if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
126 bool InstMightUnwind = true;
127 if (const auto *CI = dyn_cast<CallInst>(&I)) {
128 if (Function *Callee = CI->getCalledFunction()) {
129 CallGraphNode *CalleeNode = CG[Callee];
130 // If the callee is outside our current SCC then we may throw
131 // because it might. If it is inside, do nothing.
132 if (SCCNodes.count(CalleeNode) > 0)
133 InstMightUnwind = false;
136 SCCMightUnwind |= InstMightUnwind;
138 if (CheckReturnViaAsm && !SCCMightReturn)
139 if (auto ICS = ImmutableCallSite(&I))
140 if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
141 if (IA->hasSideEffects())
142 SCCMightReturn = true;
145 if (SCCMightUnwind && SCCMightReturn)
151 // If the SCC doesn't unwind or doesn't throw, note this fact.
152 if (!SCCMightUnwind || !SCCMightReturn)
153 for (CallGraphNode *I : SCC) {
154 Function *F = I->getFunction();
156 if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
157 F->addFnAttr(Attribute::NoUnwind);
161 if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
162 F->addFnAttr(Attribute::NoReturn);
167 for (CallGraphNode *I : SCC) {
168 // Convert any invoke instructions to non-throwing functions in this node
169 // into call instructions with a branch. This makes the exception blocks
171 if (Function *F = I->getFunction())
172 MadeChange |= SimplifyFunction(F, CG);
179 bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
182 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
183 return runImpl(SCC, CG);
187 // SimplifyFunction - Given information about callees, simplify the specified
188 // function if we have invokes to non-unwinding functions or code after calls to
189 // no-return functions.
190 static bool SimplifyFunction(Function *F, CallGraph &CG) {
191 bool MadeChange = false;
192 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
193 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
194 if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
195 BasicBlock *UnwindBlock = II->getUnwindDest();
196 removeUnwindEdge(&*BB);
198 // If the unwind block is now dead, nuke it.
199 if (pred_empty(UnwindBlock))
200 DeleteBasicBlock(UnwindBlock, CG); // Delete the new BB.
206 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
207 if (CallInst *CI = dyn_cast<CallInst>(I++))
208 if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
209 // This call calls a function that cannot return. Insert an
210 // unreachable instruction after it and simplify the code. Do this
211 // by splitting the BB, adding the unreachable, then deleting the
213 BasicBlock *New = BB->splitBasicBlock(I);
215 // Remove the uncond branch and add an unreachable.
216 BB->getInstList().pop_back();
217 new UnreachableInst(BB->getContext(), &*BB);
219 DeleteBasicBlock(New, CG); // Delete the new BB.
229 /// DeleteBasicBlock - remove the specified basic block from the program,
230 /// updating the callgraph to reflect any now-obsolete edges due to calls that
232 static void DeleteBasicBlock(BasicBlock *BB, CallGraph &CG) {
233 assert(pred_empty(BB) && "BB is not dead!");
235 Instruction *TokenInst = nullptr;
237 CallGraphNode *CGN = CG[BB->getParent()];
238 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
241 if (I->getType()->isTokenTy()) {
246 if (auto CS = CallSite (&*I)) {
247 const Function *Callee = CS.getCalledFunction();
248 if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
249 CGN->removeCallEdgeFor(CS);
250 else if (!Callee->isIntrinsic())
251 CGN->removeCallEdgeFor(CS);
255 I->replaceAllUsesWith(UndefValue::get(I->getType()));
259 if (!isa<TerminatorInst>(TokenInst))
260 changeToUnreachable(TokenInst->getNextNode(), /*UseLLVMTrap=*/false);
262 // Get the list of successors of this block.
263 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
265 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
266 Succs[i]->removePredecessor(BB);
268 BB->eraseFromParent();