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/Statistic.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/Analysis/CallGraphSCCPass.h"
23 #include "llvm/Analysis/EHPersonalities.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include <algorithm>
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "prune-eh"
36 
37 STATISTIC(NumRemoved, "Number of invokes removed");
38 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
39 
40 namespace {
41   struct PruneEH : public CallGraphSCCPass {
42     static char ID; // Pass identification, replacement for typeid
43     PruneEH() : CallGraphSCCPass(ID) {
44       initializePruneEHPass(*PassRegistry::getPassRegistry());
45     }
46 
47     // runOnSCC - Analyze the SCC, performing the transformation if possible.
48     bool runOnSCC(CallGraphSCC &SCC) override;
49 
50     bool SimplifyFunction(Function *F);
51     void DeleteBasicBlock(BasicBlock *BB);
52   };
53 }
54 
55 char PruneEH::ID = 0;
56 INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
57                 "Remove unused exception handling info", false, false)
58 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
59 INITIALIZE_PASS_END(PruneEH, "prune-eh",
60                 "Remove unused exception handling info", false, false)
61 
62 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
63 
64 
65 bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
66   SmallPtrSet<CallGraphNode *, 8> SCCNodes;
67   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
68   bool MadeChange = false;
69 
70   // Fill SCCNodes with the elements of the SCC.  Used for quickly
71   // looking up whether a given CallGraphNode is in this SCC.
72   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
73     SCCNodes.insert(*I);
74 
75   // First pass, scan all of the functions in the SCC, simplifying them
76   // according to what we know.
77   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
78     if (Function *F = (*I)->getFunction())
79       MadeChange |= SimplifyFunction(F);
80 
81   // Next, check to see if any callees might throw or if there are any external
82   // functions in this SCC: if so, we cannot prune any functions in this SCC.
83   // Definitions that are weak and not declared non-throwing might be
84   // overridden at linktime with something that throws, so assume that.
85   // If this SCC includes the unwind instruction, we KNOW it throws, so
86   // obviously the SCC might throw.
87   //
88   bool SCCMightUnwind = false, SCCMightReturn = false;
89   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end();
90        (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
91     Function *F = (*I)->getFunction();
92     if (!F) {
93       SCCMightUnwind = true;
94       SCCMightReturn = true;
95     } else if (F->isDeclaration() || F->isInterposable()) {
96       // Note: isInterposable (as opposed to hasExactDefinition) is fine above,
97       // since we're not inferring new attributes here, but only using existing,
98       // assumed to be correct, function attributes.
99       SCCMightUnwind |= !F->doesNotThrow();
100       SCCMightReturn |= !F->doesNotReturn();
101     } else {
102       bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
103       bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
104       // Determine if we should scan for InlineAsm in a naked function as it
105       // is the only way to return without a ReturnInst.  Only do this for
106       // no-inline functions as functions which may be inlined cannot
107       // meaningfully return via assembly.
108       bool CheckReturnViaAsm = CheckReturn &&
109                                F->hasFnAttribute(Attribute::Naked) &&
110                                F->hasFnAttribute(Attribute::NoInline);
111 
112       if (!CheckUnwind && !CheckReturn)
113         continue;
114 
115       for (const BasicBlock &BB : *F) {
116         const TerminatorInst *TI = BB.getTerminator();
117         if (CheckUnwind && TI->mayThrow()) {
118           SCCMightUnwind = true;
119         } else if (CheckReturn && isa<ReturnInst>(TI)) {
120           SCCMightReturn = true;
121         }
122 
123         for (const Instruction &I : BB) {
124           if ((!CheckUnwind || SCCMightUnwind) &&
125               (!CheckReturnViaAsm || SCCMightReturn))
126             break;
127 
128           // Check to see if this function performs an unwind or calls an
129           // unwinding function.
130           if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
131             bool InstMightUnwind = true;
132             if (const auto *CI = dyn_cast<CallInst>(&I)) {
133               if (Function *Callee = CI->getCalledFunction()) {
134                 CallGraphNode *CalleeNode = CG[Callee];
135                 // If the callee is outside our current SCC then we may throw
136                 // because it might.  If it is inside, do nothing.
137                 if (SCCNodes.count(CalleeNode) > 0)
138                   InstMightUnwind = false;
139               }
140             }
141             SCCMightUnwind |= InstMightUnwind;
142           }
143           if (CheckReturnViaAsm && !SCCMightReturn)
144             if (auto ICS = ImmutableCallSite(&I))
145               if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
146                 if (IA->hasSideEffects())
147                   SCCMightReturn = true;
148         }
149 
150         if (SCCMightUnwind && SCCMightReturn)
151           break;
152       }
153     }
154   }
155 
156   // If the SCC doesn't unwind or doesn't throw, note this fact.
157   if (!SCCMightUnwind || !SCCMightReturn)
158     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
159       Function *F = (*I)->getFunction();
160 
161       if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
162         F->addFnAttr(Attribute::NoUnwind);
163         MadeChange = true;
164       }
165 
166       if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
167         F->addFnAttr(Attribute::NoReturn);
168         MadeChange = true;
169       }
170     }
171 
172   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
173     // Convert any invoke instructions to non-throwing functions in this node
174     // into call instructions with a branch.  This makes the exception blocks
175     // dead.
176     if (Function *F = (*I)->getFunction())
177       MadeChange |= SimplifyFunction(F);
178   }
179 
180   return MadeChange;
181 }
182 
183 
184 // SimplifyFunction - Given information about callees, simplify the specified
185 // function if we have invokes to non-unwinding functions or code after calls to
186 // no-return functions.
187 bool PruneEH::SimplifyFunction(Function *F) {
188   bool MadeChange = false;
189   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
190     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
191       if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
192         BasicBlock *UnwindBlock = II->getUnwindDest();
193         removeUnwindEdge(&*BB);
194 
195         // If the unwind block is now dead, nuke it.
196         if (pred_empty(UnwindBlock))
197           DeleteBasicBlock(UnwindBlock);  // Delete the new BB.
198 
199         ++NumRemoved;
200         MadeChange = true;
201       }
202 
203     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
204       if (CallInst *CI = dyn_cast<CallInst>(I++))
205         if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
206           // This call calls a function that cannot return.  Insert an
207           // unreachable instruction after it and simplify the code.  Do this
208           // by splitting the BB, adding the unreachable, then deleting the
209           // new BB.
210           BasicBlock *New = BB->splitBasicBlock(I);
211 
212           // Remove the uncond branch and add an unreachable.
213           BB->getInstList().pop_back();
214           new UnreachableInst(BB->getContext(), &*BB);
215 
216           DeleteBasicBlock(New);  // Delete the new BB.
217           MadeChange = true;
218           ++NumUnreach;
219           break;
220         }
221   }
222 
223   return MadeChange;
224 }
225 
226 /// DeleteBasicBlock - remove the specified basic block from the program,
227 /// updating the callgraph to reflect any now-obsolete edges due to calls that
228 /// exist in the BB.
229 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
230   assert(pred_empty(BB) && "BB is not dead!");
231   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
232 
233   Instruction *TokenInst = nullptr;
234 
235   CallGraphNode *CGN = CG[BB->getParent()];
236   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
237     --I;
238 
239     if (I->getType()->isTokenTy()) {
240       TokenInst = &*I;
241       break;
242     }
243 
244     if (auto CS = CallSite (&*I)) {
245       const Function *Callee = CS.getCalledFunction();
246       if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
247         CGN->removeCallEdgeFor(CS);
248       else if (!Callee->isIntrinsic())
249         CGN->removeCallEdgeFor(CS);
250     }
251 
252     if (!I->use_empty())
253       I->replaceAllUsesWith(UndefValue::get(I->getType()));
254   }
255 
256   if (TokenInst) {
257     if (!isa<TerminatorInst>(TokenInst))
258       changeToUnreachable(TokenInst->getNextNode(), /*UseLLVMTrap=*/false);
259   } else {
260     // Get the list of successors of this block.
261     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
262 
263     for (unsigned i = 0, e = Succs.size(); i != e; ++i)
264       Succs[i]->removePredecessor(BB);
265 
266     BB->eraseFromParent();
267   }
268 }
269