LLVM  mainline
PruneEH.cpp
Go to the documentation of this file.
00001 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a simple interprocedural pass which walks the
00011 // call-graph, turning invoke instructions into calls, iff the callee cannot
00012 // throw an exception, and marking functions 'nounwind' if they cannot throw.
00013 // It implements this as a bottom-up traversal of the call-graph.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/Transforms/IPO.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/SmallVector.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/Support/raw_ostream.h"
00022 #include "llvm/Analysis/CallGraph.h"
00023 #include "llvm/Analysis/CallGraphSCCPass.h"
00024 #include "llvm/Analysis/EHPersonalities.h"
00025 #include "llvm/IR/CFG.h"
00026 #include "llvm/IR/Constants.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/IR/InlineAsm.h"
00029 #include "llvm/IR/Instructions.h"
00030 #include "llvm/IR/IntrinsicInst.h"
00031 #include "llvm/IR/LLVMContext.h"
00032 #include "llvm/Transforms/Utils/Local.h"
00033 #include <algorithm>
00034 using namespace llvm;
00035 
00036 #define DEBUG_TYPE "prune-eh"
00037 
00038 STATISTIC(NumRemoved, "Number of invokes removed");
00039 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
00040 
00041 namespace {
00042   struct PruneEH : public CallGraphSCCPass {
00043     static char ID; // Pass identification, replacement for typeid
00044     PruneEH() : CallGraphSCCPass(ID) {
00045       initializePruneEHPass(*PassRegistry::getPassRegistry());
00046     }
00047 
00048     // runOnSCC - Analyze the SCC, performing the transformation if possible.
00049     bool runOnSCC(CallGraphSCC &SCC) override;
00050 
00051     bool SimplifyFunction(Function *F);
00052     void DeleteBasicBlock(BasicBlock *BB);
00053   };
00054 }
00055 
00056 char PruneEH::ID = 0;
00057 INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
00058                 "Remove unused exception handling info", false, false)
00059 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
00060 INITIALIZE_PASS_END(PruneEH, "prune-eh",
00061                 "Remove unused exception handling info", false, false)
00062 
00063 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
00064 
00065 
00066 bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
00067   SmallPtrSet<CallGraphNode *, 8> SCCNodes;
00068   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
00069   bool MadeChange = false;
00070 
00071   // Fill SCCNodes with the elements of the SCC.  Used for quickly
00072   // looking up whether a given CallGraphNode is in this SCC.
00073   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
00074     SCCNodes.insert(*I);
00075 
00076   // First pass, scan all of the functions in the SCC, simplifying them
00077   // according to what we know.
00078   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
00079     if (Function *F = (*I)->getFunction())
00080       MadeChange |= SimplifyFunction(F);
00081 
00082   // Next, check to see if any callees might throw or if there are any external
00083   // functions in this SCC: if so, we cannot prune any functions in this SCC.
00084   // Definitions that are weak and not declared non-throwing might be 
00085   // overridden at linktime with something that throws, so assume that.
00086   // If this SCC includes the unwind instruction, we KNOW it throws, so
00087   // obviously the SCC might throw.
00088   //
00089   bool SCCMightUnwind = false, SCCMightReturn = false;
00090   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); 
00091        (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
00092     Function *F = (*I)->getFunction();
00093     if (!F) {
00094       SCCMightUnwind = true;
00095       SCCMightReturn = true;
00096     } else if (F->isDeclaration() || F->mayBeOverridden()) {
00097       SCCMightUnwind |= !F->doesNotThrow();
00098       SCCMightReturn |= !F->doesNotReturn();
00099     } else {
00100       bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
00101       bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
00102       // Determine if we should scan for InlineAsm in a naked function as it
00103       // is the only way to return without a ReturnInst.  Only do this for
00104       // no-inline functions as functions which may be inlined cannot
00105       // meaningfully return via assembly.
00106       bool CheckReturnViaAsm = CheckReturn &&
00107                                F->hasFnAttribute(Attribute::Naked) &&
00108                                F->hasFnAttribute(Attribute::NoInline);
00109 
00110       if (!CheckUnwind && !CheckReturn)
00111         continue;
00112 
00113       for (const BasicBlock &BB : *F) {
00114         const TerminatorInst *TI = BB.getTerminator();
00115         if (CheckUnwind && TI->mayThrow()) {
00116           SCCMightUnwind = true;
00117         } else if (CheckReturn && isa<ReturnInst>(TI)) {
00118           SCCMightReturn = true;
00119         }
00120 
00121         for (const Instruction &I : BB) {
00122           if ((!CheckUnwind || SCCMightUnwind) &&
00123               (!CheckReturnViaAsm || SCCMightReturn))
00124             break;
00125 
00126           // Check to see if this function performs an unwind or calls an
00127           // unwinding function.
00128           if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
00129             bool InstMightUnwind = true;
00130             if (const auto *CI = dyn_cast<CallInst>(&I)) {
00131               if (Function *Callee = CI->getCalledFunction()) {
00132                 CallGraphNode *CalleeNode = CG[Callee];
00133                 // If the callee is outside our current SCC then we may throw
00134                 // because it might.  If it is inside, do nothing.
00135                 if (SCCNodes.count(CalleeNode) > 0)
00136                   InstMightUnwind = false;
00137               }
00138             }
00139             SCCMightUnwind |= InstMightUnwind;
00140           }
00141           if (CheckReturnViaAsm && !SCCMightReturn)
00142             if (auto ICS = ImmutableCallSite(&I))
00143               if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
00144                 if (IA->hasSideEffects())
00145                   SCCMightReturn = true;
00146         }
00147 
00148         if (SCCMightUnwind && SCCMightReturn)
00149           break;
00150       }
00151     }
00152   }
00153 
00154   // If the SCC doesn't unwind or doesn't throw, note this fact.
00155   if (!SCCMightUnwind || !SCCMightReturn)
00156     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00157       Function *F = (*I)->getFunction();
00158 
00159       if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
00160         F->addFnAttr(Attribute::NoUnwind);
00161         MadeChange = true;
00162       }
00163 
00164       if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
00165         F->addFnAttr(Attribute::NoReturn);
00166         MadeChange = true;
00167       }
00168     }
00169 
00170   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00171     // Convert any invoke instructions to non-throwing functions in this node
00172     // into call instructions with a branch.  This makes the exception blocks
00173     // dead.
00174     if (Function *F = (*I)->getFunction())
00175       MadeChange |= SimplifyFunction(F);
00176   }
00177 
00178   return MadeChange;
00179 }
00180 
00181 
00182 // SimplifyFunction - Given information about callees, simplify the specified
00183 // function if we have invokes to non-unwinding functions or code after calls to
00184 // no-return functions.
00185 bool PruneEH::SimplifyFunction(Function *F) {
00186   bool MadeChange = false;
00187   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
00188     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
00189       if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
00190         BasicBlock *UnwindBlock = II->getUnwindDest();
00191         removeUnwindEdge(&*BB);
00192 
00193         // If the unwind block is now dead, nuke it.
00194         if (pred_empty(UnwindBlock))
00195           DeleteBasicBlock(UnwindBlock);  // Delete the new BB.
00196 
00197         ++NumRemoved;
00198         MadeChange = true;
00199       }
00200 
00201     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
00202       if (CallInst *CI = dyn_cast<CallInst>(I++))
00203         if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
00204           // This call calls a function that cannot return.  Insert an
00205           // unreachable instruction after it and simplify the code.  Do this
00206           // by splitting the BB, adding the unreachable, then deleting the
00207           // new BB.
00208           BasicBlock *New = BB->splitBasicBlock(I);
00209 
00210           // Remove the uncond branch and add an unreachable.
00211           BB->getInstList().pop_back();
00212           new UnreachableInst(BB->getContext(), &*BB);
00213 
00214           DeleteBasicBlock(New);  // Delete the new BB.
00215           MadeChange = true;
00216           ++NumUnreach;
00217           break;
00218         }
00219   }
00220 
00221   return MadeChange;
00222 }
00223 
00224 /// DeleteBasicBlock - remove the specified basic block from the program,
00225 /// updating the callgraph to reflect any now-obsolete edges due to calls that
00226 /// exist in the BB.
00227 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
00228   assert(pred_empty(BB) && "BB is not dead!");
00229   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
00230 
00231   Instruction *TokenInst = nullptr;
00232 
00233   CallGraphNode *CGN = CG[BB->getParent()];
00234   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
00235     --I;
00236 
00237     if (I->getType()->isTokenTy()) {
00238       TokenInst = &*I;
00239       break;
00240     }
00241 
00242     if (auto CS = CallSite (&*I)) {
00243       const Function *Callee = CS.getCalledFunction();
00244       if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
00245         CGN->removeCallEdgeFor(CS);
00246       else if (!Callee->isIntrinsic())
00247         CGN->removeCallEdgeFor(CS);
00248     }
00249 
00250     if (!I->use_empty())
00251       I->replaceAllUsesWith(UndefValue::get(I->getType()));
00252   }
00253 
00254   if (TokenInst) {
00255     if (!isa<TerminatorInst>(TokenInst))
00256       changeToUnreachable(TokenInst->getNextNode(), /*UseLLVMTrap=*/false);
00257   } else {
00258     // Get the list of successors of this block.
00259     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
00260 
00261     for (unsigned i = 0, e = Succs.size(); i != e; ++i)
00262       Succs[i]->removePredecessor(BB);
00263 
00264     BB->eraseFromParent();
00265   }
00266 }