DwarfEHPrepare.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. //===- DwarfEHPrepare - Prepare exception handling for code generation ----===//
  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 pass mulches exception handling code into a form adapted to code
  10. // generation. Required if using dwarf exception handling.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/BitVector.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/ADT/Triple.h"
  17. #include "llvm/Analysis/CFG.h"
  18. #include "llvm/Analysis/DomTreeUpdater.h"
  19. #include "llvm/Analysis/EHPersonalities.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/CodeGen/RuntimeLibcalls.h"
  22. #include "llvm/CodeGen/TargetLowering.h"
  23. #include "llvm/CodeGen/TargetPassConfig.h"
  24. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  25. #include "llvm/IR/BasicBlock.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/Instructions.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/InitializePasses.h"
  34. #include "llvm/Pass.h"
  35. #include "llvm/Support/Casting.h"
  36. #include "llvm/Target/TargetMachine.h"
  37. #include "llvm/Transforms/Utils/Local.h"
  38. #include <cstddef>
  39. using namespace llvm;
  40. #define DEBUG_TYPE "dwarfehprepare"
  41. STATISTIC(NumResumesLowered, "Number of resume calls lowered");
  42. STATISTIC(NumCleanupLandingPadsUnreachable,
  43. "Number of cleanup landing pads found unreachable");
  44. STATISTIC(NumCleanupLandingPadsRemaining,
  45. "Number of cleanup landing pads remaining");
  46. STATISTIC(NumNoUnwind, "Number of functions with nounwind");
  47. STATISTIC(NumUnwind, "Number of functions with unwind");
  48. namespace {
  49. class DwarfEHPrepare {
  50. CodeGenOpt::Level OptLevel;
  51. Function &F;
  52. const TargetLowering &TLI;
  53. DomTreeUpdater *DTU;
  54. const TargetTransformInfo *TTI;
  55. const Triple &TargetTriple;
  56. /// Return the exception object from the value passed into
  57. /// the 'resume' instruction (typically an aggregate). Clean up any dead
  58. /// instructions, including the 'resume' instruction.
  59. Value *GetExceptionObject(ResumeInst *RI);
  60. /// Replace resumes that are not reachable from a cleanup landing pad with
  61. /// unreachable and then simplify those blocks.
  62. size_t
  63. pruneUnreachableResumes(SmallVectorImpl<ResumeInst *> &Resumes,
  64. SmallVectorImpl<LandingPadInst *> &CleanupLPads);
  65. /// Convert the ResumeInsts that are still present
  66. /// into calls to the appropriate _Unwind_Resume function.
  67. bool InsertUnwindResumeCalls();
  68. public:
  69. DwarfEHPrepare(CodeGenOpt::Level OptLevel_, Function &F_,
  70. const TargetLowering &TLI_, DomTreeUpdater *DTU_,
  71. const TargetTransformInfo *TTI_, const Triple &TargetTriple_)
  72. : OptLevel(OptLevel_), F(F_), TLI(TLI_), DTU(DTU_), TTI(TTI_),
  73. TargetTriple(TargetTriple_) {}
  74. bool run();
  75. };
  76. } // namespace
  77. Value *DwarfEHPrepare::GetExceptionObject(ResumeInst *RI) {
  78. Value *V = RI->getOperand(0);
  79. Value *ExnObj = nullptr;
  80. InsertValueInst *SelIVI = dyn_cast<InsertValueInst>(V);
  81. LoadInst *SelLoad = nullptr;
  82. InsertValueInst *ExcIVI = nullptr;
  83. bool EraseIVIs = false;
  84. if (SelIVI) {
  85. if (SelIVI->getNumIndices() == 1 && *SelIVI->idx_begin() == 1) {
  86. ExcIVI = dyn_cast<InsertValueInst>(SelIVI->getOperand(0));
  87. if (ExcIVI && isa<UndefValue>(ExcIVI->getOperand(0)) &&
  88. ExcIVI->getNumIndices() == 1 && *ExcIVI->idx_begin() == 0) {
  89. ExnObj = ExcIVI->getOperand(1);
  90. SelLoad = dyn_cast<LoadInst>(SelIVI->getOperand(1));
  91. EraseIVIs = true;
  92. }
  93. }
  94. }
  95. if (!ExnObj)
  96. ExnObj = ExtractValueInst::Create(RI->getOperand(0), 0, "exn.obj", RI);
  97. RI->eraseFromParent();
  98. if (EraseIVIs) {
  99. if (SelIVI->use_empty())
  100. SelIVI->eraseFromParent();
  101. if (ExcIVI->use_empty())
  102. ExcIVI->eraseFromParent();
  103. if (SelLoad && SelLoad->use_empty())
  104. SelLoad->eraseFromParent();
  105. }
  106. return ExnObj;
  107. }
  108. size_t DwarfEHPrepare::pruneUnreachableResumes(
  109. SmallVectorImpl<ResumeInst *> &Resumes,
  110. SmallVectorImpl<LandingPadInst *> &CleanupLPads) {
  111. assert(DTU && "Should have DomTreeUpdater here.");
  112. BitVector ResumeReachable(Resumes.size());
  113. size_t ResumeIndex = 0;
  114. for (auto *RI : Resumes) {
  115. for (auto *LP : CleanupLPads) {
  116. if (isPotentiallyReachable(LP, RI, nullptr, &DTU->getDomTree())) {
  117. ResumeReachable.set(ResumeIndex);
  118. break;
  119. }
  120. }
  121. ++ResumeIndex;
  122. }
  123. // If everything is reachable, there is no change.
  124. if (ResumeReachable.all())
  125. return Resumes.size();
  126. LLVMContext &Ctx = F.getContext();
  127. // Otherwise, insert unreachable instructions and call simplifycfg.
  128. size_t ResumesLeft = 0;
  129. for (size_t I = 0, E = Resumes.size(); I < E; ++I) {
  130. ResumeInst *RI = Resumes[I];
  131. if (ResumeReachable[I]) {
  132. Resumes[ResumesLeft++] = RI;
  133. } else {
  134. BasicBlock *BB = RI->getParent();
  135. new UnreachableInst(Ctx, RI);
  136. RI->eraseFromParent();
  137. simplifyCFG(BB, *TTI, DTU);
  138. }
  139. }
  140. Resumes.resize(ResumesLeft);
  141. return ResumesLeft;
  142. }
  143. bool DwarfEHPrepare::InsertUnwindResumeCalls() {
  144. SmallVector<ResumeInst *, 16> Resumes;
  145. SmallVector<LandingPadInst *, 16> CleanupLPads;
  146. if (F.doesNotThrow())
  147. NumNoUnwind++;
  148. else
  149. NumUnwind++;
  150. for (BasicBlock &BB : F) {
  151. if (auto *RI = dyn_cast<ResumeInst>(BB.getTerminator()))
  152. Resumes.push_back(RI);
  153. if (auto *LP = BB.getLandingPadInst())
  154. if (LP->isCleanup())
  155. CleanupLPads.push_back(LP);
  156. }
  157. NumCleanupLandingPadsRemaining += CleanupLPads.size();
  158. if (Resumes.empty())
  159. return false;
  160. // Check the personality, don't do anything if it's scope-based.
  161. EHPersonality Pers = classifyEHPersonality(F.getPersonalityFn());
  162. if (isScopedEHPersonality(Pers))
  163. return false;
  164. LLVMContext &Ctx = F.getContext();
  165. size_t ResumesLeft = Resumes.size();
  166. if (OptLevel != CodeGenOpt::None) {
  167. ResumesLeft = pruneUnreachableResumes(Resumes, CleanupLPads);
  168. #if LLVM_ENABLE_STATS
  169. unsigned NumRemainingLPs = 0;
  170. for (BasicBlock &BB : F) {
  171. if (auto *LP = BB.getLandingPadInst())
  172. if (LP->isCleanup())
  173. NumRemainingLPs++;
  174. }
  175. NumCleanupLandingPadsUnreachable += CleanupLPads.size() - NumRemainingLPs;
  176. NumCleanupLandingPadsRemaining -= CleanupLPads.size() - NumRemainingLPs;
  177. #endif
  178. }
  179. if (ResumesLeft == 0)
  180. return true; // We pruned them all.
  181. // RewindFunction - _Unwind_Resume or the target equivalent.
  182. FunctionCallee RewindFunction;
  183. CallingConv::ID RewindFunctionCallingConv;
  184. FunctionType *FTy;
  185. const char *RewindName;
  186. bool DoesRewindFunctionNeedExceptionObject;
  187. if ((Pers == EHPersonality::GNU_CXX || Pers == EHPersonality::GNU_CXX_SjLj) &&
  188. TargetTriple.isTargetEHABICompatible()) {
  189. RewindName = TLI.getLibcallName(RTLIB::CXA_END_CLEANUP);
  190. FTy = FunctionType::get(Type::getVoidTy(Ctx), false);
  191. RewindFunctionCallingConv =
  192. TLI.getLibcallCallingConv(RTLIB::CXA_END_CLEANUP);
  193. DoesRewindFunctionNeedExceptionObject = false;
  194. } else {
  195. RewindName = TLI.getLibcallName(RTLIB::UNWIND_RESUME);
  196. FTy =
  197. FunctionType::get(Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false);
  198. RewindFunctionCallingConv = TLI.getLibcallCallingConv(RTLIB::UNWIND_RESUME);
  199. DoesRewindFunctionNeedExceptionObject = true;
  200. }
  201. RewindFunction = F.getParent()->getOrInsertFunction(RewindName, FTy);
  202. // Create the basic block where the _Unwind_Resume call will live.
  203. if (ResumesLeft == 1) {
  204. // Instead of creating a new BB and PHI node, just append the call to
  205. // _Unwind_Resume to the end of the single resume block.
  206. ResumeInst *RI = Resumes.front();
  207. BasicBlock *UnwindBB = RI->getParent();
  208. Value *ExnObj = GetExceptionObject(RI);
  209. llvm::SmallVector<Value *, 1> RewindFunctionArgs;
  210. if (DoesRewindFunctionNeedExceptionObject)
  211. RewindFunctionArgs.push_back(ExnObj);
  212. // Call the rewind function.
  213. CallInst *CI =
  214. CallInst::Create(RewindFunction, RewindFunctionArgs, "", UnwindBB);
  215. CI->setCallingConv(RewindFunctionCallingConv);
  216. // We never expect _Unwind_Resume to return.
  217. CI->setDoesNotReturn();
  218. new UnreachableInst(Ctx, UnwindBB);
  219. return true;
  220. }
  221. std::vector<DominatorTree::UpdateType> Updates;
  222. Updates.reserve(Resumes.size());
  223. llvm::SmallVector<Value *, 1> RewindFunctionArgs;
  224. BasicBlock *UnwindBB = BasicBlock::Create(Ctx, "unwind_resume", &F);
  225. PHINode *PN = PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesLeft, "exn.obj",
  226. UnwindBB);
  227. // Extract the exception object from the ResumeInst and add it to the PHI node
  228. // that feeds the _Unwind_Resume call.
  229. for (ResumeInst *RI : Resumes) {
  230. BasicBlock *Parent = RI->getParent();
  231. BranchInst::Create(UnwindBB, Parent);
  232. Updates.push_back({DominatorTree::Insert, Parent, UnwindBB});
  233. Value *ExnObj = GetExceptionObject(RI);
  234. PN->addIncoming(ExnObj, Parent);
  235. ++NumResumesLowered;
  236. }
  237. if (DoesRewindFunctionNeedExceptionObject)
  238. RewindFunctionArgs.push_back(PN);
  239. // Call the function.
  240. CallInst *CI =
  241. CallInst::Create(RewindFunction, RewindFunctionArgs, "", UnwindBB);
  242. CI->setCallingConv(RewindFunctionCallingConv);
  243. // We never expect _Unwind_Resume to return.
  244. CI->setDoesNotReturn();
  245. new UnreachableInst(Ctx, UnwindBB);
  246. if (DTU)
  247. DTU->applyUpdates(Updates);
  248. return true;
  249. }
  250. bool DwarfEHPrepare::run() {
  251. bool Changed = InsertUnwindResumeCalls();
  252. return Changed;
  253. }
  254. static bool prepareDwarfEH(CodeGenOpt::Level OptLevel, Function &F,
  255. const TargetLowering &TLI, DominatorTree *DT,
  256. const TargetTransformInfo *TTI,
  257. const Triple &TargetTriple) {
  258. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  259. return DwarfEHPrepare(OptLevel, F, TLI, DT ? &DTU : nullptr, TTI,
  260. TargetTriple)
  261. .run();
  262. }
  263. namespace {
  264. class DwarfEHPrepareLegacyPass : public FunctionPass {
  265. CodeGenOpt::Level OptLevel;
  266. public:
  267. static char ID; // Pass identification, replacement for typeid.
  268. DwarfEHPrepareLegacyPass(CodeGenOpt::Level OptLevel = CodeGenOpt::Default)
  269. : FunctionPass(ID), OptLevel(OptLevel) {}
  270. bool runOnFunction(Function &F) override {
  271. const TargetMachine &TM =
  272. getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
  273. const TargetLowering &TLI = *TM.getSubtargetImpl(F)->getTargetLowering();
  274. DominatorTree *DT = nullptr;
  275. const TargetTransformInfo *TTI = nullptr;
  276. if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
  277. DT = &DTWP->getDomTree();
  278. if (OptLevel != CodeGenOpt::None) {
  279. if (!DT)
  280. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  281. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  282. }
  283. return prepareDwarfEH(OptLevel, F, TLI, DT, TTI, TM.getTargetTriple());
  284. }
  285. void getAnalysisUsage(AnalysisUsage &AU) const override {
  286. AU.addRequired<TargetPassConfig>();
  287. AU.addRequired<TargetTransformInfoWrapperPass>();
  288. if (OptLevel != CodeGenOpt::None) {
  289. AU.addRequired<DominatorTreeWrapperPass>();
  290. AU.addRequired<TargetTransformInfoWrapperPass>();
  291. }
  292. AU.addPreserved<DominatorTreeWrapperPass>();
  293. }
  294. StringRef getPassName() const override {
  295. return "Exception handling preparation";
  296. }
  297. };
  298. } // end anonymous namespace
  299. char DwarfEHPrepareLegacyPass::ID = 0;
  300. INITIALIZE_PASS_BEGIN(DwarfEHPrepareLegacyPass, DEBUG_TYPE,
  301. "Prepare DWARF exceptions", false, false)
  302. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  303. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  304. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  305. INITIALIZE_PASS_END(DwarfEHPrepareLegacyPass, DEBUG_TYPE,
  306. "Prepare DWARF exceptions", false, false)
  307. FunctionPass *llvm::createDwarfEHPass(CodeGenOpt::Level OptLevel) {
  308. return new DwarfEHPrepareLegacyPass(OptLevel);
  309. }