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