1 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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. It implements this as a bottom-up traversal of the
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "prune-eh"
18 #include "llvm/Transforms/IPO.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/CFG.h"
31 STATISTIC(NumRemoved, "Number of invokes removed");
32 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
35 struct PruneEH : public CallGraphSCCPass {
36 /// DoesNotUnwind - This set contains all of the functions which we have
37 /// determined cannot unwind.
38 std::set<CallGraphNode*> DoesNotUnwind;
40 /// DoesNotReturn - This set contains all of the functions which we have
41 /// determined cannot return normally (but might unwind).
42 std::set<CallGraphNode*> DoesNotReturn;
44 // runOnSCC - Analyze the SCC, performing the transformation if possible.
45 bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
47 bool SimplifyFunction(Function *F);
48 void DeleteBasicBlock(BasicBlock *BB);
50 RegisterPass<PruneEH> X("prune-eh", "Remove unused exception handling info");
53 ModulePass *llvm::createPruneEHPass() { return new PruneEH(); }
56 bool PruneEH::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
57 CallGraph &CG = getAnalysis<CallGraph>();
58 bool MadeChange = false;
60 // First pass, scan all of the functions in the SCC, simplifying them
61 // according to what we know.
62 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
63 if (Function *F = SCC[i]->getFunction())
64 MadeChange |= SimplifyFunction(F);
66 // Next, check to see if any callees might throw or if there are any external
67 // functions in this SCC: if so, we cannot prune any functions in this SCC.
68 // If this SCC includes the unwind instruction, we KNOW it throws, so
69 // obviously the SCC might throw.
71 bool SCCMightUnwind = false, SCCMightReturn = false;
72 for (unsigned i = 0, e = SCC.size();
73 (!SCCMightUnwind || !SCCMightReturn) && i != e; ++i) {
74 Function *F = SCC[i]->getFunction();
75 if (F == 0 || (F->isExternal() && !F->getIntrinsicID())) {
76 SCCMightUnwind = true;
77 SCCMightReturn = true;
80 SCCMightReturn = true;
82 // Check to see if this function performs an unwind or calls an
83 // unwinding function.
84 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
85 if (isa<UnwindInst>(BB->getTerminator())) { // Uses unwind!
86 SCCMightUnwind = true;
87 } else if (isa<ReturnInst>(BB->getTerminator())) {
88 SCCMightReturn = true;
91 // Invoke instructions don't allow unwinding to continue, so we are
92 // only interested in call instructions.
94 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
95 if (CallInst *CI = dyn_cast<CallInst>(I)) {
96 if (Function *Callee = CI->getCalledFunction()) {
97 CallGraphNode *CalleeNode = CG[Callee];
98 // If the callee is outside our current SCC, or if it is not
99 // known to throw, then we might throw also.
100 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end()&&
101 !DoesNotUnwind.count(CalleeNode)) {
102 SCCMightUnwind = true;
106 // Indirect call, it might throw.
107 SCCMightUnwind = true;
111 if (SCCMightUnwind && SCCMightReturn) break;
116 // If the SCC doesn't unwind or doesn't throw, note this fact.
118 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
119 DoesNotUnwind.insert(SCC[i]);
121 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
122 DoesNotReturn.insert(SCC[i]);
124 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
125 // Convert any invoke instructions to non-throwing functions in this node
126 // into call instructions with a branch. This makes the exception blocks
128 if (Function *F = SCC[i]->getFunction())
129 MadeChange |= SimplifyFunction(F);
136 // SimplifyFunction - Given information about callees, simplify the specified
137 // function if we have invokes to non-unwinding functions or code after calls to
138 // no-return functions.
139 bool PruneEH::SimplifyFunction(Function *F) {
140 CallGraph &CG = getAnalysis<CallGraph>();
141 bool MadeChange = false;
142 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
143 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
144 if (Function *F = II->getCalledFunction())
145 if (DoesNotUnwind.count(CG[F])) {
146 // Insert a call instruction before the invoke...
147 std::string Name = II->getName(); II->setName("");
148 CallInst *Call = new CallInst(II->getCalledValue(),
149 std::vector<Value*>(II->op_begin()+3,
152 Call->setCallingConv(II->getCallingConv());
154 // Anything that used the value produced by the invoke instruction
155 // now uses the value produced by the call instruction.
156 II->replaceAllUsesWith(Call);
157 BasicBlock *UnwindBlock = II->getUnwindDest();
158 UnwindBlock->removePredecessor(II->getParent());
160 // Insert a branch to the normal destination right before the
162 new BranchInst(II->getNormalDest(), II);
164 // Finally, delete the invoke instruction!
165 BB->getInstList().pop_back();
167 // If the unwind block is now dead, nuke it.
168 if (pred_begin(UnwindBlock) == pred_end(UnwindBlock))
169 DeleteBasicBlock(UnwindBlock); // Delete the new BB.
175 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
176 if (CallInst *CI = dyn_cast<CallInst>(I++))
177 if (Function *Callee = CI->getCalledFunction())
178 if (DoesNotReturn.count(CG[Callee]) && !isa<UnreachableInst>(I)) {
179 // This call calls a function that cannot return. Insert an
180 // unreachable instruction after it and simplify the code. Do this
181 // by splitting the BB, adding the unreachable, then deleting the
183 BasicBlock *New = BB->splitBasicBlock(I);
185 // Remove the uncond branch and add an unreachable.
186 BB->getInstList().pop_back();
187 new UnreachableInst(BB);
189 DeleteBasicBlock(New); // Delete the new BB.
199 /// DeleteBasicBlock - remove the specified basic block from the program,
200 /// updating the callgraph to reflect any now-obsolete edges due to calls that
202 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
203 assert(pred_begin(BB) == pred_end(BB) && "BB is not dead!");
204 CallGraph &CG = getAnalysis<CallGraph>();
206 CallGraphNode *CGN = CG[BB->getParent()];
207 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
209 if (CallInst *CI = dyn_cast<CallInst>(I)) {
210 if (Function *Callee = CI->getCalledFunction())
211 CGN->removeCallEdgeTo(CG[Callee]);
212 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
213 if (Function *Callee = II->getCalledFunction())
214 CGN->removeCallEdgeTo(CG[Callee]);
217 I->replaceAllUsesWith(UndefValue::get(I->getType()));
220 // Get the list of successors of this block.
221 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
223 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
224 Succs[i]->removePredecessor(BB);
226 BB->eraseFromParent();