blob: a783272843fa7b21b25f605b59426b18fee69a70 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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
13// call-graph.
14//
15//===----------------------------------------------------------------------===//
16
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/SmallVector.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/CFG.h"
28#include "llvm/Support/Compiler.h"
29#include <set>
30#include <algorithm>
31using namespace llvm;
32
33STATISTIC(NumRemoved, "Number of invokes removed");
34STATISTIC(NumUnreach, "Number of noreturn calls optimized");
35
36namespace {
37 struct VISIBILITY_HIDDEN PruneEH : public CallGraphSCCPass {
38 static char ID; // Pass identification, replacement for typeid
39 PruneEH() : CallGraphSCCPass((intptr_t)&ID) {}
40
41 /// DoesNotUnwind - This set contains all of the functions which we have
42 /// determined cannot unwind.
43 std::set<CallGraphNode*> DoesNotUnwind;
44
45 /// DoesNotReturn - This set contains all of the functions which we have
46 /// determined cannot return normally (but might unwind).
47 std::set<CallGraphNode*> DoesNotReturn;
48
49 // runOnSCC - Analyze the SCC, performing the transformation if possible.
50 bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
51
52 bool SimplifyFunction(Function *F);
53 void DeleteBasicBlock(BasicBlock *BB);
54 };
55
56 char PruneEH::ID = 0;
57 RegisterPass<PruneEH> X("prune-eh", "Remove unused exception handling info");
58}
59
60Pass *llvm::createPruneEHPass() { return new PruneEH(); }
61
62
63bool PruneEH::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
64 CallGraph &CG = getAnalysis<CallGraph>();
65 bool MadeChange = false;
66
67 // First pass, scan all of the functions in the SCC, simplifying them
68 // according to what we know.
69 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
70 if (Function *F = SCC[i]->getFunction())
71 MadeChange |= SimplifyFunction(F);
72
73 // Next, check to see if any callees might throw or if there are any external
74 // functions in this SCC: if so, we cannot prune any functions in this SCC.
75 // If this SCC includes the unwind instruction, we KNOW it throws, so
76 // obviously the SCC might throw.
77 //
78 bool SCCMightUnwind = false, SCCMightReturn = false;
79 for (unsigned i = 0, e = SCC.size();
80 (!SCCMightUnwind || !SCCMightReturn) && i != e; ++i) {
81 Function *F = SCC[i]->getFunction();
82 if (F == 0 || (F->isDeclaration() && !F->getIntrinsicID())) {
83 SCCMightUnwind = true;
84 SCCMightReturn = true;
85 } else {
86 if (F->isDeclaration())
87 SCCMightReturn = true;
88
89 // Check to see if this function performs an unwind or calls an
90 // unwinding function.
91 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
92 if (isa<UnwindInst>(BB->getTerminator())) { // Uses unwind!
93 SCCMightUnwind = true;
94 } else if (isa<ReturnInst>(BB->getTerminator())) {
95 SCCMightReturn = true;
96 }
97
98 // Invoke instructions don't allow unwinding to continue, so we are
99 // only interested in call instructions.
100 if (!SCCMightUnwind)
101 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
102 if (CallInst *CI = dyn_cast<CallInst>(I)) {
103 if (Function *Callee = CI->getCalledFunction()) {
104 CallGraphNode *CalleeNode = CG[Callee];
105 // If the callee is outside our current SCC, or if it is not
106 // known to throw, then we might throw also.
107 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end()&&
108 !DoesNotUnwind.count(CalleeNode)) {
109 SCCMightUnwind = true;
110 break;
111 }
112 } else {
113 // Indirect call, it might throw.
114 SCCMightUnwind = true;
115 break;
116 }
117 }
118 if (SCCMightUnwind && SCCMightReturn) break;
119 }
120 }
121 }
122
123 // If the SCC doesn't unwind or doesn't throw, note this fact.
124 if (!SCCMightUnwind)
125 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
126 DoesNotUnwind.insert(SCC[i]);
127 if (!SCCMightReturn)
128 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
129 DoesNotReturn.insert(SCC[i]);
130
131 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
132 // Convert any invoke instructions to non-throwing functions in this node
133 // into call instructions with a branch. This makes the exception blocks
134 // dead.
135 if (Function *F = SCC[i]->getFunction())
136 MadeChange |= SimplifyFunction(F);
137 }
138
139 return MadeChange;
140}
141
142
143// SimplifyFunction - Given information about callees, simplify the specified
144// function if we have invokes to non-unwinding functions or code after calls to
145// no-return functions.
146bool PruneEH::SimplifyFunction(Function *F) {
147 CallGraph &CG = getAnalysis<CallGraph>();
148 bool MadeChange = false;
149 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
150 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
151 if (Function *F = II->getCalledFunction())
152 if (DoesNotUnwind.count(CG[F])) {
153 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
154 // Insert a call instruction before the invoke.
155 CallInst *Call = new CallInst(II->getCalledValue(),
156 &Args[0], Args.size(), "", II);
157 Call->takeName(II);
158 Call->setCallingConv(II->getCallingConv());
159
160 // Anything that used the value produced by the invoke instruction
161 // now uses the value produced by the call instruction.
162 II->replaceAllUsesWith(Call);
163 BasicBlock *UnwindBlock = II->getUnwindDest();
164 UnwindBlock->removePredecessor(II->getParent());
165
166 // Insert a branch to the normal destination right before the
167 // invoke.
168 new BranchInst(II->getNormalDest(), II);
169
170 // Finally, delete the invoke instruction!
171 BB->getInstList().pop_back();
172
173 // If the unwind block is now dead, nuke it.
174 if (pred_begin(UnwindBlock) == pred_end(UnwindBlock))
175 DeleteBasicBlock(UnwindBlock); // Delete the new BB.
176
177 ++NumRemoved;
178 MadeChange = true;
179 }
180
181 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
182 if (CallInst *CI = dyn_cast<CallInst>(I++))
183 if (Function *Callee = CI->getCalledFunction())
184 if (DoesNotReturn.count(CG[Callee]) && !isa<UnreachableInst>(I)) {
185 // This call calls a function that cannot return. Insert an
186 // unreachable instruction after it and simplify the code. Do this
187 // by splitting the BB, adding the unreachable, then deleting the
188 // new BB.
189 BasicBlock *New = BB->splitBasicBlock(I);
190
191 // Remove the uncond branch and add an unreachable.
192 BB->getInstList().pop_back();
193 new UnreachableInst(BB);
194
195 DeleteBasicBlock(New); // Delete the new BB.
196 MadeChange = true;
197 ++NumUnreach;
198 break;
199 }
200
201 }
202 return MadeChange;
203}
204
205/// DeleteBasicBlock - remove the specified basic block from the program,
206/// updating the callgraph to reflect any now-obsolete edges due to calls that
207/// exist in the BB.
208void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
209 assert(pred_begin(BB) == pred_end(BB) && "BB is not dead!");
210 CallGraph &CG = getAnalysis<CallGraph>();
211
212 CallGraphNode *CGN = CG[BB->getParent()];
213 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
214 --I;
215 if (CallInst *CI = dyn_cast<CallInst>(I)) {
216 if (Function *Callee = CI->getCalledFunction())
217 CGN->removeCallEdgeTo(CG[Callee]);
218 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
219 if (Function *Callee = II->getCalledFunction())
220 CGN->removeCallEdgeTo(CG[Callee]);
221 }
222 if (!I->use_empty())
223 I->replaceAllUsesWith(UndefValue::get(I->getType()));
224 }
225
226 // Get the list of successors of this block.
227 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
228
229 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
230 Succs[i]->removePredecessor(BB);
231
232 BB->eraseFromParent();
233}