Home | History | Annotate | Download | only in CodeGen
      1 //===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
      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 transformation is designed for use by code generators which use SjLj
     11 // based exception handling.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #define DEBUG_TYPE "sjljehprepare"
     16 #include "llvm/Transforms/Scalar.h"
     17 #include "llvm/Constants.h"
     18 #include "llvm/DerivedTypes.h"
     19 #include "llvm/Instructions.h"
     20 #include "llvm/Intrinsics.h"
     21 #include "llvm/LLVMContext.h"
     22 #include "llvm/Module.h"
     23 #include "llvm/Pass.h"
     24 #include "llvm/CodeGen/Passes.h"
     25 #include "llvm/Target/TargetData.h"
     26 #include "llvm/Target/TargetLowering.h"
     27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     28 #include "llvm/Transforms/Utils/Local.h"
     29 #include "llvm/Support/CommandLine.h"
     30 #include "llvm/Support/Debug.h"
     31 #include "llvm/Support/IRBuilder.h"
     32 #include "llvm/ADT/DenseMap.h"
     33 #include "llvm/ADT/SmallVector.h"
     34 #include "llvm/ADT/Statistic.h"
     35 #include <set>
     36 using namespace llvm;
     37 
     38 static cl::opt<bool> DisableOldSjLjEH("disable-old-sjlj-eh", cl::Hidden,
     39     cl::desc("Disable the old SjLj EH preparation pass"));
     40 
     41 STATISTIC(NumInvokes, "Number of invokes replaced");
     42 STATISTIC(NumUnwinds, "Number of unwinds replaced");
     43 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
     44 
     45 namespace {
     46   class SjLjEHPass : public FunctionPass {
     47     const TargetLowering *TLI;
     48     Type *FunctionContextTy;
     49     Constant *RegisterFn;
     50     Constant *UnregisterFn;
     51     Constant *BuiltinSetjmpFn;
     52     Constant *FrameAddrFn;
     53     Constant *StackAddrFn;
     54     Constant *StackRestoreFn;
     55     Constant *LSDAAddrFn;
     56     Value *PersonalityFn;
     57     Constant *SelectorFn;
     58     Constant *ExceptionFn;
     59     Constant *CallSiteFn;
     60     Constant *DispatchSetupFn;
     61     Constant *FuncCtxFn;
     62     Value *CallSite;
     63     DenseMap<InvokeInst*, BasicBlock*> LPadSuccMap;
     64   public:
     65     static char ID; // Pass identification, replacement for typeid
     66     explicit SjLjEHPass(const TargetLowering *tli = NULL)
     67       : FunctionPass(ID), TLI(tli) { }
     68     bool doInitialization(Module &M);
     69     bool runOnFunction(Function &F);
     70 
     71     virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
     72     const char *getPassName() const {
     73       return "SJLJ Exception Handling preparation";
     74     }
     75 
     76   private:
     77     bool setupEntryBlockAndCallSites(Function &F);
     78     Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
     79     void lowerIncomingArguments(Function &F);
     80     void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
     81 
     82     void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
     83     void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
     84                             SwitchInst *CatchSwitch);
     85     void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
     86     void splitLandingPad(InvokeInst *II);
     87     bool insertSjLjEHSupport(Function &F);
     88   };
     89 } // end anonymous namespace
     90 
     91 char SjLjEHPass::ID = 0;
     92 
     93 // Public Interface To the SjLjEHPass pass.
     94 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
     95   return new SjLjEHPass(TLI);
     96 }
     97 // doInitialization - Set up decalarations and types needed to process
     98 // exceptions.
     99 bool SjLjEHPass::doInitialization(Module &M) {
    100   // Build the function context structure.
    101   // builtin_setjmp uses a five word jbuf
    102   Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
    103   Type *Int32Ty = Type::getInt32Ty(M.getContext());
    104   FunctionContextTy =
    105     StructType::get(VoidPtrTy,                        // __prev
    106                     Int32Ty,                          // call_site
    107                     ArrayType::get(Int32Ty, 4),       // __data
    108                     VoidPtrTy,                        // __personality
    109                     VoidPtrTy,                        // __lsda
    110                     ArrayType::get(VoidPtrTy, 5),     // __jbuf
    111                     NULL);
    112   RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
    113                                      Type::getVoidTy(M.getContext()),
    114                                      PointerType::getUnqual(FunctionContextTy),
    115                                      (Type *)0);
    116   UnregisterFn =
    117     M.getOrInsertFunction("_Unwind_SjLj_Unregister",
    118                           Type::getVoidTy(M.getContext()),
    119                           PointerType::getUnqual(FunctionContextTy),
    120                           (Type *)0);
    121   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
    122   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
    123   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
    124   BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
    125   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
    126   SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
    127   ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
    128   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
    129   DispatchSetupFn
    130     = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
    131   FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
    132   PersonalityFn = 0;
    133 
    134   return true;
    135 }
    136 
    137 /// insertCallSiteStore - Insert a store of the call-site value to the
    138 /// function context
    139 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
    140                                      Value *CallSite) {
    141   ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
    142                                               Number);
    143   // Insert a store of the call-site number
    144   new StoreInst(CallSiteNoC, CallSite, true, I);  // volatile
    145 }
    146 
    147 /// splitLandingPad - Split a landing pad. This takes considerable care because
    148 /// of PHIs and other nasties. The problem is that the jump table needs to jump
    149 /// to the landing pad block. However, the landing pad block can be jumped to
    150 /// only by an invoke instruction. So we clone the landingpad instruction into
    151 /// its own basic block, have the invoke jump to there. The landingpad
    152 /// instruction's basic block's successor is now the target for the jump table.
    153 ///
    154 /// But because of PHI nodes, we need to create another basic block for the jump
    155 /// table to jump to. This is definitely a hack, because the values for the PHI
    156 /// nodes may not be defined on the edge from the jump table. But that's okay,
    157 /// because the jump table is simply a construct to mimic what is happening in
    158 /// the CFG. So the values are mysteriously there, even though there is no value
    159 /// for the PHI from the jump table's edge (hence calling this a hack).
    160 void SjLjEHPass::splitLandingPad(InvokeInst *II) {
    161   SmallVector<BasicBlock*, 2> NewBBs;
    162   SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
    163                               ".1", ".2", this, NewBBs);
    164 
    165   // Create an empty block so that the jump table has something to jump to
    166   // which doesn't have any PHI nodes.
    167   BasicBlock *LPad = NewBBs[0];
    168   BasicBlock *Succ = *succ_begin(LPad);
    169   BasicBlock *JumpTo = BasicBlock::Create(II->getContext(), "jt.land",
    170                                           LPad->getParent(), Succ);
    171   LPad->getTerminator()->eraseFromParent();
    172   BranchInst::Create(JumpTo, LPad);
    173   BranchInst::Create(Succ, JumpTo);
    174   LPadSuccMap[II] = JumpTo;
    175 
    176   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
    177     PHINode *PN = cast<PHINode>(I);
    178     Value *Val = PN->removeIncomingValue(LPad, false);
    179     PN->addIncoming(Val, JumpTo);
    180   }
    181 }
    182 
    183 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
    184 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
    185                                     Value *CallSite,
    186                                     SwitchInst *CatchSwitch) {
    187   ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
    188                                               InvokeNo);
    189   // The runtime comes back to the dispatcher with the call_site - 1 in
    190   // the context. Odd, but there it is.
    191   ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
    192                                              InvokeNo - 1);
    193 
    194   // If the unwind edge has phi nodes, split the edge.
    195   if (isa<PHINode>(II->getUnwindDest()->begin())) {
    196     // FIXME: New EH - This if-condition will be always true in the new scheme.
    197     if (II->getUnwindDest()->isLandingPad())
    198       splitLandingPad(II);
    199     else
    200       SplitCriticalEdge(II, 1, this);
    201 
    202     // If there are any phi nodes left, they must have a single predecessor.
    203     while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
    204       PN->replaceAllUsesWith(PN->getIncomingValue(0));
    205       PN->eraseFromParent();
    206     }
    207   }
    208 
    209   // Insert the store of the call site value
    210   insertCallSiteStore(II, InvokeNo, CallSite);
    211 
    212   // Record the call site value for the back end so it stays associated with
    213   // the invoke.
    214   CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
    215 
    216   // Add a switch case to our unwind block.
    217   if (BasicBlock *SuccBB = LPadSuccMap[II]) {
    218     CatchSwitch->addCase(SwitchValC, SuccBB);
    219   } else {
    220     CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
    221   }
    222 
    223   // We still want this to look like an invoke so we emit the LSDA properly,
    224   // so we don't transform the invoke into a call here.
    225 }
    226 
    227 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
    228 /// we reach blocks we've already seen.
    229 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
    230   if (!LiveBBs.insert(BB).second) return; // already been here.
    231 
    232   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
    233     MarkBlocksLiveIn(*PI, LiveBBs);
    234 }
    235 
    236 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
    237 /// we spill into a stack location, guaranteeing that there is nothing live
    238 /// across the unwind edge.  This process also splits all critical edges
    239 /// coming out of invoke's.
    240 /// FIXME: Move this function to a common utility file (Local.cpp?) so
    241 /// both SjLj and LowerInvoke can use it.
    242 void SjLjEHPass::
    243 splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
    244   // First step, split all critical edges from invoke instructions.
    245   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
    246     InvokeInst *II = Invokes[i];
    247     SplitCriticalEdge(II, 0, this);
    248 
    249     // FIXME: New EH - This if-condition will be always true in the new scheme.
    250     if (II->getUnwindDest()->isLandingPad())
    251       splitLandingPad(II);
    252     else
    253       SplitCriticalEdge(II, 1, this);
    254 
    255     assert(!isa<PHINode>(II->getNormalDest()) &&
    256            !isa<PHINode>(II->getUnwindDest()) &&
    257            "Critical edge splitting left single entry phi nodes?");
    258   }
    259 
    260   Function *F = Invokes.back()->getParent()->getParent();
    261 
    262   // To avoid having to handle incoming arguments specially, we lower each arg
    263   // to a copy instruction in the entry block.  This ensures that the argument
    264   // value itself cannot be live across the entry block.
    265   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
    266   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
    267         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
    268     ++AfterAllocaInsertPt;
    269   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
    270        AI != E; ++AI) {
    271     Type *Ty = AI->getType();
    272     // Aggregate types can't be cast, but are legal argument types, so we have
    273     // to handle them differently. We use an extract/insert pair as a
    274     // lightweight method to achieve the same goal.
    275     if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
    276       Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
    277       Instruction *NI = InsertValueInst::Create(AI, EI, 0);
    278       NI->insertAfter(EI);
    279       AI->replaceAllUsesWith(NI);
    280       // Set the operand of the instructions back to the AllocaInst.
    281       EI->setOperand(0, AI);
    282       NI->setOperand(0, AI);
    283     } else {
    284       // This is always a no-op cast because we're casting AI to AI->getType()
    285       // so src and destination types are identical. BitCast is the only
    286       // possibility.
    287       CastInst *NC = new BitCastInst(
    288         AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
    289       AI->replaceAllUsesWith(NC);
    290       // Set the operand of the cast instruction back to the AllocaInst.
    291       // Normally it's forbidden to replace a CastInst's operand because it
    292       // could cause the opcode to reflect an illegal conversion. However,
    293       // we're replacing it here with the same value it was constructed with.
    294       // We do this because the above replaceAllUsesWith() clobbered the
    295       // operand, but we want this one to remain.
    296       NC->setOperand(0, AI);
    297     }
    298   }
    299 
    300   // Finally, scan the code looking for instructions with bad live ranges.
    301   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
    302     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
    303       // Ignore obvious cases we don't have to handle.  In particular, most
    304       // instructions either have no uses or only have a single use inside the
    305       // current block.  Ignore them quickly.
    306       Instruction *Inst = II;
    307       if (Inst->use_empty()) continue;
    308       if (Inst->hasOneUse() &&
    309           cast<Instruction>(Inst->use_back())->getParent() == BB &&
    310           !isa<PHINode>(Inst->use_back())) continue;
    311 
    312       // If this is an alloca in the entry block, it's not a real register
    313       // value.
    314       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
    315         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
    316           continue;
    317 
    318       // Avoid iterator invalidation by copying users to a temporary vector.
    319       SmallVector<Instruction*,16> Users;
    320       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
    321            UI != E; ++UI) {
    322         Instruction *User = cast<Instruction>(*UI);
    323         if (User->getParent() != BB || isa<PHINode>(User))
    324           Users.push_back(User);
    325       }
    326 
    327       // Find all of the blocks that this value is live in.
    328       std::set<BasicBlock*> LiveBBs;
    329       LiveBBs.insert(Inst->getParent());
    330       while (!Users.empty()) {
    331         Instruction *U = Users.back();
    332         Users.pop_back();
    333 
    334         if (!isa<PHINode>(U)) {
    335           MarkBlocksLiveIn(U->getParent(), LiveBBs);
    336         } else {
    337           // Uses for a PHI node occur in their predecessor block.
    338           PHINode *PN = cast<PHINode>(U);
    339           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    340             if (PN->getIncomingValue(i) == Inst)
    341               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
    342         }
    343       }
    344 
    345       // Now that we know all of the blocks that this thing is live in, see if
    346       // it includes any of the unwind locations.
    347       bool NeedsSpill = false;
    348       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
    349         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
    350         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock))
    351           NeedsSpill = true;
    352       }
    353 
    354       // If we decided we need a spill, do it.
    355       // FIXME: Spilling this way is overkill, as it forces all uses of
    356       // the value to be reloaded from the stack slot, even those that aren't
    357       // in the unwind blocks. We should be more selective.
    358       if (NeedsSpill) {
    359         ++NumSpilled;
    360         DemoteRegToStack(*Inst, true);
    361       }
    362     }
    363 }
    364 
    365 /// CreateLandingPadLoad - Load the exception handling values and insert them
    366 /// into a structure.
    367 static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
    368                                          Value *SelAddr,
    369                                          BasicBlock::iterator InsertPt) {
    370   Value *Exn = new LoadInst(ExnAddr, "exn", false,
    371                             InsertPt);
    372   Type *Ty = Type::getInt8PtrTy(F.getContext());
    373   Exn = CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
    374   Value *Sel = new LoadInst(SelAddr, "sel", false, InsertPt);
    375 
    376   Ty = StructType::get(Exn->getType(), Sel->getType(), NULL);
    377   InsertValueInst *LPadVal = InsertValueInst::Create(llvm::UndefValue::get(Ty),
    378                                                      Exn, 0,
    379                                                      "lpad.val", InsertPt);
    380   return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
    381 }
    382 
    383 /// ReplaceLandingPadVal - Replace the landingpad instruction's value with a
    384 /// load from the stored values (via CreateLandingPadLoad). This looks through
    385 /// PHI nodes, and removes them if they are dead.
    386 static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *ExnAddr,
    387                                  Value *SelAddr) {
    388   if (Inst->use_empty()) return;
    389 
    390   while (!Inst->use_empty()) {
    391     Instruction *I = cast<Instruction>(Inst->use_back());
    392 
    393     if (PHINode *PN = dyn_cast<PHINode>(I)) {
    394       ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
    395       if (PN->use_empty()) PN->eraseFromParent();
    396       continue;
    397     }
    398 
    399     I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I));
    400   }
    401 }
    402 
    403 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
    404   SmallVector<ReturnInst*,16> Returns;
    405   SmallVector<UnwindInst*,16> Unwinds;
    406   SmallVector<InvokeInst*,16> Invokes;
    407 
    408   // Look through the terminators of the basic blocks to find invokes, returns
    409   // and unwinds.
    410   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
    411     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
    412       // Remember all return instructions in case we insert an invoke into this
    413       // function.
    414       Returns.push_back(RI);
    415     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
    416       Invokes.push_back(II);
    417     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
    418       Unwinds.push_back(UI);
    419     }
    420   }
    421 
    422   NumInvokes += Invokes.size();
    423   NumUnwinds += Unwinds.size();
    424 
    425   // If we don't have any invokes, there's nothing to do.
    426   if (Invokes.empty()) return false;
    427 
    428   // Find the eh.selector.*, eh.exception and alloca calls.
    429   //
    430   // Remember any allocas() that aren't in the entry block, as the
    431   // jmpbuf saved SP will need to be updated for them.
    432   //
    433   // We'll use the first eh.selector to determine the right personality
    434   // function to use. For SJLJ, we always use the same personality for the
    435   // whole function, not on a per-selector basis.
    436   // FIXME: That's a bit ugly. Better way?
    437   SmallVector<CallInst*,16> EH_Selectors;
    438   SmallVector<CallInst*,16> EH_Exceptions;
    439   SmallVector<Instruction*,16> JmpbufUpdatePoints;
    440 
    441   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
    442     // Note: Skip the entry block since there's nothing there that interests
    443     // us. eh.selector and eh.exception shouldn't ever be there, and we
    444     // want to disregard any allocas that are there.
    445     //
    446     // FIXME: This is awkward. The new EH scheme won't need to skip the entry
    447     //        block.
    448     if (BB == F.begin()) {
    449       if (InvokeInst *II = dyn_cast<InvokeInst>(F.begin()->getTerminator())) {
    450         // FIXME: This will be always non-NULL in the new EH.
    451         if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
    452           if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
    453       }
    454 
    455       continue;
    456     }
    457 
    458     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
    459       if (CallInst *CI = dyn_cast<CallInst>(I)) {
    460         if (CI->getCalledFunction() == SelectorFn) {
    461           if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
    462           EH_Selectors.push_back(CI);
    463         } else if (CI->getCalledFunction() == ExceptionFn) {
    464           EH_Exceptions.push_back(CI);
    465         } else if (CI->getCalledFunction() == StackRestoreFn) {
    466           JmpbufUpdatePoints.push_back(CI);
    467         }
    468       } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
    469         JmpbufUpdatePoints.push_back(AI);
    470       } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
    471         // FIXME: This will be always non-NULL in the new EH.
    472         if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
    473           if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
    474       }
    475     }
    476   }
    477 
    478   // If we don't have any eh.selector calls, we can't determine the personality
    479   // function. Without a personality function, we can't process exceptions.
    480   if (!PersonalityFn) return false;
    481 
    482   // We have invokes, so we need to add register/unregister calls to get this
    483   // function onto the global unwind stack.
    484   //
    485   // First thing we need to do is scan the whole function for values that are
    486   // live across unwind edges.  Each value that is live across an unwind edge we
    487   // spill into a stack location, guaranteeing that there is nothing live across
    488   // the unwind edge.  This process also splits all critical edges coming out of
    489   // invoke's.
    490   splitLiveRangesAcrossInvokes(Invokes);
    491 
    492 
    493   SmallVector<LandingPadInst*, 16> LandingPads;
    494   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
    495     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
    496       // FIXME: This will be always non-NULL in the new EH.
    497       if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
    498         LandingPads.push_back(LPI);
    499   }
    500 
    501 
    502   BasicBlock *EntryBB = F.begin();
    503   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
    504   // that needs to be restored on all exits from the function.  This is an
    505   // alloca because the value needs to be added to the global context list.
    506   unsigned Align = 4; // FIXME: Should be a TLI check?
    507   AllocaInst *FunctionContext =
    508     new AllocaInst(FunctionContextTy, 0, Align,
    509                    "fcn_context", F.begin()->begin());
    510 
    511   Value *Idxs[2];
    512   Type *Int32Ty = Type::getInt32Ty(F.getContext());
    513   Value *Zero = ConstantInt::get(Int32Ty, 0);
    514   // We need to also keep around a reference to the call_site field
    515   Idxs[0] = Zero;
    516   Idxs[1] = ConstantInt::get(Int32Ty, 1);
    517   CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
    518                                        EntryBB->getTerminator());
    519 
    520   // The exception selector comes back in context->data[1]
    521   Idxs[1] = ConstantInt::get(Int32Ty, 2);
    522   Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
    523                                             EntryBB->getTerminator());
    524   Idxs[1] = ConstantInt::get(Int32Ty, 1);
    525   Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
    526                                                   "exc_selector_gep",
    527                                                   EntryBB->getTerminator());
    528   // The exception value comes back in context->data[0]
    529   Idxs[1] = Zero;
    530   Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
    531                                                    "exception_gep",
    532                                                    EntryBB->getTerminator());
    533 
    534   // The result of the eh.selector call will be replaced with a a reference to
    535   // the selector value returned in the function context. We leave the selector
    536   // itself so the EH analysis later can use it.
    537   for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
    538     CallInst *I = EH_Selectors[i];
    539     Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
    540     I->replaceAllUsesWith(SelectorVal);
    541   }
    542 
    543   // eh.exception calls are replaced with references to the proper location in
    544   // the context. Unlike eh.selector, the eh.exception calls are removed
    545   // entirely.
    546   for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
    547     CallInst *I = EH_Exceptions[i];
    548     // Possible for there to be duplicates, so check to make sure the
    549     // instruction hasn't already been removed.
    550     if (!I->getParent()) continue;
    551     Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
    552     Type *Ty = Type::getInt8PtrTy(F.getContext());
    553     Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
    554 
    555     I->replaceAllUsesWith(Val);
    556     I->eraseFromParent();
    557   }
    558 
    559   for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
    560     ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
    561 
    562   // The entry block changes to have the eh.sjlj.setjmp, with a conditional
    563   // branch to a dispatch block for non-zero returns. If we return normally,
    564   // we're not handling an exception and just register the function context and
    565   // continue.
    566 
    567   // Create the dispatch block.  The dispatch block is basically a big switch
    568   // statement that goes to all of the invoke landing pads.
    569   BasicBlock *DispatchBlock =
    570     BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
    571 
    572   // Insert a load of the callsite in the dispatch block, and a switch on its
    573   // value. By default, we issue a trap statement.
    574   BasicBlock *TrapBlock =
    575     BasicBlock::Create(F.getContext(), "trapbb", &F);
    576   CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
    577                    "", TrapBlock);
    578   new UnreachableInst(F.getContext(), TrapBlock);
    579 
    580   Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
    581                                      DispatchBlock);
    582   SwitchInst *DispatchSwitch =
    583     SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
    584                        DispatchBlock);
    585   // Split the entry block to insert the conditional branch for the setjmp.
    586   BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
    587                                                    "eh.sjlj.setjmp.cont");
    588 
    589   // Populate the Function Context
    590   //   1. LSDA address
    591   //   2. Personality function address
    592   //   3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
    593 
    594   // LSDA address
    595   Idxs[0] = Zero;
    596   Idxs[1] = ConstantInt::get(Int32Ty, 4);
    597   Value *LSDAFieldPtr =
    598     GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
    599                               EntryBB->getTerminator());
    600   Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
    601                                  EntryBB->getTerminator());
    602   new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
    603 
    604   Idxs[1] = ConstantInt::get(Int32Ty, 3);
    605   Value *PersonalityFieldPtr =
    606     GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
    607                               EntryBB->getTerminator());
    608   new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
    609                 EntryBB->getTerminator());
    610 
    611   // Save the frame pointer.
    612   Idxs[1] = ConstantInt::get(Int32Ty, 5);
    613   Value *JBufPtr
    614     = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
    615                                 EntryBB->getTerminator());
    616   Idxs[1] = ConstantInt::get(Int32Ty, 0);
    617   Value *FramePtr =
    618     GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
    619                               EntryBB->getTerminator());
    620 
    621   Value *Val = CallInst::Create(FrameAddrFn,
    622                                 ConstantInt::get(Int32Ty, 0),
    623                                 "fp",
    624                                 EntryBB->getTerminator());
    625   new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
    626 
    627   // Save the stack pointer.
    628   Idxs[1] = ConstantInt::get(Int32Ty, 2);
    629   Value *StackPtr =
    630     GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
    631                               EntryBB->getTerminator());
    632 
    633   Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
    634   new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
    635 
    636   // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
    637   Value *SetjmpArg =
    638     CastInst::Create(Instruction::BitCast, JBufPtr,
    639                      Type::getInt8PtrTy(F.getContext()), "",
    640                      EntryBB->getTerminator());
    641   Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
    642                                         "",
    643                                         EntryBB->getTerminator());
    644 
    645   // Add a call to dispatch_setup after the setjmp call. This is expanded to any
    646   // target-specific setup that needs to be done.
    647   CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
    648 
    649   // check the return value of the setjmp. non-zero goes to dispatcher.
    650   Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
    651                                  ICmpInst::ICMP_EQ, DispatchVal, Zero,
    652                                  "notunwind");
    653   // Nuke the uncond branch.
    654   EntryBB->getTerminator()->eraseFromParent();
    655 
    656   // Put in a new condbranch in its place.
    657   BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
    658 
    659   // Register the function context and make sure it's known to not throw
    660   CallInst *Register =
    661     CallInst::Create(RegisterFn, FunctionContext, "",
    662                      ContBlock->getTerminator());
    663   Register->setDoesNotThrow();
    664 
    665   // At this point, we are all set up, update the invoke instructions to mark
    666   // their call_site values, and fill in the dispatch switch accordingly.
    667   for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
    668     markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
    669 
    670   // Mark call instructions that aren't nounwind as no-action (call_site ==
    671   // -1). Skip the entry block, as prior to then, no function context has been
    672   // created for this function and any unexpected exceptions thrown will go
    673   // directly to the caller's context, which is what we want anyway, so no need
    674   // to do anything here.
    675   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
    676     for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
    677       if (CallInst *CI = dyn_cast<CallInst>(I)) {
    678         // Ignore calls to the EH builtins (eh.selector, eh.exception)
    679         Constant *Callee = CI->getCalledFunction();
    680         if (Callee != SelectorFn && Callee != ExceptionFn
    681             && !CI->doesNotThrow())
    682           insertCallSiteStore(CI, -1, CallSite);
    683       } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
    684         insertCallSiteStore(RI, -1, CallSite);
    685       }
    686   }
    687 
    688   // Replace all unwinds with a branch to the unwind handler.
    689   // ??? Should this ever happen with sjlj exceptions?
    690   for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
    691     BranchInst::Create(TrapBlock, Unwinds[i]);
    692     Unwinds[i]->eraseFromParent();
    693   }
    694 
    695   // Following any allocas not in the entry block, update the saved SP in the
    696   // jmpbuf to the new value.
    697   for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
    698     Instruction *AI = JmpbufUpdatePoints[i];
    699     Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
    700     StackAddr->insertAfter(AI);
    701     Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
    702     StoreStackAddr->insertAfter(StackAddr);
    703   }
    704 
    705   // Finally, for any returns from this function, if this function contains an
    706   // invoke, add a call to unregister the function context.
    707   for (unsigned i = 0, e = Returns.size(); i != e; ++i)
    708     CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
    709 
    710   return true;
    711 }
    712 
    713 /// setupFunctionContext - Allocate the function context on the stack and fill
    714 /// it with all of the data that we know at this point.
    715 Value *SjLjEHPass::
    716 setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
    717   BasicBlock *EntryBB = F.begin();
    718 
    719   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
    720   // that needs to be restored on all exits from the function. This is an alloca
    721   // because the value needs to be added to the global context list.
    722   unsigned Align =
    723     TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
    724   AllocaInst *FuncCtx =
    725     new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
    726 
    727   // Fill in the function context structure.
    728   Value *Idxs[2];
    729   Type *Int32Ty = Type::getInt32Ty(F.getContext());
    730   Value *Zero = ConstantInt::get(Int32Ty, 0);
    731   Value *One = ConstantInt::get(Int32Ty, 1);
    732 
    733   // Keep around a reference to the call_site field.
    734   Idxs[0] = Zero;
    735   Idxs[1] = One;
    736   CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
    737                                        EntryBB->getTerminator());
    738 
    739   // Reference the __data field.
    740   Idxs[1] = ConstantInt::get(Int32Ty, 2);
    741   Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
    742                                             EntryBB->getTerminator());
    743 
    744   // The exception value comes back in context->__data[0].
    745   Idxs[1] = Zero;
    746   Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
    747                                                    "exception_gep",
    748                                                    EntryBB->getTerminator());
    749 
    750   // The exception selector comes back in context->__data[1].
    751   Idxs[1] = One;
    752   Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
    753                                                   "exn_selector_gep",
    754                                                   EntryBB->getTerminator());
    755 
    756   for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
    757     LandingPadInst *LPI = LPads[I];
    758     IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
    759 
    760     Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
    761     ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
    762     Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
    763 
    764     Type *LPadType = LPI->getType();
    765     Value *LPadVal = UndefValue::get(LPadType);
    766     LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
    767     LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
    768 
    769     LPI->replaceAllUsesWith(LPadVal);
    770   }
    771 
    772   // Personality function
    773   Idxs[1] = ConstantInt::get(Int32Ty, 3);
    774   if (!PersonalityFn)
    775     PersonalityFn = LPads[0]->getPersonalityFn();
    776   Value *PersonalityFieldPtr =
    777     GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
    778                               EntryBB->getTerminator());
    779   new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
    780                 EntryBB->getTerminator());
    781 
    782   // LSDA address
    783   Idxs[1] = ConstantInt::get(Int32Ty, 4);
    784   Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
    785                                                   EntryBB->getTerminator());
    786   Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
    787                                  EntryBB->getTerminator());
    788   new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
    789 
    790   return FuncCtx;
    791 }
    792 
    793 /// lowerIncomingArguments - To avoid having to handle incoming arguments
    794 /// specially, we lower each arg to a copy instruction in the entry block. This
    795 /// ensures that the argument value itself cannot be live out of the entry
    796 /// block.
    797 void SjLjEHPass::lowerIncomingArguments(Function &F) {
    798   BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
    799   while (isa<AllocaInst>(AfterAllocaInsPt) &&
    800          isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
    801     ++AfterAllocaInsPt;
    802 
    803   for (Function::arg_iterator
    804          AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
    805     Type *Ty = AI->getType();
    806 
    807     // Aggregate types can't be cast, but are legal argument types, so we have
    808     // to handle them differently. We use an extract/insert pair as a
    809     // lightweight method to achieve the same goal.
    810     if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
    811       Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
    812       Instruction *NI = InsertValueInst::Create(AI, EI, 0);
    813       NI->insertAfter(EI);
    814       AI->replaceAllUsesWith(NI);
    815 
    816       // Set the operand of the instructions back to the AllocaInst.
    817       EI->setOperand(0, AI);
    818       NI->setOperand(0, AI);
    819     } else {
    820       // This is always a no-op cast because we're casting AI to AI->getType()
    821       // so src and destination types are identical. BitCast is the only
    822       // possibility.
    823       CastInst *NC =
    824         new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
    825                         AfterAllocaInsPt);
    826       AI->replaceAllUsesWith(NC);
    827 
    828       // Set the operand of the cast instruction back to the AllocaInst.
    829       // Normally it's forbidden to replace a CastInst's operand because it
    830       // could cause the opcode to reflect an illegal conversion. However, we're
    831       // replacing it here with the same value it was constructed with.  We do
    832       // this because the above replaceAllUsesWith() clobbered the operand, but
    833       // we want this one to remain.
    834       NC->setOperand(0, AI);
    835     }
    836   }
    837 }
    838 
    839 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
    840 /// edge and spill them.
    841 void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
    842                                         ArrayRef<InvokeInst*> Invokes) {
    843   // Finally, scan the code looking for instructions with bad live ranges.
    844   for (Function::iterator
    845          BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
    846     for (BasicBlock::iterator
    847            II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
    848       // Ignore obvious cases we don't have to handle. In particular, most
    849       // instructions either have no uses or only have a single use inside the
    850       // current block. Ignore them quickly.
    851       Instruction *Inst = II;
    852       if (Inst->use_empty()) continue;
    853       if (Inst->hasOneUse() &&
    854           cast<Instruction>(Inst->use_back())->getParent() == BB &&
    855           !isa<PHINode>(Inst->use_back())) continue;
    856 
    857       // If this is an alloca in the entry block, it's not a real register
    858       // value.
    859       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
    860         if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
    861           continue;
    862 
    863       // Avoid iterator invalidation by copying users to a temporary vector.
    864       SmallVector<Instruction*, 16> Users;
    865       for (Value::use_iterator
    866              UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
    867         Instruction *User = cast<Instruction>(*UI);
    868         if (User->getParent() != BB || isa<PHINode>(User))
    869           Users.push_back(User);
    870       }
    871 
    872       // Find all of the blocks that this value is live in.
    873       std::set<BasicBlock*> LiveBBs;
    874       LiveBBs.insert(Inst->getParent());
    875       while (!Users.empty()) {
    876         Instruction *U = Users.back();
    877         Users.pop_back();
    878 
    879         if (!isa<PHINode>(U)) {
    880           MarkBlocksLiveIn(U->getParent(), LiveBBs);
    881         } else {
    882           // Uses for a PHI node occur in their predecessor block.
    883           PHINode *PN = cast<PHINode>(U);
    884           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    885             if (PN->getIncomingValue(i) == Inst)
    886               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
    887         }
    888       }
    889 
    890       // Now that we know all of the blocks that this thing is live in, see if
    891       // it includes any of the unwind locations.
    892       bool NeedsSpill = false;
    893       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
    894         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
    895         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
    896           NeedsSpill = true;
    897         }
    898       }
    899 
    900       // If we decided we need a spill, do it.
    901       // FIXME: Spilling this way is overkill, as it forces all uses of
    902       // the value to be reloaded from the stack slot, even those that aren't
    903       // in the unwind blocks. We should be more selective.
    904       if (NeedsSpill) {
    905         ++NumSpilled;
    906         DemoteRegToStack(*Inst, true);
    907       }
    908     }
    909   }
    910 }
    911 
    912 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
    913 /// the function context and marking the call sites with the appropriate
    914 /// values. These values are used by the DWARF EH emitter.
    915 bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
    916   SmallVector<ReturnInst*,     16> Returns;
    917   SmallVector<InvokeInst*,     16> Invokes;
    918   SmallVector<LandingPadInst*, 16> LPads;
    919 
    920   // Look through the terminators of the basic blocks to find invokes.
    921   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
    922     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
    923       Invokes.push_back(II);
    924       LPads.push_back(II->getUnwindDest()->getLandingPadInst());
    925     } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
    926       Returns.push_back(RI);
    927     }
    928 
    929   if (Invokes.empty()) return false;
    930 
    931   lowerIncomingArguments(F);
    932   lowerAcrossUnwindEdges(F, Invokes);
    933 
    934   Value *FuncCtx = setupFunctionContext(F, LPads);
    935   BasicBlock *EntryBB = F.begin();
    936   Type *Int32Ty = Type::getInt32Ty(F.getContext());
    937 
    938   Value *Idxs[2] = {
    939     ConstantInt::get(Int32Ty, 0), 0
    940   };
    941 
    942   // Get a reference to the jump buffer.
    943   Idxs[1] = ConstantInt::get(Int32Ty, 5);
    944   Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
    945                                              EntryBB->getTerminator());
    946 
    947   // Save the frame pointer.
    948   Idxs[1] = ConstantInt::get(Int32Ty, 0);
    949   Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
    950                                               EntryBB->getTerminator());
    951 
    952   Value *Val = CallInst::Create(FrameAddrFn,
    953                                 ConstantInt::get(Int32Ty, 0),
    954                                 "fp",
    955                                 EntryBB->getTerminator());
    956   new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
    957 
    958   // Save the stack pointer.
    959   Idxs[1] = ConstantInt::get(Int32Ty, 2);
    960   Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
    961                                               EntryBB->getTerminator());
    962 
    963   Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
    964   new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
    965 
    966   // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
    967   Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
    968                                       Type::getInt8PtrTy(F.getContext()), "",
    969                                       EntryBB->getTerminator());
    970   CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
    971 
    972   // Store a pointer to the function context so that the back-end will know
    973   // where to look for it.
    974   Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
    975                                        Type::getInt8PtrTy(F.getContext()), "",
    976                                        EntryBB->getTerminator());
    977   CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
    978 
    979   // At this point, we are all set up, update the invoke instructions to mark
    980   // their call_site values.
    981   for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
    982     insertCallSiteStore(Invokes[I], I + 1, CallSite);
    983 
    984     ConstantInt *CallSiteNum =
    985       ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
    986 
    987     // Record the call site value for the back end so it stays associated with
    988     // the invoke.
    989     CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
    990   }
    991 
    992   // Mark call instructions that aren't nounwind as no-action (call_site ==
    993   // -1). Skip the entry block, as prior to then, no function context has been
    994   // created for this function and any unexpected exceptions thrown will go
    995   // directly to the caller's context, which is what we want anyway, so no need
    996   // to do anything here.
    997   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
    998     for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
    999       if (CallInst *CI = dyn_cast<CallInst>(I)) {
   1000         if (!CI->doesNotThrow())
   1001           insertCallSiteStore(CI, -1, CallSite);
   1002       } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
   1003         insertCallSiteStore(RI, -1, CallSite);
   1004       }
   1005 
   1006   // Register the function context and make sure it's known to not throw
   1007   CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
   1008                                         EntryBB->getTerminator());
   1009   Register->setDoesNotThrow();
   1010 
   1011   // Finally, for any returns from this function, if this function contains an
   1012   // invoke, add a call to unregister the function context.
   1013   for (unsigned I = 0, E = Returns.size(); I != E; ++I)
   1014     CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
   1015 
   1016   return true;
   1017 }
   1018 
   1019 bool SjLjEHPass::runOnFunction(Function &F) {
   1020   bool Res = false;
   1021   if (!DisableOldSjLjEH)
   1022     Res = insertSjLjEHSupport(F);
   1023   else
   1024     Res = setupEntryBlockAndCallSites(F);
   1025   return Res;
   1026 }
   1027