PruneEH.cpp revision 296417
159118Skris//===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
222347Spst//
329964Sache//                     The LLVM Compiler Infrastructure
492906Smarkm//
592906Smarkm// This file is distributed under the University of Illinois Open Source
622347Spst// License. See LICENSE.TXT for details.
722347Spst//
822347Spst//===----------------------------------------------------------------------===//
922347Spst//
1022347Spst// This file implements a simple interprocedural pass which walks the
1192906Smarkm// call-graph, turning invoke instructions into calls, iff the callee cannot
1292906Smarkm// throw an exception, and marking functions 'nounwind' if they cannot throw.
1359118Skris// It implements this as a bottom-up traversal of the call-graph.
1459118Skris//
1522347Spst//===----------------------------------------------------------------------===//
1622347Spst
1722347Spst#include "llvm/Transforms/IPO.h"
1822347Spst#include "llvm/ADT/SmallPtrSet.h"
1922347Spst#include "llvm/ADT/SmallVector.h"
2022347Spst#include "llvm/ADT/Statistic.h"
2122347Spst#include "llvm/Support/raw_ostream.h"
2222347Spst#include "llvm/Analysis/CallGraph.h"
2322347Spst#include "llvm/Analysis/CallGraphSCCPass.h"
2422347Spst#include "llvm/Analysis/EHPersonalities.h"
2522347Spst#include "llvm/IR/CFG.h"
2622347Spst#include "llvm/IR/Constants.h"
2722347Spst#include "llvm/IR/Function.h"
2822347Spst#include "llvm/IR/InlineAsm.h"
2922347Spst#include "llvm/IR/Instructions.h"
3022347Spst#include "llvm/IR/IntrinsicInst.h"
3122347Spst#include "llvm/IR/LLVMContext.h"
3222347Spst#include "llvm/Transforms/Utils/Local.h"
3322347Spst#include <algorithm>
3422347Spstusing namespace llvm;
3522347Spst
3659118Skris#define DEBUG_TYPE "prune-eh"
3722347Spst
3822347SpstSTATISTIC(NumRemoved, "Number of invokes removed");
3922347SpstSTATISTIC(NumUnreach, "Number of noreturn calls optimized");
4022347Spst
4122347Spstnamespace {
4222347Spst  struct PruneEH : public CallGraphSCCPass {
4322347Spst    static char ID; // Pass identification, replacement for typeid
4422347Spst    PruneEH() : CallGraphSCCPass(ID) {
4522347Spst      initializePruneEHPass(*PassRegistry::getPassRegistry());
4622347Spst    }
4722347Spst
4822347Spst    // runOnSCC - Analyze the SCC, performing the transformation if possible.
4922347Spst    bool runOnSCC(CallGraphSCC &SCC) override;
5022347Spst
5122347Spst    bool SimplifyFunction(Function *F);
5222347Spst    void DeleteBasicBlock(BasicBlock *BB);
5392906Smarkm  };
5422347Spst}
5522347Spst
5622347Spstchar PruneEH::ID = 0;
5722347SpstINITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
5822347Spst                "Remove unused exception handling info", false, false)
5922347SpstINITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
6022347SpstINITIALIZE_PASS_END(PruneEH, "prune-eh",
6122347Spst                "Remove unused exception handling info", false, false)
6222347Spst
6322347SpstPass *llvm::createPruneEHPass() { return new PruneEH(); }
6422347Spst
6522347Spst
6622347Spstbool PruneEH::runOnSCC(CallGraphSCC &SCC) {
6722347Spst  SmallPtrSet<CallGraphNode *, 8> SCCNodes;
6822347Spst  CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
6922347Spst  bool MadeChange = false;
7022347Spst
7159118Skris  // Fill SCCNodes with the elements of the SCC.  Used for quickly
7222347Spst  // looking up whether a given CallGraphNode is in this SCC.
7359118Skris  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
7459118Skris    SCCNodes.insert(*I);
7559118Skris
7659118Skris  // First pass, scan all of the functions in the SCC, simplifying them
7759118Skris  // according to what we know.
7859118Skris  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
7922347Spst    if (Function *F = (*I)->getFunction())
8022347Spst      MadeChange |= SimplifyFunction(F);
81
82  // Next, check to see if any callees might throw or if there are any external
83  // functions in this SCC: if so, we cannot prune any functions in this SCC.
84  // Definitions that are weak and not declared non-throwing might be
85  // overridden at linktime with something that throws, so assume that.
86  // If this SCC includes the unwind instruction, we KNOW it throws, so
87  // obviously the SCC might throw.
88  //
89  bool SCCMightUnwind = false, SCCMightReturn = false;
90  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end();
91       (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
92    Function *F = (*I)->getFunction();
93    if (!F) {
94      SCCMightUnwind = true;
95      SCCMightReturn = true;
96    } else if (F->isDeclaration() || F->mayBeOverridden()) {
97      SCCMightUnwind |= !F->doesNotThrow();
98      SCCMightReturn |= !F->doesNotReturn();
99    } else {
100      bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
101      bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
102      // Determine if we should scan for InlineAsm in a naked function as it
103      // is the only way to return without a ReturnInst.  Only do this for
104      // no-inline functions as functions which may be inlined cannot
105      // meaningfully return via assembly.
106      bool CheckReturnViaAsm = CheckReturn &&
107                               F->hasFnAttribute(Attribute::Naked) &&
108                               F->hasFnAttribute(Attribute::NoInline);
109
110      if (!CheckUnwind && !CheckReturn)
111        continue;
112
113      for (const BasicBlock &BB : *F) {
114        const TerminatorInst *TI = BB.getTerminator();
115        if (CheckUnwind && TI->mayThrow()) {
116          SCCMightUnwind = true;
117        } else if (CheckReturn && isa<ReturnInst>(TI)) {
118          SCCMightReturn = true;
119        }
120
121        for (const Instruction &I : BB) {
122          if ((!CheckUnwind || SCCMightUnwind) &&
123              (!CheckReturnViaAsm || SCCMightReturn))
124            break;
125
126          // Check to see if this function performs an unwind or calls an
127          // unwinding function.
128          if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
129            bool InstMightUnwind = true;
130            if (const auto *CI = dyn_cast<CallInst>(&I)) {
131              if (Function *Callee = CI->getCalledFunction()) {
132                CallGraphNode *CalleeNode = CG[Callee];
133                // If the callee is outside our current SCC then we may throw
134                // because it might.  If it is inside, do nothing.
135                if (SCCNodes.count(CalleeNode) > 0)
136                  InstMightUnwind = false;
137              }
138            }
139            SCCMightUnwind |= InstMightUnwind;
140          }
141          if (CheckReturnViaAsm && !SCCMightReturn)
142            if (auto ICS = ImmutableCallSite(&I))
143              if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
144                if (IA->hasSideEffects())
145                  SCCMightReturn = true;
146        }
147
148        if (SCCMightUnwind && SCCMightReturn)
149          break;
150      }
151    }
152  }
153
154  // If the SCC doesn't unwind or doesn't throw, note this fact.
155  if (!SCCMightUnwind || !SCCMightReturn)
156    for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
157      Function *F = (*I)->getFunction();
158
159      if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
160        F->addFnAttr(Attribute::NoUnwind);
161        MadeChange = true;
162      }
163
164      if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
165        F->addFnAttr(Attribute::NoReturn);
166        MadeChange = true;
167      }
168    }
169
170  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
171    // Convert any invoke instructions to non-throwing functions in this node
172    // into call instructions with a branch.  This makes the exception blocks
173    // dead.
174    if (Function *F = (*I)->getFunction())
175      MadeChange |= SimplifyFunction(F);
176  }
177
178  return MadeChange;
179}
180
181
182// SimplifyFunction - Given information about callees, simplify the specified
183// function if we have invokes to non-unwinding functions or code after calls to
184// no-return functions.
185bool PruneEH::SimplifyFunction(Function *F) {
186  bool MadeChange = false;
187  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
188    if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
189      if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
190        BasicBlock *UnwindBlock = II->getUnwindDest();
191        removeUnwindEdge(&*BB);
192
193        // If the unwind block is now dead, nuke it.
194        if (pred_empty(UnwindBlock))
195          DeleteBasicBlock(UnwindBlock);  // Delete the new BB.
196
197        ++NumRemoved;
198        MadeChange = true;
199      }
200
201    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
202      if (CallInst *CI = dyn_cast<CallInst>(I++))
203        if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
204          // This call calls a function that cannot return.  Insert an
205          // unreachable instruction after it and simplify the code.  Do this
206          // by splitting the BB, adding the unreachable, then deleting the
207          // new BB.
208          BasicBlock *New = BB->splitBasicBlock(I);
209
210          // Remove the uncond branch and add an unreachable.
211          BB->getInstList().pop_back();
212          new UnreachableInst(BB->getContext(), &*BB);
213
214          DeleteBasicBlock(New);  // Delete the new BB.
215          MadeChange = true;
216          ++NumUnreach;
217          break;
218        }
219  }
220
221  return MadeChange;
222}
223
224/// DeleteBasicBlock - remove the specified basic block from the program,
225/// updating the callgraph to reflect any now-obsolete edges due to calls that
226/// exist in the BB.
227void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
228  assert(pred_empty(BB) && "BB is not dead!");
229  CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
230
231  Instruction *TokenInst = nullptr;
232
233  CallGraphNode *CGN = CG[BB->getParent()];
234  for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
235    --I;
236
237    if (I->getType()->isTokenTy()) {
238      TokenInst = &*I;
239      break;
240    }
241
242    if (auto CS = CallSite (&*I)) {
243      const Function *Callee = CS.getCalledFunction();
244      if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
245        CGN->removeCallEdgeFor(CS);
246      else if (!Callee->isIntrinsic())
247        CGN->removeCallEdgeFor(CS);
248    }
249
250    if (!I->use_empty())
251      I->replaceAllUsesWith(UndefValue::get(I->getType()));
252  }
253
254  if (TokenInst) {
255    if (!isa<TerminatorInst>(TokenInst))
256      changeToUnreachable(TokenInst->getNextNode(), /*UseLLVMTrap=*/false);
257  } else {
258    // Get the list of successors of this block.
259    std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
260
261    for (unsigned i = 0, e = Succs.size(); i != e; ++i)
262      Succs[i]->removePredecessor(BB);
263
264    BB->eraseFromParent();
265  }
266}
267