1 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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, and marking functions 'nounwind' if they cannot throw.
13 // It implements this as a bottom-up traversal of the call-graph.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Analysis/CallGraph.h"
23 #include "llvm/Analysis/CallGraphSCCPass.h"
24 #include "llvm/Analysis/LibCallSemantics.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include <algorithm>
32 using namespace llvm;
33
34 #define DEBUG_TYPE "prune-eh"
35
36 STATISTIC(NumRemoved, "Number of invokes removed");
37 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
38
39 namespace {
40 struct PruneEH : public CallGraphSCCPass {
41 static char ID; // Pass identification, replacement for typeid
PruneEH__anon32217f7e0111::PruneEH42 PruneEH() : CallGraphSCCPass(ID) {
43 initializePruneEHPass(*PassRegistry::getPassRegistry());
44 }
45
46 // runOnSCC - Analyze the SCC, performing the transformation if possible.
47 bool runOnSCC(CallGraphSCC &SCC) override;
48
49 bool SimplifyFunction(Function *F);
50 void DeleteBasicBlock(BasicBlock *BB);
51 };
52 }
53
54 char PruneEH::ID = 0;
55 INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
56 "Remove unused exception handling info", false, false)
INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)57 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
58 INITIALIZE_PASS_END(PruneEH, "prune-eh",
59 "Remove unused exception handling info", false, false)
60
61 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
62
63
runOnSCC(CallGraphSCC & SCC)64 bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
65 SmallPtrSet<CallGraphNode *, 8> SCCNodes;
66 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
67 bool MadeChange = false;
68
69 // Fill SCCNodes with the elements of the SCC. Used for quickly
70 // looking up whether a given CallGraphNode is in this SCC.
71 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
72 SCCNodes.insert(*I);
73
74 // First pass, scan all of the functions in the SCC, simplifying them
75 // according to what we know.
76 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
77 if (Function *F = (*I)->getFunction())
78 MadeChange |= SimplifyFunction(F);
79
80 // Next, check to see if any callees might throw or if there are any external
81 // functions in this SCC: if so, we cannot prune any functions in this SCC.
82 // Definitions that are weak and not declared non-throwing might be
83 // overridden at linktime with something that throws, so assume that.
84 // If this SCC includes the unwind instruction, we KNOW it throws, so
85 // obviously the SCC might throw.
86 //
87 bool SCCMightUnwind = false, SCCMightReturn = false;
88 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end();
89 (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
90 Function *F = (*I)->getFunction();
91 if (!F) {
92 SCCMightUnwind = true;
93 SCCMightReturn = true;
94 } else if (F->isDeclaration() || F->mayBeOverridden()) {
95 SCCMightUnwind |= !F->doesNotThrow();
96 SCCMightReturn |= !F->doesNotReturn();
97 } else {
98 bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
99 bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
100
101 if (!CheckUnwind && !CheckReturn)
102 continue;
103
104 // Check to see if this function performs an unwind or calls an
105 // unwinding function.
106 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
107 if (CheckUnwind && isa<ResumeInst>(BB->getTerminator())) {
108 // Uses unwind / resume!
109 SCCMightUnwind = true;
110 } else if (CheckReturn && isa<ReturnInst>(BB->getTerminator())) {
111 SCCMightReturn = true;
112 }
113
114 // Invoke instructions don't allow unwinding to continue, so we are
115 // only interested in call instructions.
116 if (CheckUnwind && !SCCMightUnwind)
117 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
118 if (CallInst *CI = dyn_cast<CallInst>(I)) {
119 if (CI->doesNotThrow()) {
120 // This call cannot throw.
121 } else if (Function *Callee = CI->getCalledFunction()) {
122 CallGraphNode *CalleeNode = CG[Callee];
123 // If the callee is outside our current SCC then we may
124 // throw because it might.
125 if (!SCCNodes.count(CalleeNode)) {
126 SCCMightUnwind = true;
127 break;
128 }
129 } else {
130 // Indirect call, it might throw.
131 SCCMightUnwind = true;
132 break;
133 }
134 }
135 if (SCCMightUnwind && SCCMightReturn) break;
136 }
137 }
138 }
139
140 // If the SCC doesn't unwind or doesn't throw, note this fact.
141 if (!SCCMightUnwind || !SCCMightReturn)
142 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
143 AttrBuilder NewAttributes;
144
145 if (!SCCMightUnwind)
146 NewAttributes.addAttribute(Attribute::NoUnwind);
147 if (!SCCMightReturn)
148 NewAttributes.addAttribute(Attribute::NoReturn);
149
150 Function *F = (*I)->getFunction();
151 const AttributeSet &PAL = F->getAttributes().getFnAttributes();
152 const AttributeSet &NPAL = AttributeSet::get(
153 F->getContext(), AttributeSet::FunctionIndex, NewAttributes);
154
155 if (PAL != NPAL) {
156 MadeChange = true;
157 F->addAttributes(AttributeSet::FunctionIndex, NPAL);
158 }
159 }
160
161 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
162 // Convert any invoke instructions to non-throwing functions in this node
163 // into call instructions with a branch. This makes the exception blocks
164 // dead.
165 if (Function *F = (*I)->getFunction())
166 MadeChange |= SimplifyFunction(F);
167 }
168
169 return MadeChange;
170 }
171
172
173 // SimplifyFunction - Given information about callees, simplify the specified
174 // function if we have invokes to non-unwinding functions or code after calls to
175 // no-return functions.
SimplifyFunction(Function * F)176 bool PruneEH::SimplifyFunction(Function *F) {
177 bool MadeChange = false;
178 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
179 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
180 if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(II)) {
181 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
182 // Insert a call instruction before the invoke.
183 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
184 Call->takeName(II);
185 Call->setCallingConv(II->getCallingConv());
186 Call->setAttributes(II->getAttributes());
187 Call->setDebugLoc(II->getDebugLoc());
188
189 // Anything that used the value produced by the invoke instruction
190 // now uses the value produced by the call instruction. Note that we
191 // do this even for void functions and calls with no uses so that the
192 // callgraph edge is updated.
193 II->replaceAllUsesWith(Call);
194 BasicBlock *UnwindBlock = II->getUnwindDest();
195 UnwindBlock->removePredecessor(II->getParent());
196
197 // Insert a branch to the normal destination right before the
198 // invoke.
199 BranchInst::Create(II->getNormalDest(), II);
200
201 // Finally, delete the invoke instruction!
202 BB->getInstList().pop_back();
203
204 // If the unwind block is now dead, nuke it.
205 if (pred_empty(UnwindBlock))
206 DeleteBasicBlock(UnwindBlock); // Delete the new BB.
207
208 ++NumRemoved;
209 MadeChange = true;
210 }
211
212 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
213 if (CallInst *CI = dyn_cast<CallInst>(I++))
214 if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
215 // This call calls a function that cannot return. Insert an
216 // unreachable instruction after it and simplify the code. Do this
217 // by splitting the BB, adding the unreachable, then deleting the
218 // new BB.
219 BasicBlock *New = BB->splitBasicBlock(I);
220
221 // Remove the uncond branch and add an unreachable.
222 BB->getInstList().pop_back();
223 new UnreachableInst(BB->getContext(), BB);
224
225 DeleteBasicBlock(New); // Delete the new BB.
226 MadeChange = true;
227 ++NumUnreach;
228 break;
229 }
230 }
231
232 return MadeChange;
233 }
234
235 /// DeleteBasicBlock - remove the specified basic block from the program,
236 /// updating the callgraph to reflect any now-obsolete edges due to calls that
237 /// exist in the BB.
DeleteBasicBlock(BasicBlock * BB)238 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
239 assert(pred_empty(BB) && "BB is not dead!");
240 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
241
242 CallGraphNode *CGN = CG[BB->getParent()];
243 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
244 --I;
245 if (CallInst *CI = dyn_cast<CallInst>(I)) {
246 if (!isa<IntrinsicInst>(I))
247 CGN->removeCallEdgeFor(CI);
248 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I))
249 CGN->removeCallEdgeFor(II);
250 if (!I->use_empty())
251 I->replaceAllUsesWith(UndefValue::get(I->getType()));
252 }
253
254 // Get the list of successors of this block.
255 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
256
257 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
258 Succs[i]->removePredecessor(BB);
259
260 BB->eraseFromParent();
261 }
262