1 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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, and marking functions 'nounwind' if they cannot throw.
13 // It implements this as a bottom-up traversal of the call-graph.
15 //===----------------------------------------------------------------------===//
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"
34 #define DEBUG_TYPE "prune-eh"
36 STATISTIC(NumRemoved, "Number of invokes removed");
37 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
40 struct PruneEH : public CallGraphSCCPass {
41 static char ID; // Pass identification, replacement for typeid
42 PruneEH() : CallGraphSCCPass(ID) {
43 initializePruneEHPass(*PassRegistry::getPassRegistry());
46 // runOnSCC - Analyze the SCC, performing the transformation if possible.
47 bool runOnSCC(CallGraphSCC &SCC) override;
49 bool SimplifyFunction(Function *F);
50 void DeleteBasicBlock(BasicBlock *BB);
55 INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
56 "Remove unused exception handling info", false, false)
57 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
58 INITIALIZE_PASS_END(PruneEH, "prune-eh",
59 "Remove unused exception handling info", false, false)
61 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
64 bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
65 SmallPtrSet<CallGraphNode *, 8> SCCNodes;
66 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
67 bool MadeChange = false;
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)
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);
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.
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();
92 SCCMightUnwind = true;
93 SCCMightReturn = true;
94 } else if (F->isDeclaration() || F->mayBeOverridden()) {
95 SCCMightUnwind |= !F->doesNotThrow();
96 SCCMightReturn |= !F->doesNotReturn();
98 bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
99 bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
101 if (!CheckUnwind && !CheckReturn)
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;
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;
130 // Indirect call, it might throw.
131 SCCMightUnwind = true;
135 if (SCCMightUnwind && SCCMightReturn) break;
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;
146 NewAttributes.addAttribute(Attribute::NoUnwind);
148 NewAttributes.addAttribute(Attribute::NoReturn);
150 Function *F = (*I)->getFunction();
151 const AttributeSet &PAL = F->getAttributes().getFnAttributes();
152 const AttributeSet &NPAL = AttributeSet::get(
153 F->getContext(), AttributeSet::FunctionIndex, NewAttributes);
157 F->addAttributes(AttributeSet::FunctionIndex, NPAL);
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
165 if (Function *F = (*I)->getFunction())
166 MadeChange |= SimplifyFunction(F);
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.
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);
185 Call->setCallingConv(II->getCallingConv());
186 Call->setAttributes(II->getAttributes());
187 Call->setDebugLoc(II->getDebugLoc());
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());
197 // Insert a branch to the normal destination right before the
199 BranchInst::Create(II->getNormalDest(), II);
201 // Finally, delete the invoke instruction!
202 BB->getInstList().pop_back();
204 // If the unwind block is now dead, nuke it.
205 if (pred_empty(UnwindBlock))
206 DeleteBasicBlock(UnwindBlock); // Delete the new BB.
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
219 BasicBlock *New = BB->splitBasicBlock(I);
221 // Remove the uncond branch and add an unreachable.
222 BB->getInstList().pop_back();
223 new UnreachableInst(BB->getContext(), BB);
225 DeleteBasicBlock(New); // Delete the new BB.
235 /// DeleteBasicBlock - remove the specified basic block from the program,
236 /// updating the callgraph to reflect any now-obsolete edges due to calls that
238 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
239 assert(pred_empty(BB) && "BB is not dead!");
240 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
242 CallGraphNode *CGN = CG[BB->getParent()];
243 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
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);
251 I->replaceAllUsesWith(UndefValue::get(I->getType()));
254 // Get the list of successors of this block.
255 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
257 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
258 Succs[i]->removePredecessor(BB);
260 BB->eraseFromParent();