PruneEH.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a simple interprocedural pass which walks the
  10. // call-graph, turning invoke instructions into calls, iff the callee cannot
  11. // throw an exception, and marking functions 'nounwind' if they cannot throw.
  12. // It implements this as a bottom-up traversal of the call-graph.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/CallGraph.h"
  19. #include "llvm/Analysis/CallGraphSCCPass.h"
  20. #include "llvm/Analysis/EHPersonalities.h"
  21. #include "llvm/IR/CFG.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/InlineAsm.h"
  25. #include "llvm/IR/Instructions.h"
  26. #include "llvm/IR/LLVMContext.h"
  27. #include "llvm/InitializePasses.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Transforms/IPO.h"
  30. #include "llvm/Transforms/Utils/CallGraphUpdater.h"
  31. #include "llvm/Transforms/Utils/Local.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. #define DEBUG_TYPE "prune-eh"
  35. STATISTIC(NumRemoved, "Number of invokes removed");
  36. STATISTIC(NumUnreach, "Number of noreturn calls optimized");
  37. namespace {
  38. struct PruneEH : public CallGraphSCCPass {
  39. static char ID; // Pass identification, replacement for typeid
  40. PruneEH() : CallGraphSCCPass(ID) {
  41. initializePruneEHPass(*PassRegistry::getPassRegistry());
  42. }
  43. // runOnSCC - Analyze the SCC, performing the transformation if possible.
  44. bool runOnSCC(CallGraphSCC &SCC) override;
  45. };
  46. }
  47. static bool SimplifyFunction(Function *F, CallGraphUpdater &CGU);
  48. static void DeleteBasicBlock(BasicBlock *BB, CallGraphUpdater &CGU);
  49. char PruneEH::ID = 0;
  50. INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
  51. "Remove unused exception handling info", false, false)
  52. INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
  53. INITIALIZE_PASS_END(PruneEH, "prune-eh",
  54. "Remove unused exception handling info", false, false)
  55. Pass *llvm::createPruneEHPass() { return new PruneEH(); }
  56. static bool runImpl(CallGraphUpdater &CGU, SetVector<Function *> &Functions) {
  57. #ifndef NDEBUG
  58. for (auto *F : Functions)
  59. assert(F && "null Function");
  60. #endif
  61. bool MadeChange = false;
  62. // First pass, scan all of the functions in the SCC, simplifying them
  63. // according to what we know.
  64. for (Function *F : Functions)
  65. MadeChange |= SimplifyFunction(F, CGU);
  66. // Next, check to see if any callees might throw or if there are any external
  67. // functions in this SCC: if so, we cannot prune any functions in this SCC.
  68. // Definitions that are weak and not declared non-throwing might be
  69. // overridden at linktime with something that throws, so assume that.
  70. // If this SCC includes the unwind instruction, we KNOW it throws, so
  71. // obviously the SCC might throw.
  72. //
  73. bool SCCMightUnwind = false, SCCMightReturn = false;
  74. for (Function *F : Functions) {
  75. if (!F->hasExactDefinition()) {
  76. SCCMightUnwind |= !F->doesNotThrow();
  77. SCCMightReturn |= !F->doesNotReturn();
  78. } else {
  79. bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
  80. bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
  81. // Determine if we should scan for InlineAsm in a naked function as it
  82. // is the only way to return without a ReturnInst. Only do this for
  83. // no-inline functions as functions which may be inlined cannot
  84. // meaningfully return via assembly.
  85. bool CheckReturnViaAsm = CheckReturn &&
  86. F->hasFnAttribute(Attribute::Naked) &&
  87. F->hasFnAttribute(Attribute::NoInline);
  88. if (!CheckUnwind && !CheckReturn)
  89. continue;
  90. for (const BasicBlock &BB : *F) {
  91. const Instruction *TI = BB.getTerminator();
  92. if (CheckUnwind && TI->mayThrow()) {
  93. SCCMightUnwind = true;
  94. } else if (CheckReturn && isa<ReturnInst>(TI)) {
  95. SCCMightReturn = true;
  96. }
  97. for (const Instruction &I : BB) {
  98. if ((!CheckUnwind || SCCMightUnwind) &&
  99. (!CheckReturnViaAsm || SCCMightReturn))
  100. break;
  101. // Check to see if this function performs an unwind or calls an
  102. // unwinding function.
  103. if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
  104. bool InstMightUnwind = true;
  105. if (const auto *CI = dyn_cast<CallInst>(&I)) {
  106. if (Function *Callee = CI->getCalledFunction()) {
  107. // If the callee is outside our current SCC then we may throw
  108. // because it might. If it is inside, do nothing.
  109. if (Functions.contains(Callee))
  110. InstMightUnwind = false;
  111. }
  112. }
  113. SCCMightUnwind |= InstMightUnwind;
  114. }
  115. if (CheckReturnViaAsm && !SCCMightReturn)
  116. if (const auto *CB = dyn_cast<CallBase>(&I))
  117. if (const auto *IA = dyn_cast<InlineAsm>(CB->getCalledOperand()))
  118. if (IA->hasSideEffects())
  119. SCCMightReturn = true;
  120. }
  121. }
  122. if (SCCMightUnwind && SCCMightReturn)
  123. break;
  124. }
  125. }
  126. // If the SCC doesn't unwind or doesn't throw, note this fact.
  127. if (!SCCMightUnwind || !SCCMightReturn)
  128. for (Function *F : Functions) {
  129. if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
  130. F->addFnAttr(Attribute::NoUnwind);
  131. MadeChange = true;
  132. }
  133. if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
  134. F->addFnAttr(Attribute::NoReturn);
  135. MadeChange = true;
  136. }
  137. }
  138. for (Function *F : Functions) {
  139. // Convert any invoke instructions to non-throwing functions in this node
  140. // into call instructions with a branch. This makes the exception blocks
  141. // dead.
  142. MadeChange |= SimplifyFunction(F, CGU);
  143. }
  144. return MadeChange;
  145. }
  146. bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
  147. if (skipSCC(SCC))
  148. return false;
  149. SetVector<Function *> Functions;
  150. for (auto &N : SCC) {
  151. if (auto *F = N->getFunction())
  152. Functions.insert(F);
  153. }
  154. CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
  155. CallGraphUpdater CGU;
  156. CGU.initialize(CG, SCC);
  157. return runImpl(CGU, Functions);
  158. }
  159. // SimplifyFunction - Given information about callees, simplify the specified
  160. // function if we have invokes to non-unwinding functions or code after calls to
  161. // no-return functions.
  162. static bool SimplifyFunction(Function *F, CallGraphUpdater &CGU) {
  163. bool MadeChange = false;
  164. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
  165. if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
  166. if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
  167. BasicBlock *UnwindBlock = II->getUnwindDest();
  168. removeUnwindEdge(&*BB);
  169. // If the unwind block is now dead, nuke it.
  170. if (pred_empty(UnwindBlock))
  171. DeleteBasicBlock(UnwindBlock, CGU); // Delete the new BB.
  172. ++NumRemoved;
  173. MadeChange = true;
  174. }
  175. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
  176. if (CallInst *CI = dyn_cast<CallInst>(I++))
  177. if (CI->doesNotReturn() && !CI->isMustTailCall() &&
  178. !isa<UnreachableInst>(I)) {
  179. // This call calls a function that cannot return. Insert an
  180. // unreachable instruction after it and simplify the code. Do this
  181. // by splitting the BB, adding the unreachable, then deleting the
  182. // new BB.
  183. BasicBlock *New = BB->splitBasicBlock(I);
  184. // Remove the uncond branch and add an unreachable.
  185. BB->getInstList().pop_back();
  186. new UnreachableInst(BB->getContext(), &*BB);
  187. DeleteBasicBlock(New, CGU); // Delete the new BB.
  188. MadeChange = true;
  189. ++NumUnreach;
  190. break;
  191. }
  192. }
  193. return MadeChange;
  194. }
  195. /// DeleteBasicBlock - remove the specified basic block from the program,
  196. /// updating the callgraph to reflect any now-obsolete edges due to calls that
  197. /// exist in the BB.
  198. static void DeleteBasicBlock(BasicBlock *BB, CallGraphUpdater &CGU) {
  199. assert(pred_empty(BB) && "BB is not dead!");
  200. Instruction *TokenInst = nullptr;
  201. for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
  202. --I;
  203. if (I->getType()->isTokenTy()) {
  204. TokenInst = &*I;
  205. break;
  206. }
  207. if (auto *Call = dyn_cast<CallBase>(&*I)) {
  208. const Function *Callee = Call->getCalledFunction();
  209. if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
  210. CGU.removeCallSite(*Call);
  211. else if (!Callee->isIntrinsic())
  212. CGU.removeCallSite(*Call);
  213. }
  214. if (!I->use_empty())
  215. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  216. }
  217. if (TokenInst) {
  218. if (!TokenInst->isTerminator())
  219. changeToUnreachable(TokenInst->getNextNode());
  220. } else {
  221. // Get the list of successors of this block.
  222. std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
  223. for (unsigned i = 0, e = Succs.size(); i != e; ++i)
  224. Succs[i]->removePredecessor(BB);
  225. BB->eraseFromParent();
  226. }
  227. }