Eliminate static ctors due to Statistic objects
[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 #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"
27 #include <set>
28 #include <algorithm>
29 using namespace llvm;
30
31 STATISTIC(NumRemoved, "Number of invokes removed");
32 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
33
34 namespace {
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;
39
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;
43
44     // runOnSCC - Analyze the SCC, performing the transformation if possible.
45     bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
46
47     bool SimplifyFunction(Function *F);
48     void DeleteBasicBlock(BasicBlock *BB);
49   };
50   RegisterPass<PruneEH> X("prune-eh", "Remove unused exception handling info");
51 }
52
53 ModulePass *llvm::createPruneEHPass() { return new PruneEH(); }
54
55
56 bool PruneEH::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
57   CallGraph &CG = getAnalysis<CallGraph>();
58   bool MadeChange = false;
59
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);
65
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.
70   //
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;
78     } else {
79       if (F->isExternal())
80         SCCMightReturn = true;
81
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;
89         }
90
91         // Invoke instructions don't allow unwinding to continue, so we are
92         // only interested in call instructions.
93         if (!SCCMightUnwind)
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;
103                   break;
104                 }
105               } else {
106                 // Indirect call, it might throw.
107                 SCCMightUnwind = true;
108                 break;
109               }
110             }
111         if (SCCMightUnwind && SCCMightReturn) break;
112       }
113     }
114   }
115
116   // If the SCC doesn't unwind or doesn't throw, note this fact.
117   if (!SCCMightUnwind)
118     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
119       DoesNotUnwind.insert(SCC[i]);
120   if (!SCCMightReturn)
121     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
122       DoesNotReturn.insert(SCC[i]);
123
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
127     // dead.
128     if (Function *F = SCC[i]->getFunction())
129       MadeChange |= SimplifyFunction(F);
130   }
131
132   return MadeChange;
133 }
134
135
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,
150                                                             II->op_end()),
151                                         Name, II);
152           Call->setCallingConv(II->getCallingConv());
153
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());
159
160           // Insert a branch to the normal destination right before the
161           // invoke.
162           new BranchInst(II->getNormalDest(), II);
163
164           // Finally, delete the invoke instruction!
165           BB->getInstList().pop_back();
166
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.
170
171           ++NumRemoved;
172           MadeChange = true;
173         }
174
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
182             // new BB.
183             BasicBlock *New = BB->splitBasicBlock(I);
184
185             // Remove the uncond branch and add an unreachable.
186             BB->getInstList().pop_back();
187             new UnreachableInst(BB);
188
189             DeleteBasicBlock(New);  // Delete the new BB.
190             MadeChange = true;
191             ++NumUnreach;
192             break;
193           }
194
195   }
196   return MadeChange;
197 }
198
199 /// DeleteBasicBlock - remove the specified basic block from the program,
200 /// updating the callgraph to reflect any now-obsolete edges due to calls that
201 /// exist in the BB.
202 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
203   assert(pred_begin(BB) == pred_end(BB) && "BB is not dead!");
204   CallGraph &CG = getAnalysis<CallGraph>();
205
206   CallGraphNode *CGN = CG[BB->getParent()];
207   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
208     --I;
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]);
215     }
216     if (!I->use_empty())
217       I->replaceAllUsesWith(UndefValue::get(I->getType()));
218   }
219
220   // Get the list of successors of this block.
221   std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
222
223   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
224     Succs[i]->removePredecessor(BB);
225
226   BB->eraseFromParent();
227 }