106f32e7eSjoerg //===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This transformation is designed for use by code generators which use SjLj
1006f32e7eSjoerg // based exception handling.
1106f32e7eSjoerg //
1206f32e7eSjoerg //===----------------------------------------------------------------------===//
1306f32e7eSjoerg 
1406f32e7eSjoerg #include "llvm/ADT/SetVector.h"
1506f32e7eSjoerg #include "llvm/ADT/SmallPtrSet.h"
1606f32e7eSjoerg #include "llvm/ADT/SmallVector.h"
1706f32e7eSjoerg #include "llvm/ADT/Statistic.h"
1806f32e7eSjoerg #include "llvm/CodeGen/Passes.h"
1906f32e7eSjoerg #include "llvm/IR/Constants.h"
2006f32e7eSjoerg #include "llvm/IR/DataLayout.h"
2106f32e7eSjoerg #include "llvm/IR/DerivedTypes.h"
2206f32e7eSjoerg #include "llvm/IR/IRBuilder.h"
2306f32e7eSjoerg #include "llvm/IR/Instructions.h"
2406f32e7eSjoerg #include "llvm/IR/Intrinsics.h"
2506f32e7eSjoerg #include "llvm/IR/Module.h"
26*da58b97aSjoerg #include "llvm/InitializePasses.h"
2706f32e7eSjoerg #include "llvm/Pass.h"
2806f32e7eSjoerg #include "llvm/Support/Debug.h"
2906f32e7eSjoerg #include "llvm/Support/raw_ostream.h"
30*da58b97aSjoerg #include "llvm/Target/TargetMachine.h"
31*da58b97aSjoerg #include "llvm/Transforms/Utils/Local.h"
3206f32e7eSjoerg using namespace llvm;
3306f32e7eSjoerg 
3406f32e7eSjoerg #define DEBUG_TYPE "sjljehprepare"
3506f32e7eSjoerg 
3606f32e7eSjoerg STATISTIC(NumInvokes, "Number of invokes replaced");
3706f32e7eSjoerg STATISTIC(NumSpilled, "Number of registers live across unwind edges");
3806f32e7eSjoerg 
3906f32e7eSjoerg namespace {
4006f32e7eSjoerg class SjLjEHPrepare : public FunctionPass {
41*da58b97aSjoerg   IntegerType *DataTy;
4206f32e7eSjoerg   Type *doubleUnderDataTy;
4306f32e7eSjoerg   Type *doubleUnderJBufTy;
4406f32e7eSjoerg   Type *FunctionContextTy;
4506f32e7eSjoerg   FunctionCallee RegisterFn;
4606f32e7eSjoerg   FunctionCallee UnregisterFn;
4706f32e7eSjoerg   Function *BuiltinSetupDispatchFn;
4806f32e7eSjoerg   Function *FrameAddrFn;
4906f32e7eSjoerg   Function *StackAddrFn;
5006f32e7eSjoerg   Function *StackRestoreFn;
5106f32e7eSjoerg   Function *LSDAAddrFn;
5206f32e7eSjoerg   Function *CallSiteFn;
5306f32e7eSjoerg   Function *FuncCtxFn;
5406f32e7eSjoerg   AllocaInst *FuncCtx;
55*da58b97aSjoerg   const TargetMachine *TM;
5606f32e7eSjoerg 
5706f32e7eSjoerg public:
5806f32e7eSjoerg   static char ID; // Pass identification, replacement for typeid
SjLjEHPrepare(const TargetMachine * TM=nullptr)59*da58b97aSjoerg   explicit SjLjEHPrepare(const TargetMachine *TM = nullptr)
60*da58b97aSjoerg       : FunctionPass(ID), TM(TM) {}
6106f32e7eSjoerg   bool doInitialization(Module &M) override;
6206f32e7eSjoerg   bool runOnFunction(Function &F) override;
6306f32e7eSjoerg 
getAnalysisUsage(AnalysisUsage & AU) const6406f32e7eSjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {}
getPassName() const6506f32e7eSjoerg   StringRef getPassName() const override {
6606f32e7eSjoerg     return "SJLJ Exception Handling preparation";
6706f32e7eSjoerg   }
6806f32e7eSjoerg 
6906f32e7eSjoerg private:
7006f32e7eSjoerg   bool setupEntryBlockAndCallSites(Function &F);
7106f32e7eSjoerg   void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
7206f32e7eSjoerg   Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
7306f32e7eSjoerg   void lowerIncomingArguments(Function &F);
7406f32e7eSjoerg   void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
7506f32e7eSjoerg   void insertCallSiteStore(Instruction *I, int Number);
7606f32e7eSjoerg };
7706f32e7eSjoerg } // end anonymous namespace
7806f32e7eSjoerg 
7906f32e7eSjoerg char SjLjEHPrepare::ID = 0;
8006f32e7eSjoerg INITIALIZE_PASS(SjLjEHPrepare, DEBUG_TYPE, "Prepare SjLj exceptions",
8106f32e7eSjoerg                 false, false)
8206f32e7eSjoerg 
8306f32e7eSjoerg // Public Interface To the SjLjEHPrepare pass.
createSjLjEHPreparePass(const TargetMachine * TM)84*da58b97aSjoerg FunctionPass *llvm::createSjLjEHPreparePass(const TargetMachine *TM) {
85*da58b97aSjoerg   return new SjLjEHPrepare(TM);
86*da58b97aSjoerg }
87*da58b97aSjoerg 
8806f32e7eSjoerg // doInitialization - Set up decalarations and types needed to process
8906f32e7eSjoerg // exceptions.
doInitialization(Module & M)9006f32e7eSjoerg bool SjLjEHPrepare::doInitialization(Module &M) {
9106f32e7eSjoerg   // Build the function context structure.
9206f32e7eSjoerg   // builtin_setjmp uses a five word jbuf
9306f32e7eSjoerg   Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
94*da58b97aSjoerg   unsigned DataBits =
95*da58b97aSjoerg       TM ? TM->getSjLjDataSize() : TargetMachine::DefaultSjLjDataSize;
96*da58b97aSjoerg   DataTy = Type::getIntNTy(M.getContext(), DataBits);
97*da58b97aSjoerg   doubleUnderDataTy = ArrayType::get(DataTy, 4);
9806f32e7eSjoerg   doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
9906f32e7eSjoerg   FunctionContextTy = StructType::get(VoidPtrTy,         // __prev
100*da58b97aSjoerg                                       DataTy,            // call_site
10106f32e7eSjoerg                                       doubleUnderDataTy, // __data
10206f32e7eSjoerg                                       VoidPtrTy,         // __personality
10306f32e7eSjoerg                                       VoidPtrTy,         // __lsda
10406f32e7eSjoerg                                       doubleUnderJBufTy  // __jbuf
10506f32e7eSjoerg   );
10606f32e7eSjoerg 
10706f32e7eSjoerg   return true;
10806f32e7eSjoerg }
10906f32e7eSjoerg 
11006f32e7eSjoerg /// insertCallSiteStore - Insert a store of the call-site value to the
11106f32e7eSjoerg /// function context
insertCallSiteStore(Instruction * I,int Number)11206f32e7eSjoerg void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
11306f32e7eSjoerg   IRBuilder<> Builder(I);
11406f32e7eSjoerg 
11506f32e7eSjoerg   // Get a reference to the call_site field.
11606f32e7eSjoerg   Type *Int32Ty = Type::getInt32Ty(I->getContext());
11706f32e7eSjoerg   Value *Zero = ConstantInt::get(Int32Ty, 0);
11806f32e7eSjoerg   Value *One = ConstantInt::get(Int32Ty, 1);
11906f32e7eSjoerg   Value *Idxs[2] = { Zero, One };
12006f32e7eSjoerg   Value *CallSite =
12106f32e7eSjoerg       Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
12206f32e7eSjoerg 
12306f32e7eSjoerg   // Insert a store of the call-site number
124*da58b97aSjoerg   ConstantInt *CallSiteNoC = ConstantInt::get(DataTy, Number);
12506f32e7eSjoerg   Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
12606f32e7eSjoerg }
12706f32e7eSjoerg 
12806f32e7eSjoerg /// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until
12906f32e7eSjoerg /// we reach blocks we've already seen.
MarkBlocksLiveIn(BasicBlock * BB,SmallPtrSetImpl<BasicBlock * > & LiveBBs)13006f32e7eSjoerg static void MarkBlocksLiveIn(BasicBlock *BB,
13106f32e7eSjoerg                              SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
13206f32e7eSjoerg   if (!LiveBBs.insert(BB).second)
13306f32e7eSjoerg     return; // already been here.
13406f32e7eSjoerg 
13506f32e7eSjoerg   df_iterator_default_set<BasicBlock*> Visited;
13606f32e7eSjoerg 
13706f32e7eSjoerg   for (BasicBlock *B : inverse_depth_first_ext(BB, Visited))
13806f32e7eSjoerg     LiveBBs.insert(B);
13906f32e7eSjoerg }
14006f32e7eSjoerg 
14106f32e7eSjoerg /// substituteLPadValues - Substitute the values returned by the landingpad
14206f32e7eSjoerg /// instruction with those returned by the personality function.
substituteLPadValues(LandingPadInst * LPI,Value * ExnVal,Value * SelVal)14306f32e7eSjoerg void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
14406f32e7eSjoerg                                          Value *SelVal) {
145*da58b97aSjoerg   SmallVector<Value *, 8> UseWorkList(LPI->users());
14606f32e7eSjoerg   while (!UseWorkList.empty()) {
14706f32e7eSjoerg     Value *Val = UseWorkList.pop_back_val();
14806f32e7eSjoerg     auto *EVI = dyn_cast<ExtractValueInst>(Val);
14906f32e7eSjoerg     if (!EVI)
15006f32e7eSjoerg       continue;
15106f32e7eSjoerg     if (EVI->getNumIndices() != 1)
15206f32e7eSjoerg       continue;
15306f32e7eSjoerg     if (*EVI->idx_begin() == 0)
15406f32e7eSjoerg       EVI->replaceAllUsesWith(ExnVal);
15506f32e7eSjoerg     else if (*EVI->idx_begin() == 1)
15606f32e7eSjoerg       EVI->replaceAllUsesWith(SelVal);
15706f32e7eSjoerg     if (EVI->use_empty())
15806f32e7eSjoerg       EVI->eraseFromParent();
15906f32e7eSjoerg   }
16006f32e7eSjoerg 
16106f32e7eSjoerg   if (LPI->use_empty())
16206f32e7eSjoerg     return;
16306f32e7eSjoerg 
16406f32e7eSjoerg   // There are still some uses of LPI. Construct an aggregate with the exception
16506f32e7eSjoerg   // values and replace the LPI with that aggregate.
16606f32e7eSjoerg   Type *LPadType = LPI->getType();
16706f32e7eSjoerg   Value *LPadVal = UndefValue::get(LPadType);
16806f32e7eSjoerg   auto *SelI = cast<Instruction>(SelVal);
16906f32e7eSjoerg   IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
17006f32e7eSjoerg   LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
17106f32e7eSjoerg   LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
17206f32e7eSjoerg 
17306f32e7eSjoerg   LPI->replaceAllUsesWith(LPadVal);
17406f32e7eSjoerg }
17506f32e7eSjoerg 
17606f32e7eSjoerg /// setupFunctionContext - Allocate the function context on the stack and fill
17706f32e7eSjoerg /// it with all of the data that we know at this point.
setupFunctionContext(Function & F,ArrayRef<LandingPadInst * > LPads)17806f32e7eSjoerg Value *SjLjEHPrepare::setupFunctionContext(Function &F,
17906f32e7eSjoerg                                            ArrayRef<LandingPadInst *> LPads) {
18006f32e7eSjoerg   BasicBlock *EntryBB = &F.front();
18106f32e7eSjoerg 
18206f32e7eSjoerg   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
18306f32e7eSjoerg   // that needs to be restored on all exits from the function. This is an alloca
18406f32e7eSjoerg   // because the value needs to be added to the global context list.
18506f32e7eSjoerg   auto &DL = F.getParent()->getDataLayout();
18606f32e7eSjoerg   const Align Alignment(DL.getPrefTypeAlignment(FunctionContextTy));
18706f32e7eSjoerg   FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(), nullptr,
18806f32e7eSjoerg                            Alignment, "fn_context", &EntryBB->front());
18906f32e7eSjoerg 
19006f32e7eSjoerg   // Fill in the function context structure.
19106f32e7eSjoerg   for (LandingPadInst *LPI : LPads) {
19206f32e7eSjoerg     IRBuilder<> Builder(LPI->getParent(),
19306f32e7eSjoerg                         LPI->getParent()->getFirstInsertionPt());
19406f32e7eSjoerg 
19506f32e7eSjoerg     // Reference the __data field.
19606f32e7eSjoerg     Value *FCData =
19706f32e7eSjoerg         Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
19806f32e7eSjoerg 
19906f32e7eSjoerg     // The exception values come back in context->__data[0].
20006f32e7eSjoerg     Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
20106f32e7eSjoerg                                                       0, 0, "exception_gep");
202*da58b97aSjoerg     Value *ExnVal = Builder.CreateLoad(DataTy, ExceptionAddr, true, "exn_val");
20306f32e7eSjoerg     ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
20406f32e7eSjoerg 
20506f32e7eSjoerg     Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
20606f32e7eSjoerg                                                      0, 1, "exn_selector_gep");
20706f32e7eSjoerg     Value *SelVal =
208*da58b97aSjoerg         Builder.CreateLoad(DataTy, SelectorAddr, true, "exn_selector_val");
209*da58b97aSjoerg 
210*da58b97aSjoerg     // SelVal must be Int32Ty, so trunc it
211*da58b97aSjoerg     SelVal = Builder.CreateTrunc(SelVal, Type::getInt32Ty(F.getContext()));
21206f32e7eSjoerg 
21306f32e7eSjoerg     substituteLPadValues(LPI, ExnVal, SelVal);
21406f32e7eSjoerg   }
21506f32e7eSjoerg 
21606f32e7eSjoerg   // Personality function
21706f32e7eSjoerg   IRBuilder<> Builder(EntryBB->getTerminator());
21806f32e7eSjoerg   Value *PersonalityFn = F.getPersonalityFn();
21906f32e7eSjoerg   Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
22006f32e7eSjoerg       FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
22106f32e7eSjoerg   Builder.CreateStore(
22206f32e7eSjoerg       Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
22306f32e7eSjoerg       PersonalityFieldPtr, /*isVolatile=*/true);
22406f32e7eSjoerg 
22506f32e7eSjoerg   // LSDA address
22606f32e7eSjoerg   Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
22706f32e7eSjoerg   Value *LSDAFieldPtr =
22806f32e7eSjoerg       Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
22906f32e7eSjoerg   Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
23006f32e7eSjoerg 
23106f32e7eSjoerg   return FuncCtx;
23206f32e7eSjoerg }
23306f32e7eSjoerg 
23406f32e7eSjoerg /// lowerIncomingArguments - To avoid having to handle incoming arguments
23506f32e7eSjoerg /// specially, we lower each arg to a copy instruction in the entry block. This
23606f32e7eSjoerg /// ensures that the argument value itself cannot be live out of the entry
23706f32e7eSjoerg /// block.
lowerIncomingArguments(Function & F)23806f32e7eSjoerg void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
23906f32e7eSjoerg   BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
24006f32e7eSjoerg   while (isa<AllocaInst>(AfterAllocaInsPt) &&
24106f32e7eSjoerg          cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
24206f32e7eSjoerg     ++AfterAllocaInsPt;
24306f32e7eSjoerg   assert(AfterAllocaInsPt != F.front().end());
24406f32e7eSjoerg 
24506f32e7eSjoerg   for (auto &AI : F.args()) {
24606f32e7eSjoerg     // Swift error really is a register that we model as memory -- instruction
24706f32e7eSjoerg     // selection will perform mem-to-reg for us and spill/reload appropriately
24806f32e7eSjoerg     // around calls that clobber it. There is no need to spill this
24906f32e7eSjoerg     // value to the stack and doing so would not be allowed.
25006f32e7eSjoerg     if (AI.isSwiftError())
25106f32e7eSjoerg       continue;
25206f32e7eSjoerg 
25306f32e7eSjoerg     Type *Ty = AI.getType();
25406f32e7eSjoerg 
25506f32e7eSjoerg     // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
25606f32e7eSjoerg     Value *TrueValue = ConstantInt::getTrue(F.getContext());
25706f32e7eSjoerg     Value *UndefValue = UndefValue::get(Ty);
25806f32e7eSjoerg     Instruction *SI = SelectInst::Create(
25906f32e7eSjoerg         TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
26006f32e7eSjoerg     AI.replaceAllUsesWith(SI);
26106f32e7eSjoerg 
26206f32e7eSjoerg     // Reset the operand, because it  was clobbered by the RAUW above.
26306f32e7eSjoerg     SI->setOperand(1, &AI);
26406f32e7eSjoerg   }
26506f32e7eSjoerg }
26606f32e7eSjoerg 
26706f32e7eSjoerg /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
26806f32e7eSjoerg /// edge and spill them.
lowerAcrossUnwindEdges(Function & F,ArrayRef<InvokeInst * > Invokes)26906f32e7eSjoerg void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
27006f32e7eSjoerg                                            ArrayRef<InvokeInst *> Invokes) {
27106f32e7eSjoerg   // Finally, scan the code looking for instructions with bad live ranges.
27206f32e7eSjoerg   for (BasicBlock &BB : F) {
27306f32e7eSjoerg     for (Instruction &Inst : BB) {
27406f32e7eSjoerg       // Ignore obvious cases we don't have to handle. In particular, most
27506f32e7eSjoerg       // instructions either have no uses or only have a single use inside the
27606f32e7eSjoerg       // current block. Ignore them quickly.
27706f32e7eSjoerg       if (Inst.use_empty())
27806f32e7eSjoerg         continue;
27906f32e7eSjoerg       if (Inst.hasOneUse() &&
28006f32e7eSjoerg           cast<Instruction>(Inst.user_back())->getParent() == &BB &&
28106f32e7eSjoerg           !isa<PHINode>(Inst.user_back()))
28206f32e7eSjoerg         continue;
28306f32e7eSjoerg 
28406f32e7eSjoerg       // If this is an alloca in the entry block, it's not a real register
28506f32e7eSjoerg       // value.
28606f32e7eSjoerg       if (auto *AI = dyn_cast<AllocaInst>(&Inst))
28706f32e7eSjoerg         if (AI->isStaticAlloca())
28806f32e7eSjoerg           continue;
28906f32e7eSjoerg 
29006f32e7eSjoerg       // Avoid iterator invalidation by copying users to a temporary vector.
29106f32e7eSjoerg       SmallVector<Instruction *, 16> Users;
29206f32e7eSjoerg       for (User *U : Inst.users()) {
29306f32e7eSjoerg         Instruction *UI = cast<Instruction>(U);
29406f32e7eSjoerg         if (UI->getParent() != &BB || isa<PHINode>(UI))
29506f32e7eSjoerg           Users.push_back(UI);
29606f32e7eSjoerg       }
29706f32e7eSjoerg 
29806f32e7eSjoerg       // Find all of the blocks that this value is live in.
29906f32e7eSjoerg       SmallPtrSet<BasicBlock *, 32> LiveBBs;
30006f32e7eSjoerg       LiveBBs.insert(&BB);
30106f32e7eSjoerg       while (!Users.empty()) {
30206f32e7eSjoerg         Instruction *U = Users.pop_back_val();
30306f32e7eSjoerg 
30406f32e7eSjoerg         if (!isa<PHINode>(U)) {
30506f32e7eSjoerg           MarkBlocksLiveIn(U->getParent(), LiveBBs);
30606f32e7eSjoerg         } else {
30706f32e7eSjoerg           // Uses for a PHI node occur in their predecessor block.
30806f32e7eSjoerg           PHINode *PN = cast<PHINode>(U);
30906f32e7eSjoerg           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
31006f32e7eSjoerg             if (PN->getIncomingValue(i) == &Inst)
31106f32e7eSjoerg               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
31206f32e7eSjoerg         }
31306f32e7eSjoerg       }
31406f32e7eSjoerg 
31506f32e7eSjoerg       // Now that we know all of the blocks that this thing is live in, see if
31606f32e7eSjoerg       // it includes any of the unwind locations.
31706f32e7eSjoerg       bool NeedsSpill = false;
31806f32e7eSjoerg       for (InvokeInst *Invoke : Invokes) {
31906f32e7eSjoerg         BasicBlock *UnwindBlock = Invoke->getUnwindDest();
32006f32e7eSjoerg         if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
32106f32e7eSjoerg           LLVM_DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
32206f32e7eSjoerg                             << UnwindBlock->getName() << "\n");
32306f32e7eSjoerg           NeedsSpill = true;
32406f32e7eSjoerg           break;
32506f32e7eSjoerg         }
32606f32e7eSjoerg       }
32706f32e7eSjoerg 
32806f32e7eSjoerg       // If we decided we need a spill, do it.
32906f32e7eSjoerg       // FIXME: Spilling this way is overkill, as it forces all uses of
33006f32e7eSjoerg       // the value to be reloaded from the stack slot, even those that aren't
33106f32e7eSjoerg       // in the unwind blocks. We should be more selective.
33206f32e7eSjoerg       if (NeedsSpill) {
33306f32e7eSjoerg         DemoteRegToStack(Inst, true);
33406f32e7eSjoerg         ++NumSpilled;
33506f32e7eSjoerg       }
33606f32e7eSjoerg     }
33706f32e7eSjoerg   }
33806f32e7eSjoerg 
33906f32e7eSjoerg   // Go through the landing pads and remove any PHIs there.
34006f32e7eSjoerg   for (InvokeInst *Invoke : Invokes) {
34106f32e7eSjoerg     BasicBlock *UnwindBlock = Invoke->getUnwindDest();
34206f32e7eSjoerg     LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
34306f32e7eSjoerg 
34406f32e7eSjoerg     // Place PHIs into a set to avoid invalidating the iterator.
34506f32e7eSjoerg     SmallPtrSet<PHINode *, 8> PHIsToDemote;
34606f32e7eSjoerg     for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
34706f32e7eSjoerg       PHIsToDemote.insert(cast<PHINode>(PN));
34806f32e7eSjoerg     if (PHIsToDemote.empty())
34906f32e7eSjoerg       continue;
35006f32e7eSjoerg 
35106f32e7eSjoerg     // Demote the PHIs to the stack.
35206f32e7eSjoerg     for (PHINode *PN : PHIsToDemote)
35306f32e7eSjoerg       DemotePHIToStack(PN);
35406f32e7eSjoerg 
35506f32e7eSjoerg     // Move the landingpad instruction back to the top of the landing pad block.
35606f32e7eSjoerg     LPI->moveBefore(&UnwindBlock->front());
35706f32e7eSjoerg   }
35806f32e7eSjoerg }
35906f32e7eSjoerg 
36006f32e7eSjoerg /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
36106f32e7eSjoerg /// the function context and marking the call sites with the appropriate
36206f32e7eSjoerg /// values. These values are used by the DWARF EH emitter.
setupEntryBlockAndCallSites(Function & F)36306f32e7eSjoerg bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
36406f32e7eSjoerg   SmallVector<ReturnInst *, 16> Returns;
36506f32e7eSjoerg   SmallVector<InvokeInst *, 16> Invokes;
36606f32e7eSjoerg   SmallSetVector<LandingPadInst *, 16> LPads;
36706f32e7eSjoerg 
36806f32e7eSjoerg   // Look through the terminators of the basic blocks to find invokes.
36906f32e7eSjoerg   for (BasicBlock &BB : F)
37006f32e7eSjoerg     if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
37106f32e7eSjoerg       if (Function *Callee = II->getCalledFunction())
37206f32e7eSjoerg         if (Callee->getIntrinsicID() == Intrinsic::donothing) {
37306f32e7eSjoerg           // Remove the NOP invoke.
37406f32e7eSjoerg           BranchInst::Create(II->getNormalDest(), II);
37506f32e7eSjoerg           II->eraseFromParent();
37606f32e7eSjoerg           continue;
37706f32e7eSjoerg         }
37806f32e7eSjoerg 
37906f32e7eSjoerg       Invokes.push_back(II);
38006f32e7eSjoerg       LPads.insert(II->getUnwindDest()->getLandingPadInst());
38106f32e7eSjoerg     } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
38206f32e7eSjoerg       Returns.push_back(RI);
38306f32e7eSjoerg     }
38406f32e7eSjoerg 
38506f32e7eSjoerg   if (Invokes.empty())
38606f32e7eSjoerg     return false;
38706f32e7eSjoerg 
38806f32e7eSjoerg   NumInvokes += Invokes.size();
38906f32e7eSjoerg 
39006f32e7eSjoerg   lowerIncomingArguments(F);
39106f32e7eSjoerg   lowerAcrossUnwindEdges(F, Invokes);
39206f32e7eSjoerg 
39306f32e7eSjoerg   Value *FuncCtx =
39406f32e7eSjoerg       setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
39506f32e7eSjoerg   BasicBlock *EntryBB = &F.front();
39606f32e7eSjoerg   IRBuilder<> Builder(EntryBB->getTerminator());
39706f32e7eSjoerg 
39806f32e7eSjoerg   // Get a reference to the jump buffer.
39906f32e7eSjoerg   Value *JBufPtr =
40006f32e7eSjoerg       Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
40106f32e7eSjoerg 
40206f32e7eSjoerg   // Save the frame pointer.
40306f32e7eSjoerg   Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
40406f32e7eSjoerg                                                "jbuf_fp_gep");
40506f32e7eSjoerg 
40606f32e7eSjoerg   Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
40706f32e7eSjoerg   Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
40806f32e7eSjoerg 
40906f32e7eSjoerg   // Save the stack pointer.
41006f32e7eSjoerg   Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
41106f32e7eSjoerg                                                "jbuf_sp_gep");
41206f32e7eSjoerg 
41306f32e7eSjoerg   Val = Builder.CreateCall(StackAddrFn, {}, "sp");
41406f32e7eSjoerg   Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
41506f32e7eSjoerg 
41606f32e7eSjoerg   // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
41706f32e7eSjoerg   Builder.CreateCall(BuiltinSetupDispatchFn, {});
41806f32e7eSjoerg 
41906f32e7eSjoerg   // Store a pointer to the function context so that the back-end will know
42006f32e7eSjoerg   // where to look for it.
42106f32e7eSjoerg   Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
42206f32e7eSjoerg   Builder.CreateCall(FuncCtxFn, FuncCtxArg);
42306f32e7eSjoerg 
42406f32e7eSjoerg   // At this point, we are all set up, update the invoke instructions to mark
42506f32e7eSjoerg   // their call_site values.
42606f32e7eSjoerg   for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
42706f32e7eSjoerg     insertCallSiteStore(Invokes[I], I + 1);
42806f32e7eSjoerg 
42906f32e7eSjoerg     ConstantInt *CallSiteNum =
43006f32e7eSjoerg         ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
43106f32e7eSjoerg 
43206f32e7eSjoerg     // Record the call site value for the back end so it stays associated with
43306f32e7eSjoerg     // the invoke.
43406f32e7eSjoerg     CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
43506f32e7eSjoerg   }
43606f32e7eSjoerg 
43706f32e7eSjoerg   // Mark call instructions that aren't nounwind as no-action (call_site ==
43806f32e7eSjoerg   // -1). Skip the entry block, as prior to then, no function context has been
43906f32e7eSjoerg   // created for this function and any unexpected exceptions thrown will go
44006f32e7eSjoerg   // directly to the caller's context, which is what we want anyway, so no need
44106f32e7eSjoerg   // to do anything here.
44206f32e7eSjoerg   for (BasicBlock &BB : F) {
44306f32e7eSjoerg     if (&BB == &F.front())
44406f32e7eSjoerg       continue;
44506f32e7eSjoerg     for (Instruction &I : BB)
44606f32e7eSjoerg       if (I.mayThrow())
44706f32e7eSjoerg         insertCallSiteStore(&I, -1);
44806f32e7eSjoerg   }
44906f32e7eSjoerg 
45006f32e7eSjoerg   // Register the function context and make sure it's known to not throw
45106f32e7eSjoerg   CallInst *Register =
45206f32e7eSjoerg       CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
45306f32e7eSjoerg   Register->setDoesNotThrow();
45406f32e7eSjoerg 
45506f32e7eSjoerg   // Following any allocas not in the entry block, update the saved SP in the
45606f32e7eSjoerg   // jmpbuf to the new value.
45706f32e7eSjoerg   for (BasicBlock &BB : F) {
45806f32e7eSjoerg     if (&BB == &F.front())
45906f32e7eSjoerg       continue;
46006f32e7eSjoerg     for (Instruction &I : BB) {
46106f32e7eSjoerg       if (auto *CI = dyn_cast<CallInst>(&I)) {
46206f32e7eSjoerg         if (CI->getCalledFunction() != StackRestoreFn)
46306f32e7eSjoerg           continue;
46406f32e7eSjoerg       } else if (!isa<AllocaInst>(&I)) {
46506f32e7eSjoerg         continue;
46606f32e7eSjoerg       }
46706f32e7eSjoerg       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
46806f32e7eSjoerg       StackAddr->insertAfter(&I);
469*da58b97aSjoerg       new StoreInst(StackAddr, StackPtr, true, StackAddr->getNextNode());
47006f32e7eSjoerg     }
47106f32e7eSjoerg   }
47206f32e7eSjoerg 
47306f32e7eSjoerg   // Finally, for any returns from this function, if this function contains an
47406f32e7eSjoerg   // invoke, add a call to unregister the function context.
47506f32e7eSjoerg   for (ReturnInst *Return : Returns)
47606f32e7eSjoerg     CallInst::Create(UnregisterFn, FuncCtx, "", Return);
47706f32e7eSjoerg 
47806f32e7eSjoerg   return true;
47906f32e7eSjoerg }
48006f32e7eSjoerg 
runOnFunction(Function & F)48106f32e7eSjoerg bool SjLjEHPrepare::runOnFunction(Function &F) {
48206f32e7eSjoerg   Module &M = *F.getParent();
48306f32e7eSjoerg   RegisterFn = M.getOrInsertFunction(
48406f32e7eSjoerg       "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
48506f32e7eSjoerg       PointerType::getUnqual(FunctionContextTy));
48606f32e7eSjoerg   UnregisterFn = M.getOrInsertFunction(
48706f32e7eSjoerg       "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
48806f32e7eSjoerg       PointerType::getUnqual(FunctionContextTy));
48906f32e7eSjoerg   FrameAddrFn = Intrinsic::getDeclaration(
49006f32e7eSjoerg       &M, Intrinsic::frameaddress,
49106f32e7eSjoerg       {Type::getInt8PtrTy(M.getContext(),
49206f32e7eSjoerg                           M.getDataLayout().getAllocaAddrSpace())});
49306f32e7eSjoerg   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
49406f32e7eSjoerg   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
49506f32e7eSjoerg   BuiltinSetupDispatchFn =
49606f32e7eSjoerg     Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
49706f32e7eSjoerg   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
49806f32e7eSjoerg   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
49906f32e7eSjoerg   FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
50006f32e7eSjoerg 
50106f32e7eSjoerg   bool Res = setupEntryBlockAndCallSites(F);
50206f32e7eSjoerg   return Res;
50306f32e7eSjoerg }
504