SjLjEHPrepare.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. //===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
  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 transformation is designed for use by code generators which use SjLj
  10. // based exception handling.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/SetVector.h"
  14. #include "llvm/ADT/SmallPtrSet.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/Transforms/Utils/Local.h"
  18. #include "llvm/CodeGen/Passes.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DataLayout.h"
  21. #include "llvm/IR/DerivedTypes.h"
  22. #include "llvm/IR/IRBuilder.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Intrinsics.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/Pass.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace llvm;
  30. #define DEBUG_TYPE "sjljehprepare"
  31. STATISTIC(NumInvokes, "Number of invokes replaced");
  32. STATISTIC(NumSpilled, "Number of registers live across unwind edges");
  33. namespace {
  34. class SjLjEHPrepare : public FunctionPass {
  35. Type *doubleUnderDataTy;
  36. Type *doubleUnderJBufTy;
  37. Type *FunctionContextTy;
  38. FunctionCallee RegisterFn;
  39. FunctionCallee UnregisterFn;
  40. Function *BuiltinSetupDispatchFn;
  41. Function *FrameAddrFn;
  42. Function *StackAddrFn;
  43. Function *StackRestoreFn;
  44. Function *LSDAAddrFn;
  45. Function *CallSiteFn;
  46. Function *FuncCtxFn;
  47. AllocaInst *FuncCtx;
  48. public:
  49. static char ID; // Pass identification, replacement for typeid
  50. explicit SjLjEHPrepare() : FunctionPass(ID) {}
  51. bool doInitialization(Module &M) override;
  52. bool runOnFunction(Function &F) override;
  53. void getAnalysisUsage(AnalysisUsage &AU) const override {}
  54. StringRef getPassName() const override {
  55. return "SJLJ Exception Handling preparation";
  56. }
  57. private:
  58. bool setupEntryBlockAndCallSites(Function &F);
  59. void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
  60. Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
  61. void lowerIncomingArguments(Function &F);
  62. void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
  63. void insertCallSiteStore(Instruction *I, int Number);
  64. };
  65. } // end anonymous namespace
  66. char SjLjEHPrepare::ID = 0;
  67. INITIALIZE_PASS(SjLjEHPrepare, DEBUG_TYPE, "Prepare SjLj exceptions",
  68. false, false)
  69. // Public Interface To the SjLjEHPrepare pass.
  70. FunctionPass *llvm::createSjLjEHPreparePass() { return new SjLjEHPrepare(); }
  71. // doInitialization - Set up decalarations and types needed to process
  72. // exceptions.
  73. bool SjLjEHPrepare::doInitialization(Module &M) {
  74. // Build the function context structure.
  75. // builtin_setjmp uses a five word jbuf
  76. Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
  77. Type *Int32Ty = Type::getInt32Ty(M.getContext());
  78. doubleUnderDataTy = ArrayType::get(Int32Ty, 4);
  79. doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
  80. FunctionContextTy = StructType::get(VoidPtrTy, // __prev
  81. Int32Ty, // call_site
  82. doubleUnderDataTy, // __data
  83. VoidPtrTy, // __personality
  84. VoidPtrTy, // __lsda
  85. doubleUnderJBufTy // __jbuf
  86. );
  87. return true;
  88. }
  89. /// insertCallSiteStore - Insert a store of the call-site value to the
  90. /// function context
  91. void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
  92. IRBuilder<> Builder(I);
  93. // Get a reference to the call_site field.
  94. Type *Int32Ty = Type::getInt32Ty(I->getContext());
  95. Value *Zero = ConstantInt::get(Int32Ty, 0);
  96. Value *One = ConstantInt::get(Int32Ty, 1);
  97. Value *Idxs[2] = { Zero, One };
  98. Value *CallSite =
  99. Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
  100. // Insert a store of the call-site number
  101. ConstantInt *CallSiteNoC =
  102. ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
  103. Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
  104. }
  105. /// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until
  106. /// we reach blocks we've already seen.
  107. static void MarkBlocksLiveIn(BasicBlock *BB,
  108. SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
  109. if (!LiveBBs.insert(BB).second)
  110. return; // already been here.
  111. df_iterator_default_set<BasicBlock*> Visited;
  112. for (BasicBlock *B : inverse_depth_first_ext(BB, Visited))
  113. LiveBBs.insert(B);
  114. }
  115. /// substituteLPadValues - Substitute the values returned by the landingpad
  116. /// instruction with those returned by the personality function.
  117. void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
  118. Value *SelVal) {
  119. SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
  120. while (!UseWorkList.empty()) {
  121. Value *Val = UseWorkList.pop_back_val();
  122. auto *EVI = dyn_cast<ExtractValueInst>(Val);
  123. if (!EVI)
  124. continue;
  125. if (EVI->getNumIndices() != 1)
  126. continue;
  127. if (*EVI->idx_begin() == 0)
  128. EVI->replaceAllUsesWith(ExnVal);
  129. else if (*EVI->idx_begin() == 1)
  130. EVI->replaceAllUsesWith(SelVal);
  131. if (EVI->use_empty())
  132. EVI->eraseFromParent();
  133. }
  134. if (LPI->use_empty())
  135. return;
  136. // There are still some uses of LPI. Construct an aggregate with the exception
  137. // values and replace the LPI with that aggregate.
  138. Type *LPadType = LPI->getType();
  139. Value *LPadVal = UndefValue::get(LPadType);
  140. auto *SelI = cast<Instruction>(SelVal);
  141. IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
  142. LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
  143. LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
  144. LPI->replaceAllUsesWith(LPadVal);
  145. }
  146. /// setupFunctionContext - Allocate the function context on the stack and fill
  147. /// it with all of the data that we know at this point.
  148. Value *SjLjEHPrepare::setupFunctionContext(Function &F,
  149. ArrayRef<LandingPadInst *> LPads) {
  150. BasicBlock *EntryBB = &F.front();
  151. // Create an alloca for the incoming jump buffer ptr and the new jump buffer
  152. // that needs to be restored on all exits from the function. This is an alloca
  153. // because the value needs to be added to the global context list.
  154. auto &DL = F.getParent()->getDataLayout();
  155. unsigned Align = DL.getPrefTypeAlignment(FunctionContextTy);
  156. FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(),
  157. nullptr, Align, "fn_context", &EntryBB->front());
  158. // Fill in the function context structure.
  159. for (LandingPadInst *LPI : LPads) {
  160. IRBuilder<> Builder(LPI->getParent(),
  161. LPI->getParent()->getFirstInsertionPt());
  162. // Reference the __data field.
  163. Value *FCData =
  164. Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
  165. // The exception values come back in context->__data[0].
  166. Type *Int32Ty = Type::getInt32Ty(F.getContext());
  167. Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
  168. 0, 0, "exception_gep");
  169. Value *ExnVal = Builder.CreateLoad(Int32Ty, ExceptionAddr, true, "exn_val");
  170. ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
  171. Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
  172. 0, 1, "exn_selector_gep");
  173. Value *SelVal =
  174. Builder.CreateLoad(Int32Ty, SelectorAddr, true, "exn_selector_val");
  175. substituteLPadValues(LPI, ExnVal, SelVal);
  176. }
  177. // Personality function
  178. IRBuilder<> Builder(EntryBB->getTerminator());
  179. Value *PersonalityFn = F.getPersonalityFn();
  180. Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
  181. FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
  182. Builder.CreateStore(
  183. Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
  184. PersonalityFieldPtr, /*isVolatile=*/true);
  185. // LSDA address
  186. Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
  187. Value *LSDAFieldPtr =
  188. Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
  189. Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
  190. return FuncCtx;
  191. }
  192. /// lowerIncomingArguments - To avoid having to handle incoming arguments
  193. /// specially, we lower each arg to a copy instruction in the entry block. This
  194. /// ensures that the argument value itself cannot be live out of the entry
  195. /// block.
  196. void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
  197. BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
  198. while (isa<AllocaInst>(AfterAllocaInsPt) &&
  199. cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
  200. ++AfterAllocaInsPt;
  201. assert(AfterAllocaInsPt != F.front().end());
  202. for (auto &AI : F.args()) {
  203. // Swift error really is a register that we model as memory -- instruction
  204. // selection will perform mem-to-reg for us and spill/reload appropriately
  205. // around calls that clobber it. There is no need to spill this
  206. // value to the stack and doing so would not be allowed.
  207. if (AI.isSwiftError())
  208. continue;
  209. Type *Ty = AI.getType();
  210. // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
  211. Value *TrueValue = ConstantInt::getTrue(F.getContext());
  212. Value *UndefValue = UndefValue::get(Ty);
  213. Instruction *SI = SelectInst::Create(
  214. TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
  215. AI.replaceAllUsesWith(SI);
  216. // Reset the operand, because it was clobbered by the RAUW above.
  217. SI->setOperand(1, &AI);
  218. }
  219. }
  220. /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
  221. /// edge and spill them.
  222. void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
  223. ArrayRef<InvokeInst *> Invokes) {
  224. // Finally, scan the code looking for instructions with bad live ranges.
  225. for (BasicBlock &BB : F) {
  226. for (Instruction &Inst : BB) {
  227. // Ignore obvious cases we don't have to handle. In particular, most
  228. // instructions either have no uses or only have a single use inside the
  229. // current block. Ignore them quickly.
  230. if (Inst.use_empty())
  231. continue;
  232. if (Inst.hasOneUse() &&
  233. cast<Instruction>(Inst.user_back())->getParent() == &BB &&
  234. !isa<PHINode>(Inst.user_back()))
  235. continue;
  236. // If this is an alloca in the entry block, it's not a real register
  237. // value.
  238. if (auto *AI = dyn_cast<AllocaInst>(&Inst))
  239. if (AI->isStaticAlloca())
  240. continue;
  241. // Avoid iterator invalidation by copying users to a temporary vector.
  242. SmallVector<Instruction *, 16> Users;
  243. for (User *U : Inst.users()) {
  244. Instruction *UI = cast<Instruction>(U);
  245. if (UI->getParent() != &BB || isa<PHINode>(UI))
  246. Users.push_back(UI);
  247. }
  248. // Find all of the blocks that this value is live in.
  249. SmallPtrSet<BasicBlock *, 32> LiveBBs;
  250. LiveBBs.insert(&BB);
  251. while (!Users.empty()) {
  252. Instruction *U = Users.pop_back_val();
  253. if (!isa<PHINode>(U)) {
  254. MarkBlocksLiveIn(U->getParent(), LiveBBs);
  255. } else {
  256. // Uses for a PHI node occur in their predecessor block.
  257. PHINode *PN = cast<PHINode>(U);
  258. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  259. if (PN->getIncomingValue(i) == &Inst)
  260. MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
  261. }
  262. }
  263. // Now that we know all of the blocks that this thing is live in, see if
  264. // it includes any of the unwind locations.
  265. bool NeedsSpill = false;
  266. for (InvokeInst *Invoke : Invokes) {
  267. BasicBlock *UnwindBlock = Invoke->getUnwindDest();
  268. if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
  269. LLVM_DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
  270. << UnwindBlock->getName() << "\n");
  271. NeedsSpill = true;
  272. break;
  273. }
  274. }
  275. // If we decided we need a spill, do it.
  276. // FIXME: Spilling this way is overkill, as it forces all uses of
  277. // the value to be reloaded from the stack slot, even those that aren't
  278. // in the unwind blocks. We should be more selective.
  279. if (NeedsSpill) {
  280. DemoteRegToStack(Inst, true);
  281. ++NumSpilled;
  282. }
  283. }
  284. }
  285. // Go through the landing pads and remove any PHIs there.
  286. for (InvokeInst *Invoke : Invokes) {
  287. BasicBlock *UnwindBlock = Invoke->getUnwindDest();
  288. LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
  289. // Place PHIs into a set to avoid invalidating the iterator.
  290. SmallPtrSet<PHINode *, 8> PHIsToDemote;
  291. for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
  292. PHIsToDemote.insert(cast<PHINode>(PN));
  293. if (PHIsToDemote.empty())
  294. continue;
  295. // Demote the PHIs to the stack.
  296. for (PHINode *PN : PHIsToDemote)
  297. DemotePHIToStack(PN);
  298. // Move the landingpad instruction back to the top of the landing pad block.
  299. LPI->moveBefore(&UnwindBlock->front());
  300. }
  301. }
  302. /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
  303. /// the function context and marking the call sites with the appropriate
  304. /// values. These values are used by the DWARF EH emitter.
  305. bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
  306. SmallVector<ReturnInst *, 16> Returns;
  307. SmallVector<InvokeInst *, 16> Invokes;
  308. SmallSetVector<LandingPadInst *, 16> LPads;
  309. // Look through the terminators of the basic blocks to find invokes.
  310. for (BasicBlock &BB : F)
  311. if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
  312. if (Function *Callee = II->getCalledFunction())
  313. if (Callee->getIntrinsicID() == Intrinsic::donothing) {
  314. // Remove the NOP invoke.
  315. BranchInst::Create(II->getNormalDest(), II);
  316. II->eraseFromParent();
  317. continue;
  318. }
  319. Invokes.push_back(II);
  320. LPads.insert(II->getUnwindDest()->getLandingPadInst());
  321. } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  322. Returns.push_back(RI);
  323. }
  324. if (Invokes.empty())
  325. return false;
  326. NumInvokes += Invokes.size();
  327. lowerIncomingArguments(F);
  328. lowerAcrossUnwindEdges(F, Invokes);
  329. Value *FuncCtx =
  330. setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
  331. BasicBlock *EntryBB = &F.front();
  332. IRBuilder<> Builder(EntryBB->getTerminator());
  333. // Get a reference to the jump buffer.
  334. Value *JBufPtr =
  335. Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
  336. // Save the frame pointer.
  337. Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
  338. "jbuf_fp_gep");
  339. Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
  340. Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
  341. // Save the stack pointer.
  342. Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
  343. "jbuf_sp_gep");
  344. Val = Builder.CreateCall(StackAddrFn, {}, "sp");
  345. Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
  346. // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
  347. Builder.CreateCall(BuiltinSetupDispatchFn, {});
  348. // Store a pointer to the function context so that the back-end will know
  349. // where to look for it.
  350. Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
  351. Builder.CreateCall(FuncCtxFn, FuncCtxArg);
  352. // At this point, we are all set up, update the invoke instructions to mark
  353. // their call_site values.
  354. for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
  355. insertCallSiteStore(Invokes[I], I + 1);
  356. ConstantInt *CallSiteNum =
  357. ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
  358. // Record the call site value for the back end so it stays associated with
  359. // the invoke.
  360. CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
  361. }
  362. // Mark call instructions that aren't nounwind as no-action (call_site ==
  363. // -1). Skip the entry block, as prior to then, no function context has been
  364. // created for this function and any unexpected exceptions thrown will go
  365. // directly to the caller's context, which is what we want anyway, so no need
  366. // to do anything here.
  367. for (BasicBlock &BB : F) {
  368. if (&BB == &F.front())
  369. continue;
  370. for (Instruction &I : BB)
  371. if (I.mayThrow())
  372. insertCallSiteStore(&I, -1);
  373. }
  374. // Register the function context and make sure it's known to not throw
  375. CallInst *Register =
  376. CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
  377. Register->setDoesNotThrow();
  378. // Following any allocas not in the entry block, update the saved SP in the
  379. // jmpbuf to the new value.
  380. for (BasicBlock &BB : F) {
  381. if (&BB == &F.front())
  382. continue;
  383. for (Instruction &I : BB) {
  384. if (auto *CI = dyn_cast<CallInst>(&I)) {
  385. if (CI->getCalledFunction() != StackRestoreFn)
  386. continue;
  387. } else if (!isa<AllocaInst>(&I)) {
  388. continue;
  389. }
  390. Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
  391. StackAddr->insertAfter(&I);
  392. Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
  393. StoreStackAddr->insertAfter(StackAddr);
  394. }
  395. }
  396. // Finally, for any returns from this function, if this function contains an
  397. // invoke, add a call to unregister the function context.
  398. for (ReturnInst *Return : Returns)
  399. CallInst::Create(UnregisterFn, FuncCtx, "", Return);
  400. return true;
  401. }
  402. bool SjLjEHPrepare::runOnFunction(Function &F) {
  403. Module &M = *F.getParent();
  404. RegisterFn = M.getOrInsertFunction(
  405. "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
  406. PointerType::getUnqual(FunctionContextTy));
  407. UnregisterFn = M.getOrInsertFunction(
  408. "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
  409. PointerType::getUnqual(FunctionContextTy));
  410. FrameAddrFn = Intrinsic::getDeclaration(
  411. &M, Intrinsic::frameaddress,
  412. {Type::getInt8PtrTy(M.getContext(),
  413. M.getDataLayout().getAllocaAddrSpace())});
  414. StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
  415. StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
  416. BuiltinSetupDispatchFn =
  417. Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
  418. LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
  419. CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
  420. FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
  421. bool Res = setupEntryBlockAndCallSites(F);
  422. return Res;
  423. }