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/EHPersonalities.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/InlineAsm.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/LLVMContext.h"
32#include <algorithm>
33using namespace llvm;
34
35#define DEBUG_TYPE "prune-eh"
36
37STATISTIC(NumRemoved, "Number of invokes removed");
38STATISTIC(NumUnreach, "Number of noreturn calls optimized");
39
40namespace {
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
55char PruneEH::ID = 0;
56INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
57                "Remove unused exception handling info", false, false)
58INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
59INITIALIZE_PASS_END(PruneEH, "prune-eh",
60                "Remove unused exception handling info", false, false)
61
62Pass *llvm::createPruneEHPass() { return new PruneEH(); }
63
64
65bool 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->mayBeOverridden()) {
96      SCCMightUnwind |= !F->doesNotThrow();
97      SCCMightReturn |= !F->doesNotReturn();
98    } else {
99      bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
100      bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
101      // Determine if we should scan for InlineAsm in a naked function as it
102      // is the only way to return without a ReturnInst.  Only do this for
103      // no-inline functions as functions which may be inlined cannot
104      // meaningfully return via assembly.
105      bool CheckReturnViaAsm = CheckReturn &&
106                               F->hasFnAttribute(Attribute::Naked) &&
107                               F->hasFnAttribute(Attribute::NoInline);
108
109      if (!CheckUnwind && !CheckReturn)
110        continue;
111
112      for (const BasicBlock &BB : *F) {
113        const TerminatorInst *TI = BB.getTerminator();
114        if (CheckUnwind && TI->mayThrow()) {
115          SCCMightUnwind = true;
116        } else if (CheckReturn && isa<ReturnInst>(TI)) {
117          SCCMightReturn = true;
118        }
119
120        for (const Instruction &I : BB) {
121          if ((!CheckUnwind || SCCMightUnwind) &&
122              (!CheckReturnViaAsm || SCCMightReturn))
123            break;
124
125          // Check to see if this function performs an unwind or calls an
126          // unwinding function.
127          if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
128            bool InstMightUnwind = true;
129            if (const auto *CI = dyn_cast<CallInst>(&I)) {
130              if (Function *Callee = CI->getCalledFunction()) {
131                CallGraphNode *CalleeNode = CG[Callee];
132                // If the callee is outside our current SCC then we may throw
133                // because it might.  If it is inside, do nothing.
134                if (SCCNodes.count(CalleeNode) > 0)
135                  InstMightUnwind = false;
136              }
137            }
138            SCCMightUnwind |= InstMightUnwind;
139          }
140          if (CheckReturnViaAsm && !SCCMightReturn)
141            if (auto ICS = ImmutableCallSite(&I))
142              if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
143                if (IA->hasSideEffects())
144                  SCCMightReturn = true;
145        }
146
147        if (SCCMightUnwind && SCCMightReturn)
148          break;
149      }
150    }
151  }
152
153  // If the SCC doesn't unwind or doesn't throw, note this fact.
154  if (!SCCMightUnwind || !SCCMightReturn)
155    for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
156      Function *F = (*I)->getFunction();
157
158      if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
159        F->addFnAttr(Attribute::NoUnwind);
160        MadeChange = true;
161      }
162
163      if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
164        F->addFnAttr(Attribute::NoReturn);
165        MadeChange = true;
166      }
167    }
168
169  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
170    // Convert any invoke instructions to non-throwing functions in this node
171    // into call instructions with a branch.  This makes the exception blocks
172    // dead.
173    if (Function *F = (*I)->getFunction())
174      MadeChange |= SimplifyFunction(F);
175  }
176
177  return MadeChange;
178}
179
180
181// SimplifyFunction - Given information about callees, simplify the specified
182// function if we have invokes to non-unwinding functions or code after calls to
183// no-return functions.
184bool PruneEH::SimplifyFunction(Function *F) {
185  bool MadeChange = false;
186  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
187    if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
188      if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
189        SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
190        SmallVector<OperandBundleDef, 1> OpBundles;
191        II->getOperandBundlesAsDefs(OpBundles);
192
193        // Insert a call instruction before the invoke.
194        CallInst *Call = CallInst::Create(II->getCalledValue(), Args, OpBundles,
195                                          "", II);
196        Call->takeName(II);
197        Call->setCallingConv(II->getCallingConv());
198        Call->setAttributes(II->getAttributes());
199        Call->setDebugLoc(II->getDebugLoc());
200
201        // Anything that used the value produced by the invoke instruction
202        // now uses the value produced by the call instruction.  Note that we
203        // do this even for void functions and calls with no uses so that the
204        // callgraph edge is updated.
205        II->replaceAllUsesWith(Call);
206        BasicBlock *UnwindBlock = II->getUnwindDest();
207        UnwindBlock->removePredecessor(II->getParent());
208
209        // Insert a branch to the normal destination right before the
210        // invoke.
211        BranchInst::Create(II->getNormalDest(), II);
212
213        // Finally, delete the invoke instruction!
214        BB->getInstList().pop_back();
215
216        // If the unwind block is now dead, nuke it.
217        if (pred_empty(UnwindBlock))
218          DeleteBasicBlock(UnwindBlock);  // Delete the new BB.
219
220        ++NumRemoved;
221        MadeChange = true;
222      }
223
224    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
225      if (CallInst *CI = dyn_cast<CallInst>(I++))
226        if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
227          // This call calls a function that cannot return.  Insert an
228          // unreachable instruction after it and simplify the code.  Do this
229          // by splitting the BB, adding the unreachable, then deleting the
230          // new BB.
231          BasicBlock *New = BB->splitBasicBlock(I);
232
233          // Remove the uncond branch and add an unreachable.
234          BB->getInstList().pop_back();
235          new UnreachableInst(BB->getContext(), &*BB);
236
237          DeleteBasicBlock(New);  // Delete the new BB.
238          MadeChange = true;
239          ++NumUnreach;
240          break;
241        }
242  }
243
244  return MadeChange;
245}
246
247/// DeleteBasicBlock - remove the specified basic block from the program,
248/// updating the callgraph to reflect any now-obsolete edges due to calls that
249/// exist in the BB.
250void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
251  assert(pred_empty(BB) && "BB is not dead!");
252  CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
253
254  CallGraphNode *CGN = CG[BB->getParent()];
255  for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
256    --I;
257    if (CallInst *CI = dyn_cast<CallInst>(I)) {
258      if (!isa<IntrinsicInst>(I))
259        CGN->removeCallEdgeFor(CI);
260    } else if (InvokeInst *II = dyn_cast<InvokeInst>(I))
261      CGN->removeCallEdgeFor(II);
262    if (!I->use_empty())
263      I->replaceAllUsesWith(UndefValue::get(I->getType()));
264  }
265
266  // Get the list of successors of this block.
267  std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
268
269  for (unsigned i = 0, e = Succs.size(); i != e; ++i)
270    Succs[i]->removePredecessor(BB);
271
272  BB->eraseFromParent();
273}
274