PruneEH.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. #include "llvm/Transforms/IPO.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.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/LibCallSemantics.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 <algorithm>
  32. using namespace llvm;
  33. #define DEBUG_TYPE "prune-eh"
  34. STATISTIC(NumRemoved, "Number of invokes removed");
  35. STATISTIC(NumUnreach, "Number of noreturn calls optimized");
  36. namespace {
  37. struct PruneEH : public CallGraphSCCPass {
  38. static char ID; // Pass identification, replacement for typeid
  39. PruneEH() : CallGraphSCCPass(ID) {
  40. initializePruneEHPass(*PassRegistry::getPassRegistry());
  41. }
  42. // runOnSCC - Analyze the SCC, performing the transformation if possible.
  43. bool runOnSCC(CallGraphSCC &SCC) override;
  44. bool SimplifyFunction(Function *F);
  45. void DeleteBasicBlock(BasicBlock *BB);
  46. };
  47. }
  48. char PruneEH::ID = 0;
  49. INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
  50. "Remove unused exception handling info", false, false)
  51. INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
  52. INITIALIZE_PASS_END(PruneEH, "prune-eh",
  53. "Remove unused exception handling info", false, false)
  54. Pass *llvm::createPruneEHPass() { return new PruneEH(); }
  55. bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
  56. SmallPtrSet<CallGraphNode *, 8> SCCNodes;
  57. CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
  58. bool MadeChange = false;
  59. // Fill SCCNodes with the elements of the SCC. Used for quickly
  60. // looking up whether a given CallGraphNode is in this SCC.
  61. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
  62. SCCNodes.insert(*I);
  63. // First pass, scan all of the functions in the SCC, simplifying them
  64. // according to what we know.
  65. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
  66. if (Function *F = (*I)->getFunction())
  67. MadeChange |= SimplifyFunction(F);
  68. // Next, check to see if any callees might throw or if there are any external
  69. // functions in this SCC: if so, we cannot prune any functions in this SCC.
  70. // Definitions that are weak and not declared non-throwing might be
  71. // overridden at linktime with something that throws, so assume that.
  72. // If this SCC includes the unwind instruction, we KNOW it throws, so
  73. // obviously the SCC might throw.
  74. //
  75. bool SCCMightUnwind = false, SCCMightReturn = false;
  76. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end();
  77. (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
  78. Function *F = (*I)->getFunction();
  79. if (!F) {
  80. SCCMightUnwind = true;
  81. SCCMightReturn = true;
  82. } else if (F->isDeclaration() || F->mayBeOverridden()) {
  83. SCCMightUnwind |= !F->doesNotThrow();
  84. SCCMightReturn |= !F->doesNotReturn();
  85. } else {
  86. bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
  87. bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
  88. // Determine if we should scan for InlineAsm in a naked function as it
  89. // is the only way to return without a ReturnInst. Only do this for
  90. // no-inline functions as functions which may be inlined cannot
  91. // meaningfully return via assembly.
  92. bool CheckReturnViaAsm = CheckReturn &&
  93. F->hasFnAttribute(Attribute::Naked) &&
  94. F->hasFnAttribute(Attribute::NoInline);
  95. if (!CheckUnwind && !CheckReturn)
  96. continue;
  97. for (const BasicBlock &BB : *F) {
  98. const TerminatorInst *TI = BB.getTerminator();
  99. if (CheckUnwind && TI->mayThrow()) {
  100. SCCMightUnwind = true;
  101. } else if (CheckReturn && isa<ReturnInst>(TI)) {
  102. SCCMightReturn = true;
  103. }
  104. for (const Instruction &I : BB) {
  105. if ((!CheckUnwind || SCCMightUnwind) &&
  106. (!CheckReturnViaAsm || SCCMightReturn))
  107. break;
  108. // Check to see if this function performs an unwind or calls an
  109. // unwinding function.
  110. if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
  111. bool InstMightUnwind = true;
  112. if (const auto *CI = dyn_cast<CallInst>(&I)) {
  113. if (Function *Callee = CI->getCalledFunction()) {
  114. CallGraphNode *CalleeNode = CG[Callee];
  115. // If the callee is outside our current SCC then we may throw
  116. // because it might. If it is inside, do nothing.
  117. if (SCCNodes.count(CalleeNode) > 0)
  118. InstMightUnwind = false;
  119. }
  120. }
  121. SCCMightUnwind |= InstMightUnwind;
  122. }
  123. if (CheckReturnViaAsm && !SCCMightReturn)
  124. if (auto ICS = ImmutableCallSite(&I))
  125. if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
  126. if (IA->hasSideEffects())
  127. SCCMightReturn = true;
  128. }
  129. if (SCCMightUnwind && SCCMightReturn)
  130. break;
  131. }
  132. }
  133. }
  134. // If the SCC doesn't unwind or doesn't throw, note this fact.
  135. if (!SCCMightUnwind || !SCCMightReturn)
  136. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
  137. AttrBuilder NewAttributes;
  138. if (!SCCMightUnwind)
  139. NewAttributes.addAttribute(Attribute::NoUnwind);
  140. if (!SCCMightReturn)
  141. NewAttributes.addAttribute(Attribute::NoReturn);
  142. Function *F = (*I)->getFunction();
  143. const AttributeSet &PAL = F->getAttributes().getFnAttributes();
  144. const AttributeSet &NPAL = AttributeSet::get(
  145. F->getContext(), AttributeSet::FunctionIndex, NewAttributes);
  146. if (PAL != NPAL) {
  147. MadeChange = true;
  148. F->addAttributes(AttributeSet::FunctionIndex, NPAL);
  149. }
  150. }
  151. for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
  152. // Convert any invoke instructions to non-throwing functions in this node
  153. // into call instructions with a branch. This makes the exception blocks
  154. // dead.
  155. if (Function *F = (*I)->getFunction())
  156. MadeChange |= SimplifyFunction(F);
  157. }
  158. return MadeChange;
  159. }
  160. // SimplifyFunction - Given information about callees, simplify the specified
  161. // function if we have invokes to non-unwinding functions or code after calls to
  162. // no-return functions.
  163. bool PruneEH::SimplifyFunction(Function *F) {
  164. bool MadeChange = false;
  165. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
  166. if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
  167. if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
  168. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
  169. // Insert a call instruction before the invoke.
  170. CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
  171. Call->takeName(II);
  172. Call->setCallingConv(II->getCallingConv());
  173. Call->setAttributes(II->getAttributes());
  174. Call->setDebugLoc(II->getDebugLoc());
  175. // Anything that used the value produced by the invoke instruction
  176. // now uses the value produced by the call instruction. Note that we
  177. // do this even for void functions and calls with no uses so that the
  178. // callgraph edge is updated.
  179. II->replaceAllUsesWith(Call);
  180. BasicBlock *UnwindBlock = II->getUnwindDest();
  181. UnwindBlock->removePredecessor(II->getParent());
  182. // Insert a branch to the normal destination right before the
  183. // invoke.
  184. BranchInst::Create(II->getNormalDest(), II);
  185. // Finally, delete the invoke instruction!
  186. BB->getInstList().pop_back();
  187. // If the unwind block is now dead, nuke it.
  188. if (pred_empty(UnwindBlock))
  189. DeleteBasicBlock(UnwindBlock); // Delete the new BB.
  190. ++NumRemoved;
  191. MadeChange = true;
  192. }
  193. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
  194. if (CallInst *CI = dyn_cast<CallInst>(I++))
  195. if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
  196. // This call calls a function that cannot return. Insert an
  197. // unreachable instruction after it and simplify the code. Do this
  198. // by splitting the BB, adding the unreachable, then deleting the
  199. // new BB.
  200. BasicBlock *New = BB->splitBasicBlock(I);
  201. // Remove the uncond branch and add an unreachable.
  202. BB->getInstList().pop_back();
  203. new UnreachableInst(BB->getContext(), BB);
  204. DeleteBasicBlock(New); // Delete the new BB.
  205. MadeChange = true;
  206. ++NumUnreach;
  207. break;
  208. }
  209. }
  210. return MadeChange;
  211. }
  212. /// DeleteBasicBlock - remove the specified basic block from the program,
  213. /// updating the callgraph to reflect any now-obsolete edges due to calls that
  214. /// exist in the BB.
  215. void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
  216. assert(pred_empty(BB) && "BB is not dead!");
  217. CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
  218. CallGraphNode *CGN = CG[BB->getParent()];
  219. for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
  220. --I;
  221. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  222. if (!isa<IntrinsicInst>(I))
  223. CGN->removeCallEdgeFor(CI);
  224. } else if (InvokeInst *II = dyn_cast<InvokeInst>(I))
  225. CGN->removeCallEdgeFor(II);
  226. if (!I->use_empty())
  227. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  228. }
  229. // Get the list of successors of this block.
  230. std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
  231. for (unsigned i = 0, e = Succs.size(); i != e; ++i)
  232. Succs[i]->removePredecessor(BB);
  233. BB->eraseFromParent();
  234. }