17330f729Sjoerg //===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This transformation is designed for use by code generators which use SjLj
107330f729Sjoerg // based exception handling.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg
147330f729Sjoerg #include "llvm/ADT/SetVector.h"
157330f729Sjoerg #include "llvm/ADT/SmallPtrSet.h"
167330f729Sjoerg #include "llvm/ADT/SmallVector.h"
177330f729Sjoerg #include "llvm/ADT/Statistic.h"
187330f729Sjoerg #include "llvm/CodeGen/Passes.h"
197330f729Sjoerg #include "llvm/IR/Constants.h"
207330f729Sjoerg #include "llvm/IR/DataLayout.h"
217330f729Sjoerg #include "llvm/IR/DerivedTypes.h"
227330f729Sjoerg #include "llvm/IR/IRBuilder.h"
237330f729Sjoerg #include "llvm/IR/Instructions.h"
247330f729Sjoerg #include "llvm/IR/Intrinsics.h"
257330f729Sjoerg #include "llvm/IR/Module.h"
26*82d56013Sjoerg #include "llvm/InitializePasses.h"
277330f729Sjoerg #include "llvm/Pass.h"
287330f729Sjoerg #include "llvm/Support/Debug.h"
297330f729Sjoerg #include "llvm/Support/raw_ostream.h"
30*82d56013Sjoerg #include "llvm/Target/TargetMachine.h"
31*82d56013Sjoerg #include "llvm/Transforms/Utils/Local.h"
327330f729Sjoerg using namespace llvm;
337330f729Sjoerg
347330f729Sjoerg #define DEBUG_TYPE "sjljehprepare"
357330f729Sjoerg
367330f729Sjoerg STATISTIC(NumInvokes, "Number of invokes replaced");
377330f729Sjoerg STATISTIC(NumSpilled, "Number of registers live across unwind edges");
387330f729Sjoerg
397330f729Sjoerg namespace {
407330f729Sjoerg class SjLjEHPrepare : public FunctionPass {
41*82d56013Sjoerg IntegerType *DataTy;
427330f729Sjoerg Type *doubleUnderDataTy;
437330f729Sjoerg Type *doubleUnderJBufTy;
447330f729Sjoerg Type *FunctionContextTy;
457330f729Sjoerg FunctionCallee RegisterFn;
467330f729Sjoerg FunctionCallee UnregisterFn;
477330f729Sjoerg Function *BuiltinSetupDispatchFn;
487330f729Sjoerg Function *FrameAddrFn;
497330f729Sjoerg Function *StackAddrFn;
507330f729Sjoerg Function *StackRestoreFn;
517330f729Sjoerg Function *LSDAAddrFn;
527330f729Sjoerg Function *CallSiteFn;
537330f729Sjoerg Function *FuncCtxFn;
547330f729Sjoerg AllocaInst *FuncCtx;
55*82d56013Sjoerg const TargetMachine *TM;
567330f729Sjoerg
577330f729Sjoerg public:
587330f729Sjoerg static char ID; // Pass identification, replacement for typeid
SjLjEHPrepare(const TargetMachine * TM=nullptr)59*82d56013Sjoerg explicit SjLjEHPrepare(const TargetMachine *TM = nullptr)
60*82d56013Sjoerg : FunctionPass(ID), TM(TM) {}
617330f729Sjoerg bool doInitialization(Module &M) override;
627330f729Sjoerg bool runOnFunction(Function &F) override;
637330f729Sjoerg
getAnalysisUsage(AnalysisUsage & AU) const647330f729Sjoerg void getAnalysisUsage(AnalysisUsage &AU) const override {}
getPassName() const657330f729Sjoerg StringRef getPassName() const override {
667330f729Sjoerg return "SJLJ Exception Handling preparation";
677330f729Sjoerg }
687330f729Sjoerg
697330f729Sjoerg private:
707330f729Sjoerg bool setupEntryBlockAndCallSites(Function &F);
717330f729Sjoerg void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
727330f729Sjoerg Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
737330f729Sjoerg void lowerIncomingArguments(Function &F);
747330f729Sjoerg void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
757330f729Sjoerg void insertCallSiteStore(Instruction *I, int Number);
767330f729Sjoerg };
777330f729Sjoerg } // end anonymous namespace
787330f729Sjoerg
797330f729Sjoerg char SjLjEHPrepare::ID = 0;
807330f729Sjoerg INITIALIZE_PASS(SjLjEHPrepare, DEBUG_TYPE, "Prepare SjLj exceptions",
817330f729Sjoerg false, false)
827330f729Sjoerg
837330f729Sjoerg // Public Interface To the SjLjEHPrepare pass.
createSjLjEHPreparePass(const TargetMachine * TM)84*82d56013Sjoerg FunctionPass *llvm::createSjLjEHPreparePass(const TargetMachine *TM) {
85*82d56013Sjoerg return new SjLjEHPrepare(TM);
86*82d56013Sjoerg }
87*82d56013Sjoerg
887330f729Sjoerg // doInitialization - Set up decalarations and types needed to process
897330f729Sjoerg // exceptions.
doInitialization(Module & M)907330f729Sjoerg bool SjLjEHPrepare::doInitialization(Module &M) {
917330f729Sjoerg // Build the function context structure.
927330f729Sjoerg // builtin_setjmp uses a five word jbuf
937330f729Sjoerg Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
94*82d56013Sjoerg unsigned DataBits =
95*82d56013Sjoerg TM ? TM->getSjLjDataSize() : TargetMachine::DefaultSjLjDataSize;
96*82d56013Sjoerg DataTy = Type::getIntNTy(M.getContext(), DataBits);
97*82d56013Sjoerg doubleUnderDataTy = ArrayType::get(DataTy, 4);
987330f729Sjoerg doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
997330f729Sjoerg FunctionContextTy = StructType::get(VoidPtrTy, // __prev
100*82d56013Sjoerg DataTy, // call_site
1017330f729Sjoerg doubleUnderDataTy, // __data
1027330f729Sjoerg VoidPtrTy, // __personality
1037330f729Sjoerg VoidPtrTy, // __lsda
1047330f729Sjoerg doubleUnderJBufTy // __jbuf
1057330f729Sjoerg );
1067330f729Sjoerg
1077330f729Sjoerg return true;
1087330f729Sjoerg }
1097330f729Sjoerg
1107330f729Sjoerg /// insertCallSiteStore - Insert a store of the call-site value to the
1117330f729Sjoerg /// function context
insertCallSiteStore(Instruction * I,int Number)1127330f729Sjoerg void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
1137330f729Sjoerg IRBuilder<> Builder(I);
1147330f729Sjoerg
1157330f729Sjoerg // Get a reference to the call_site field.
1167330f729Sjoerg Type *Int32Ty = Type::getInt32Ty(I->getContext());
1177330f729Sjoerg Value *Zero = ConstantInt::get(Int32Ty, 0);
1187330f729Sjoerg Value *One = ConstantInt::get(Int32Ty, 1);
1197330f729Sjoerg Value *Idxs[2] = { Zero, One };
1207330f729Sjoerg Value *CallSite =
1217330f729Sjoerg Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
1227330f729Sjoerg
1237330f729Sjoerg // Insert a store of the call-site number
124*82d56013Sjoerg ConstantInt *CallSiteNoC = ConstantInt::get(DataTy, Number);
1257330f729Sjoerg Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
1267330f729Sjoerg }
1277330f729Sjoerg
1287330f729Sjoerg /// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until
1297330f729Sjoerg /// we reach blocks we've already seen.
MarkBlocksLiveIn(BasicBlock * BB,SmallPtrSetImpl<BasicBlock * > & LiveBBs)1307330f729Sjoerg static void MarkBlocksLiveIn(BasicBlock *BB,
1317330f729Sjoerg SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
1327330f729Sjoerg if (!LiveBBs.insert(BB).second)
1337330f729Sjoerg return; // already been here.
1347330f729Sjoerg
1357330f729Sjoerg df_iterator_default_set<BasicBlock*> Visited;
1367330f729Sjoerg
1377330f729Sjoerg for (BasicBlock *B : inverse_depth_first_ext(BB, Visited))
1387330f729Sjoerg LiveBBs.insert(B);
1397330f729Sjoerg }
1407330f729Sjoerg
1417330f729Sjoerg /// substituteLPadValues - Substitute the values returned by the landingpad
1427330f729Sjoerg /// instruction with those returned by the personality function.
substituteLPadValues(LandingPadInst * LPI,Value * ExnVal,Value * SelVal)1437330f729Sjoerg void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
1447330f729Sjoerg Value *SelVal) {
145*82d56013Sjoerg SmallVector<Value *, 8> UseWorkList(LPI->users());
1467330f729Sjoerg while (!UseWorkList.empty()) {
1477330f729Sjoerg Value *Val = UseWorkList.pop_back_val();
1487330f729Sjoerg auto *EVI = dyn_cast<ExtractValueInst>(Val);
1497330f729Sjoerg if (!EVI)
1507330f729Sjoerg continue;
1517330f729Sjoerg if (EVI->getNumIndices() != 1)
1527330f729Sjoerg continue;
1537330f729Sjoerg if (*EVI->idx_begin() == 0)
1547330f729Sjoerg EVI->replaceAllUsesWith(ExnVal);
1557330f729Sjoerg else if (*EVI->idx_begin() == 1)
1567330f729Sjoerg EVI->replaceAllUsesWith(SelVal);
1577330f729Sjoerg if (EVI->use_empty())
1587330f729Sjoerg EVI->eraseFromParent();
1597330f729Sjoerg }
1607330f729Sjoerg
1617330f729Sjoerg if (LPI->use_empty())
1627330f729Sjoerg return;
1637330f729Sjoerg
1647330f729Sjoerg // There are still some uses of LPI. Construct an aggregate with the exception
1657330f729Sjoerg // values and replace the LPI with that aggregate.
1667330f729Sjoerg Type *LPadType = LPI->getType();
1677330f729Sjoerg Value *LPadVal = UndefValue::get(LPadType);
1687330f729Sjoerg auto *SelI = cast<Instruction>(SelVal);
1697330f729Sjoerg IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
1707330f729Sjoerg LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
1717330f729Sjoerg LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
1727330f729Sjoerg
1737330f729Sjoerg LPI->replaceAllUsesWith(LPadVal);
1747330f729Sjoerg }
1757330f729Sjoerg
1767330f729Sjoerg /// setupFunctionContext - Allocate the function context on the stack and fill
1777330f729Sjoerg /// it with all of the data that we know at this point.
setupFunctionContext(Function & F,ArrayRef<LandingPadInst * > LPads)1787330f729Sjoerg Value *SjLjEHPrepare::setupFunctionContext(Function &F,
1797330f729Sjoerg ArrayRef<LandingPadInst *> LPads) {
1807330f729Sjoerg BasicBlock *EntryBB = &F.front();
1817330f729Sjoerg
1827330f729Sjoerg // Create an alloca for the incoming jump buffer ptr and the new jump buffer
1837330f729Sjoerg // that needs to be restored on all exits from the function. This is an alloca
1847330f729Sjoerg // because the value needs to be added to the global context list.
1857330f729Sjoerg auto &DL = F.getParent()->getDataLayout();
1867330f729Sjoerg const Align Alignment(DL.getPrefTypeAlignment(FunctionContextTy));
1877330f729Sjoerg FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(), nullptr,
1887330f729Sjoerg Alignment, "fn_context", &EntryBB->front());
1897330f729Sjoerg
1907330f729Sjoerg // Fill in the function context structure.
1917330f729Sjoerg for (LandingPadInst *LPI : LPads) {
1927330f729Sjoerg IRBuilder<> Builder(LPI->getParent(),
1937330f729Sjoerg LPI->getParent()->getFirstInsertionPt());
1947330f729Sjoerg
1957330f729Sjoerg // Reference the __data field.
1967330f729Sjoerg Value *FCData =
1977330f729Sjoerg Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
1987330f729Sjoerg
1997330f729Sjoerg // The exception values come back in context->__data[0].
2007330f729Sjoerg Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
2017330f729Sjoerg 0, 0, "exception_gep");
202*82d56013Sjoerg Value *ExnVal = Builder.CreateLoad(DataTy, ExceptionAddr, true, "exn_val");
2037330f729Sjoerg ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
2047330f729Sjoerg
2057330f729Sjoerg Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
2067330f729Sjoerg 0, 1, "exn_selector_gep");
2077330f729Sjoerg Value *SelVal =
208*82d56013Sjoerg Builder.CreateLoad(DataTy, SelectorAddr, true, "exn_selector_val");
209*82d56013Sjoerg
210*82d56013Sjoerg // SelVal must be Int32Ty, so trunc it
211*82d56013Sjoerg SelVal = Builder.CreateTrunc(SelVal, Type::getInt32Ty(F.getContext()));
2127330f729Sjoerg
2137330f729Sjoerg substituteLPadValues(LPI, ExnVal, SelVal);
2147330f729Sjoerg }
2157330f729Sjoerg
2167330f729Sjoerg // Personality function
2177330f729Sjoerg IRBuilder<> Builder(EntryBB->getTerminator());
2187330f729Sjoerg Value *PersonalityFn = F.getPersonalityFn();
2197330f729Sjoerg Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
2207330f729Sjoerg FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
2217330f729Sjoerg Builder.CreateStore(
2227330f729Sjoerg Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
2237330f729Sjoerg PersonalityFieldPtr, /*isVolatile=*/true);
2247330f729Sjoerg
2257330f729Sjoerg // LSDA address
2267330f729Sjoerg Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
2277330f729Sjoerg Value *LSDAFieldPtr =
2287330f729Sjoerg Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
2297330f729Sjoerg Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
2307330f729Sjoerg
2317330f729Sjoerg return FuncCtx;
2327330f729Sjoerg }
2337330f729Sjoerg
2347330f729Sjoerg /// lowerIncomingArguments - To avoid having to handle incoming arguments
2357330f729Sjoerg /// specially, we lower each arg to a copy instruction in the entry block. This
2367330f729Sjoerg /// ensures that the argument value itself cannot be live out of the entry
2377330f729Sjoerg /// block.
lowerIncomingArguments(Function & F)2387330f729Sjoerg void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
2397330f729Sjoerg BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
2407330f729Sjoerg while (isa<AllocaInst>(AfterAllocaInsPt) &&
2417330f729Sjoerg cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
2427330f729Sjoerg ++AfterAllocaInsPt;
2437330f729Sjoerg assert(AfterAllocaInsPt != F.front().end());
2447330f729Sjoerg
2457330f729Sjoerg for (auto &AI : F.args()) {
2467330f729Sjoerg // Swift error really is a register that we model as memory -- instruction
2477330f729Sjoerg // selection will perform mem-to-reg for us and spill/reload appropriately
2487330f729Sjoerg // around calls that clobber it. There is no need to spill this
2497330f729Sjoerg // value to the stack and doing so would not be allowed.
2507330f729Sjoerg if (AI.isSwiftError())
2517330f729Sjoerg continue;
2527330f729Sjoerg
2537330f729Sjoerg Type *Ty = AI.getType();
2547330f729Sjoerg
2557330f729Sjoerg // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
2567330f729Sjoerg Value *TrueValue = ConstantInt::getTrue(F.getContext());
2577330f729Sjoerg Value *UndefValue = UndefValue::get(Ty);
2587330f729Sjoerg Instruction *SI = SelectInst::Create(
2597330f729Sjoerg TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
2607330f729Sjoerg AI.replaceAllUsesWith(SI);
2617330f729Sjoerg
2627330f729Sjoerg // Reset the operand, because it was clobbered by the RAUW above.
2637330f729Sjoerg SI->setOperand(1, &AI);
2647330f729Sjoerg }
2657330f729Sjoerg }
2667330f729Sjoerg
2677330f729Sjoerg /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
2687330f729Sjoerg /// edge and spill them.
lowerAcrossUnwindEdges(Function & F,ArrayRef<InvokeInst * > Invokes)2697330f729Sjoerg void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
2707330f729Sjoerg ArrayRef<InvokeInst *> Invokes) {
2717330f729Sjoerg // Finally, scan the code looking for instructions with bad live ranges.
2727330f729Sjoerg for (BasicBlock &BB : F) {
2737330f729Sjoerg for (Instruction &Inst : BB) {
2747330f729Sjoerg // Ignore obvious cases we don't have to handle. In particular, most
2757330f729Sjoerg // instructions either have no uses or only have a single use inside the
2767330f729Sjoerg // current block. Ignore them quickly.
2777330f729Sjoerg if (Inst.use_empty())
2787330f729Sjoerg continue;
2797330f729Sjoerg if (Inst.hasOneUse() &&
2807330f729Sjoerg cast<Instruction>(Inst.user_back())->getParent() == &BB &&
2817330f729Sjoerg !isa<PHINode>(Inst.user_back()))
2827330f729Sjoerg continue;
2837330f729Sjoerg
2847330f729Sjoerg // If this is an alloca in the entry block, it's not a real register
2857330f729Sjoerg // value.
2867330f729Sjoerg if (auto *AI = dyn_cast<AllocaInst>(&Inst))
2877330f729Sjoerg if (AI->isStaticAlloca())
2887330f729Sjoerg continue;
2897330f729Sjoerg
2907330f729Sjoerg // Avoid iterator invalidation by copying users to a temporary vector.
2917330f729Sjoerg SmallVector<Instruction *, 16> Users;
2927330f729Sjoerg for (User *U : Inst.users()) {
2937330f729Sjoerg Instruction *UI = cast<Instruction>(U);
2947330f729Sjoerg if (UI->getParent() != &BB || isa<PHINode>(UI))
2957330f729Sjoerg Users.push_back(UI);
2967330f729Sjoerg }
2977330f729Sjoerg
2987330f729Sjoerg // Find all of the blocks that this value is live in.
2997330f729Sjoerg SmallPtrSet<BasicBlock *, 32> LiveBBs;
3007330f729Sjoerg LiveBBs.insert(&BB);
3017330f729Sjoerg while (!Users.empty()) {
3027330f729Sjoerg Instruction *U = Users.pop_back_val();
3037330f729Sjoerg
3047330f729Sjoerg if (!isa<PHINode>(U)) {
3057330f729Sjoerg MarkBlocksLiveIn(U->getParent(), LiveBBs);
3067330f729Sjoerg } else {
3077330f729Sjoerg // Uses for a PHI node occur in their predecessor block.
3087330f729Sjoerg PHINode *PN = cast<PHINode>(U);
3097330f729Sjoerg for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3107330f729Sjoerg if (PN->getIncomingValue(i) == &Inst)
3117330f729Sjoerg MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
3127330f729Sjoerg }
3137330f729Sjoerg }
3147330f729Sjoerg
3157330f729Sjoerg // Now that we know all of the blocks that this thing is live in, see if
3167330f729Sjoerg // it includes any of the unwind locations.
3177330f729Sjoerg bool NeedsSpill = false;
3187330f729Sjoerg for (InvokeInst *Invoke : Invokes) {
3197330f729Sjoerg BasicBlock *UnwindBlock = Invoke->getUnwindDest();
3207330f729Sjoerg if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
3217330f729Sjoerg LLVM_DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
3227330f729Sjoerg << UnwindBlock->getName() << "\n");
3237330f729Sjoerg NeedsSpill = true;
3247330f729Sjoerg break;
3257330f729Sjoerg }
3267330f729Sjoerg }
3277330f729Sjoerg
3287330f729Sjoerg // If we decided we need a spill, do it.
3297330f729Sjoerg // FIXME: Spilling this way is overkill, as it forces all uses of
3307330f729Sjoerg // the value to be reloaded from the stack slot, even those that aren't
3317330f729Sjoerg // in the unwind blocks. We should be more selective.
3327330f729Sjoerg if (NeedsSpill) {
3337330f729Sjoerg DemoteRegToStack(Inst, true);
3347330f729Sjoerg ++NumSpilled;
3357330f729Sjoerg }
3367330f729Sjoerg }
3377330f729Sjoerg }
3387330f729Sjoerg
3397330f729Sjoerg // Go through the landing pads and remove any PHIs there.
3407330f729Sjoerg for (InvokeInst *Invoke : Invokes) {
3417330f729Sjoerg BasicBlock *UnwindBlock = Invoke->getUnwindDest();
3427330f729Sjoerg LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
3437330f729Sjoerg
3447330f729Sjoerg // Place PHIs into a set to avoid invalidating the iterator.
3457330f729Sjoerg SmallPtrSet<PHINode *, 8> PHIsToDemote;
3467330f729Sjoerg for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
3477330f729Sjoerg PHIsToDemote.insert(cast<PHINode>(PN));
3487330f729Sjoerg if (PHIsToDemote.empty())
3497330f729Sjoerg continue;
3507330f729Sjoerg
3517330f729Sjoerg // Demote the PHIs to the stack.
3527330f729Sjoerg for (PHINode *PN : PHIsToDemote)
3537330f729Sjoerg DemotePHIToStack(PN);
3547330f729Sjoerg
3557330f729Sjoerg // Move the landingpad instruction back to the top of the landing pad block.
3567330f729Sjoerg LPI->moveBefore(&UnwindBlock->front());
3577330f729Sjoerg }
3587330f729Sjoerg }
3597330f729Sjoerg
3607330f729Sjoerg /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
3617330f729Sjoerg /// the function context and marking the call sites with the appropriate
3627330f729Sjoerg /// values. These values are used by the DWARF EH emitter.
setupEntryBlockAndCallSites(Function & F)3637330f729Sjoerg bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
3647330f729Sjoerg SmallVector<ReturnInst *, 16> Returns;
3657330f729Sjoerg SmallVector<InvokeInst *, 16> Invokes;
3667330f729Sjoerg SmallSetVector<LandingPadInst *, 16> LPads;
3677330f729Sjoerg
3687330f729Sjoerg // Look through the terminators of the basic blocks to find invokes.
3697330f729Sjoerg for (BasicBlock &BB : F)
3707330f729Sjoerg if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
3717330f729Sjoerg if (Function *Callee = II->getCalledFunction())
3727330f729Sjoerg if (Callee->getIntrinsicID() == Intrinsic::donothing) {
3737330f729Sjoerg // Remove the NOP invoke.
3747330f729Sjoerg BranchInst::Create(II->getNormalDest(), II);
3757330f729Sjoerg II->eraseFromParent();
3767330f729Sjoerg continue;
3777330f729Sjoerg }
3787330f729Sjoerg
3797330f729Sjoerg Invokes.push_back(II);
3807330f729Sjoerg LPads.insert(II->getUnwindDest()->getLandingPadInst());
3817330f729Sjoerg } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
3827330f729Sjoerg Returns.push_back(RI);
3837330f729Sjoerg }
3847330f729Sjoerg
3857330f729Sjoerg if (Invokes.empty())
3867330f729Sjoerg return false;
3877330f729Sjoerg
3887330f729Sjoerg NumInvokes += Invokes.size();
3897330f729Sjoerg
3907330f729Sjoerg lowerIncomingArguments(F);
3917330f729Sjoerg lowerAcrossUnwindEdges(F, Invokes);
3927330f729Sjoerg
3937330f729Sjoerg Value *FuncCtx =
3947330f729Sjoerg setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
3957330f729Sjoerg BasicBlock *EntryBB = &F.front();
3967330f729Sjoerg IRBuilder<> Builder(EntryBB->getTerminator());
3977330f729Sjoerg
3987330f729Sjoerg // Get a reference to the jump buffer.
3997330f729Sjoerg Value *JBufPtr =
4007330f729Sjoerg Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
4017330f729Sjoerg
4027330f729Sjoerg // Save the frame pointer.
4037330f729Sjoerg Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
4047330f729Sjoerg "jbuf_fp_gep");
4057330f729Sjoerg
4067330f729Sjoerg Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
4077330f729Sjoerg Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
4087330f729Sjoerg
4097330f729Sjoerg // Save the stack pointer.
4107330f729Sjoerg Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
4117330f729Sjoerg "jbuf_sp_gep");
4127330f729Sjoerg
4137330f729Sjoerg Val = Builder.CreateCall(StackAddrFn, {}, "sp");
4147330f729Sjoerg Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
4157330f729Sjoerg
4167330f729Sjoerg // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
4177330f729Sjoerg Builder.CreateCall(BuiltinSetupDispatchFn, {});
4187330f729Sjoerg
4197330f729Sjoerg // Store a pointer to the function context so that the back-end will know
4207330f729Sjoerg // where to look for it.
4217330f729Sjoerg Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
4227330f729Sjoerg Builder.CreateCall(FuncCtxFn, FuncCtxArg);
4237330f729Sjoerg
4247330f729Sjoerg // At this point, we are all set up, update the invoke instructions to mark
4257330f729Sjoerg // their call_site values.
4267330f729Sjoerg for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
4277330f729Sjoerg insertCallSiteStore(Invokes[I], I + 1);
4287330f729Sjoerg
4297330f729Sjoerg ConstantInt *CallSiteNum =
4307330f729Sjoerg ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
4317330f729Sjoerg
4327330f729Sjoerg // Record the call site value for the back end so it stays associated with
4337330f729Sjoerg // the invoke.
4347330f729Sjoerg CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
4357330f729Sjoerg }
4367330f729Sjoerg
4377330f729Sjoerg // Mark call instructions that aren't nounwind as no-action (call_site ==
4387330f729Sjoerg // -1). Skip the entry block, as prior to then, no function context has been
4397330f729Sjoerg // created for this function and any unexpected exceptions thrown will go
4407330f729Sjoerg // directly to the caller's context, which is what we want anyway, so no need
4417330f729Sjoerg // to do anything here.
4427330f729Sjoerg for (BasicBlock &BB : F) {
4437330f729Sjoerg if (&BB == &F.front())
4447330f729Sjoerg continue;
4457330f729Sjoerg for (Instruction &I : BB)
4467330f729Sjoerg if (I.mayThrow())
4477330f729Sjoerg insertCallSiteStore(&I, -1);
4487330f729Sjoerg }
4497330f729Sjoerg
4507330f729Sjoerg // Register the function context and make sure it's known to not throw
4517330f729Sjoerg CallInst *Register =
4527330f729Sjoerg CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
4537330f729Sjoerg Register->setDoesNotThrow();
4547330f729Sjoerg
4557330f729Sjoerg // Following any allocas not in the entry block, update the saved SP in the
4567330f729Sjoerg // jmpbuf to the new value.
4577330f729Sjoerg for (BasicBlock &BB : F) {
4587330f729Sjoerg if (&BB == &F.front())
4597330f729Sjoerg continue;
4607330f729Sjoerg for (Instruction &I : BB) {
4617330f729Sjoerg if (auto *CI = dyn_cast<CallInst>(&I)) {
4627330f729Sjoerg if (CI->getCalledFunction() != StackRestoreFn)
4637330f729Sjoerg continue;
4647330f729Sjoerg } else if (!isa<AllocaInst>(&I)) {
4657330f729Sjoerg continue;
4667330f729Sjoerg }
4677330f729Sjoerg Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
4687330f729Sjoerg StackAddr->insertAfter(&I);
469*82d56013Sjoerg new StoreInst(StackAddr, StackPtr, true, StackAddr->getNextNode());
4707330f729Sjoerg }
4717330f729Sjoerg }
4727330f729Sjoerg
4737330f729Sjoerg // Finally, for any returns from this function, if this function contains an
4747330f729Sjoerg // invoke, add a call to unregister the function context.
4757330f729Sjoerg for (ReturnInst *Return : Returns)
4767330f729Sjoerg CallInst::Create(UnregisterFn, FuncCtx, "", Return);
4777330f729Sjoerg
4787330f729Sjoerg return true;
4797330f729Sjoerg }
4807330f729Sjoerg
runOnFunction(Function & F)4817330f729Sjoerg bool SjLjEHPrepare::runOnFunction(Function &F) {
4827330f729Sjoerg Module &M = *F.getParent();
4837330f729Sjoerg RegisterFn = M.getOrInsertFunction(
4847330f729Sjoerg "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
4857330f729Sjoerg PointerType::getUnqual(FunctionContextTy));
4867330f729Sjoerg UnregisterFn = M.getOrInsertFunction(
4877330f729Sjoerg "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
4887330f729Sjoerg PointerType::getUnqual(FunctionContextTy));
4897330f729Sjoerg FrameAddrFn = Intrinsic::getDeclaration(
4907330f729Sjoerg &M, Intrinsic::frameaddress,
4917330f729Sjoerg {Type::getInt8PtrTy(M.getContext(),
4927330f729Sjoerg M.getDataLayout().getAllocaAddrSpace())});
4937330f729Sjoerg StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
4947330f729Sjoerg StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
4957330f729Sjoerg BuiltinSetupDispatchFn =
4967330f729Sjoerg Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
4977330f729Sjoerg LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
4987330f729Sjoerg CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
4997330f729Sjoerg FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
5007330f729Sjoerg
5017330f729Sjoerg bool Res = setupEntryBlockAndCallSites(F);
5027330f729Sjoerg return Res;
5037330f729Sjoerg }
504