LLVM API Documentation

SjLjEHPrepare.cpp

Go to the documentation of this file.
00001 //===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This transformation is designed for use by code generators which use SjLj
00011 // based exception handling.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "sjljehprepare"
00016 #include "llvm/Transforms/Scalar.h"
00017 #include "llvm/Constants.h"
00018 #include "llvm/DerivedTypes.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Intrinsics.h"
00021 #include "llvm/LLVMContext.h"
00022 #include "llvm/Module.h"
00023 #include "llvm/Pass.h"
00024 #include "llvm/CodeGen/Passes.h"
00025 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00026 #include "llvm/Transforms/Utils/Local.h"
00027 #include "llvm/ADT/DenseMap.h"
00028 #include "llvm/ADT/Statistic.h"
00029 #include "llvm/ADT/SmallVector.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Support/Compiler.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/raw_ostream.h"
00034 #include "llvm/Target/TargetLowering.h"
00035 using namespace llvm;
00036 
00037 STATISTIC(NumInvokes, "Number of invokes replaced");
00038 STATISTIC(NumUnwinds, "Number of unwinds replaced");
00039 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
00040 
00041 namespace {
00042   class VISIBILITY_HIDDEN SjLjEHPass : public FunctionPass {
00043 
00044     const TargetLowering *TLI;
00045 
00046     const Type *FunctionContextTy;
00047     Constant *RegisterFn;
00048     Constant *UnregisterFn;
00049     Constant *ResumeFn;
00050     Constant *BuiltinSetjmpFn;
00051     Constant *FrameAddrFn;
00052     Constant *LSDAAddrFn;
00053     Value *PersonalityFn;
00054     Constant *Selector32Fn;
00055     Constant *Selector64Fn;
00056     Constant *ExceptionFn;
00057 
00058     Value *CallSite;
00059   public:
00060     static char ID; // Pass identification, replacement for typeid
00061     explicit SjLjEHPass(const TargetLowering *tli = NULL)
00062       : FunctionPass(&ID), TLI(tli) { }
00063     bool doInitialization(Module &M);
00064     bool runOnFunction(Function &F);
00065 
00066     virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
00067     const char *getPassName() const {
00068       return "SJLJ Exception Handling preparation";
00069     }
00070 
00071   private:
00072     void markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
00073                             Value *CallSite);
00074     void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
00075     bool insertSjLjEHSupport(Function &F);
00076   };
00077 } // end anonymous namespace
00078 
00079 char SjLjEHPass::ID = 0;
00080 
00081 // Public Interface To the SjLjEHPass pass.
00082 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
00083   return new SjLjEHPass(TLI);
00084 }
00085 // doInitialization - Make sure that there is a prototype for abort in the
00086 // current module.
00087 bool SjLjEHPass::doInitialization(Module &M) {
00088   // Build the function context structure.
00089   // builtin_setjmp uses a five word jbuf
00090   const Type *VoidPtrTy =
00091           PointerType::getUnqual(Type::getInt8Ty(M.getContext()));
00092   const Type *Int32Ty = Type::getInt32Ty(M.getContext());
00093   FunctionContextTy =
00094     StructType::get(M.getContext(),
00095                     VoidPtrTy,                        // __prev
00096                     Int32Ty,                          // call_site
00097                     ArrayType::get(Int32Ty, 4),       // __data
00098                     VoidPtrTy,                        // __personality
00099                     VoidPtrTy,                        // __lsda
00100                     ArrayType::get(VoidPtrTy, 5),     // __jbuf
00101                     NULL);
00102   RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
00103                                      Type::getVoidTy(M.getContext()),
00104                                      PointerType::getUnqual(FunctionContextTy),
00105                                      (Type *)0);
00106   UnregisterFn =
00107     M.getOrInsertFunction("_Unwind_SjLj_Unregister",
00108                           Type::getVoidTy(M.getContext()),
00109                           PointerType::getUnqual(FunctionContextTy),
00110                           (Type *)0);
00111   ResumeFn =
00112     M.getOrInsertFunction("_Unwind_SjLj_Resume",
00113                           Type::getVoidTy(M.getContext()),
00114                           VoidPtrTy,
00115                           (Type *)0);
00116   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
00117   BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
00118   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
00119   Selector32Fn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector_i32);
00120   Selector64Fn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector_i64);
00121   ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
00122 
00123   return true;
00124 }
00125 
00126 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
00127 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
00128                                     Value *CallSite) {
00129   ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
00130                                             InvokeNo);
00131 
00132   // If the unwind edge has phi nodes, split the edge.
00133   if (isa<PHINode>(II->getUnwindDest()->begin())) {
00134     SplitCriticalEdge(II, 1, this);
00135 
00136     // If there are any phi nodes left, they must have a single predecessor.
00137     while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
00138       PN->replaceAllUsesWith(PN->getIncomingValue(0));
00139       PN->eraseFromParent();
00140     }
00141   }
00142 
00143   // Insert a store of the invoke num before the invoke and store zero into the
00144   // location afterward.
00145   new StoreInst(CallSiteNoC, CallSite, true, II);  // volatile
00146 
00147   // We still want this to look like an invoke so we emit the LSDA properly
00148   // FIXME: ??? Or will this cause strangeness with mis-matched IDs like
00149   //  when it was in the front end?
00150 }
00151 
00152 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
00153 /// we reach blocks we've already seen.
00154 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
00155   if (!LiveBBs.insert(BB).second) return; // already been here.
00156 
00157   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00158     MarkBlocksLiveIn(*PI, LiveBBs);
00159 }
00160 
00161 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
00162 /// we spill into a stack location, guaranteeing that there is nothing live
00163 /// across the unwind edge.  This process also splits all critical edges
00164 /// coming out of invoke's.
00165 void SjLjEHPass::
00166 splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
00167   // First step, split all critical edges from invoke instructions.
00168   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
00169     InvokeInst *II = Invokes[i];
00170     SplitCriticalEdge(II, 0, this);
00171     SplitCriticalEdge(II, 1, this);
00172     assert(!isa<PHINode>(II->getNormalDest()) &&
00173            !isa<PHINode>(II->getUnwindDest()) &&
00174            "critical edge splitting left single entry phi nodes?");
00175   }
00176 
00177   Function *F = Invokes.back()->getParent()->getParent();
00178 
00179   // To avoid having to handle incoming arguments specially, we lower each arg
00180   // to a copy instruction in the entry block.  This ensures that the argument
00181   // value itself cannot be live across the entry block.
00182   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
00183   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
00184         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
00185     ++AfterAllocaInsertPt;
00186   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
00187        AI != E; ++AI) {
00188     // This is always a no-op cast because we're casting AI to AI->getType() so
00189     // src and destination types are identical. BitCast is the only possibility.
00190     CastInst *NC = new BitCastInst(
00191       AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
00192     AI->replaceAllUsesWith(NC);
00193     // Normally its is forbidden to replace a CastInst's operand because it
00194     // could cause the opcode to reflect an illegal conversion. However, we're
00195     // replacing it here with the same value it was constructed with to simply
00196     // make NC its user.
00197     NC->setOperand(0, AI);
00198   }
00199 
00200   // Finally, scan the code looking for instructions with bad live ranges.
00201   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00202     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
00203       // Ignore obvious cases we don't have to handle.  In particular, most
00204       // instructions either have no uses or only have a single use inside the
00205       // current block.  Ignore them quickly.
00206       Instruction *Inst = II;
00207       if (Inst->use_empty()) continue;
00208       if (Inst->hasOneUse() &&
00209           cast<Instruction>(Inst->use_back())->getParent() == BB &&
00210           !isa<PHINode>(Inst->use_back())) continue;
00211 
00212       // If this is an alloca in the entry block, it's not a real register
00213       // value.
00214       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
00215         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
00216           continue;
00217 
00218       // Avoid iterator invalidation by copying users to a temporary vector.
00219       SmallVector<Instruction*,16> Users;
00220       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
00221            UI != E; ++UI) {
00222         Instruction *User = cast<Instruction>(*UI);
00223         if (User->getParent() != BB || isa<PHINode>(User))
00224           Users.push_back(User);
00225       }
00226 
00227       // Find all of the blocks that this value is live in.
00228       std::set<BasicBlock*> LiveBBs;
00229       LiveBBs.insert(Inst->getParent());
00230       while (!Users.empty()) {
00231         Instruction *U = Users.back();
00232         Users.pop_back();
00233 
00234         if (!isa<PHINode>(U)) {
00235           MarkBlocksLiveIn(U->getParent(), LiveBBs);
00236         } else {
00237           // Uses for a PHI node occur in their predecessor block.
00238           PHINode *PN = cast<PHINode>(U);
00239           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00240             if (PN->getIncomingValue(i) == Inst)
00241               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
00242         }
00243       }
00244 
00245       // Now that we know all of the blocks that this thing is live in, see if
00246       // it includes any of the unwind locations.
00247       bool NeedsSpill = false;
00248       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
00249         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
00250         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
00251           NeedsSpill = true;
00252         }
00253       }
00254 
00255       // If we decided we need a spill, do it.
00256       if (NeedsSpill) {
00257         ++NumSpilled;
00258         DemoteRegToStack(*Inst, true);
00259       }
00260     }
00261 }
00262 
00263 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
00264   SmallVector<ReturnInst*,16> Returns;
00265   SmallVector<UnwindInst*,16> Unwinds;
00266   SmallVector<InvokeInst*,16> Invokes;
00267 
00268   // Look through the terminators of the basic blocks to find invokes, returns
00269   // and unwinds
00270   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00271     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
00272       // Remember all return instructions in case we insert an invoke into this
00273       // function.
00274       Returns.push_back(RI);
00275     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
00276       Invokes.push_back(II);
00277     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00278       Unwinds.push_back(UI);
00279     }
00280   // If we don't have any invokes or unwinds, there's nothing to do.
00281   if (Unwinds.empty() && Invokes.empty()) return false;
00282 
00283   NumInvokes += Invokes.size();
00284   NumUnwinds += Unwinds.size();
00285 
00286 
00287   if (!Invokes.empty()) {
00288     // We have invokes, so we need to add register/unregister calls to get
00289     // this function onto the global unwind stack.
00290 
00291     BasicBlock *EntryBB = F.begin();
00292     // Create an alloca for the incoming jump buffer ptr and the new jump buffer
00293     // that needs to be restored on all exits from the function.  This is an
00294     // alloca because the value needs to be added to the global context list.
00295     unsigned Align = 4; // FIXME: Should be a TLI check?
00296     AllocaInst *FunctionContext =
00297       new AllocaInst(FunctionContextTy, 0, Align,
00298                      "fcn_context", F.begin()->begin());
00299 
00300     Value *Idxs[2];
00301     const Type *Int32Ty = Type::getInt32Ty(F.getContext());
00302     Value *Zero = ConstantInt::get(Int32Ty, 0);
00303     // We need to also keep around a reference to the call_site field
00304     Idxs[0] = Zero;
00305     Idxs[1] = ConstantInt::get(Int32Ty, 1);
00306     CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
00307                                          "call_site",
00308                                          EntryBB->getTerminator());
00309 
00310     // The exception selector comes back in context->data[1]
00311     Idxs[1] = ConstantInt::get(Int32Ty, 2);
00312     Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
00313                                               "fc_data",
00314                                               EntryBB->getTerminator());
00315     Idxs[1] = ConstantInt::get(Int32Ty, 1);
00316     Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
00317                                                     "exc_selector_gep",
00318                                                     EntryBB->getTerminator());
00319     // The exception value comes back in context->data[0]
00320     Idxs[1] = Zero;
00321     Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
00322                                                      "exception_gep",
00323                                                      EntryBB->getTerminator());
00324 
00325     // Find the eh.selector.*  and eh.exception calls. We'll use the first
00326     // ex.selector to determine the right personality function to use. For
00327     // SJLJ, we always use the same personality for the whole function,
00328     // not on a per-selector basis.
00329     // FIXME: That's a bit ugly. Better way?
00330     SmallVector<CallInst*,16> EH_Selectors;
00331     SmallVector<CallInst*,16> EH_Exceptions;
00332     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00333       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00334         if (CallInst *CI = dyn_cast<CallInst>(I)) {
00335           if (CI->getCalledFunction() == Selector32Fn ||
00336               CI->getCalledFunction() == Selector64Fn) {
00337             if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
00338             EH_Selectors.push_back(CI);
00339           } else if (CI->getCalledFunction() == ExceptionFn) {
00340             EH_Exceptions.push_back(CI);
00341           }
00342         }
00343       }
00344     }
00345     // The result of the eh.selector call will be replaced with a
00346     // a reference to the selector value returned in the function
00347     // context. We leave the selector itself so the EH analysis later
00348     // can use it.
00349     for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
00350       CallInst *I = EH_Selectors[i];
00351       Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
00352       I->replaceAllUsesWith(SelectorVal);
00353     }
00354     // eh.exception calls are replaced with references to the proper
00355     // location in the context. Unlike eh.selector, the eh.exception
00356     // calls are removed entirely.
00357     for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
00358       CallInst *I = EH_Exceptions[i];
00359       // Possible for there to be duplicates, so check to make sure
00360       // the instruction hasn't already been removed.
00361       if (!I->getParent()) continue;
00362       Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
00363       Type *Ty = PointerType::getUnqual(Type::getInt8Ty(F.getContext()));
00364       Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
00365 
00366       I->replaceAllUsesWith(Val);
00367       I->eraseFromParent();
00368     }
00369 
00370 
00371 
00372 
00373     // The entry block changes to have the eh.sjlj.setjmp, with a conditional
00374     // branch to a dispatch block for non-zero returns. If we return normally,
00375     // we're not handling an exception and just register the function context
00376     // and continue.
00377 
00378     // Create the dispatch block.  The dispatch block is basically a big switch
00379     // statement that goes to all of the invoke landing pads.
00380     BasicBlock *DispatchBlock =
00381             BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
00382 
00383     // Insert a load in the Catch block, and a switch on its value.  By default,
00384     // we go to a block that just does an unwind (which is the correct action
00385     // for a standard call).
00386     BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwindbb", &F);
00387     Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
00388 
00389     Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
00390                                        DispatchBlock);
00391     SwitchInst *DispatchSwitch =
00392       SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(), DispatchBlock);
00393     // Split the entry block to insert the conditional branch for the setjmp.
00394     BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
00395                                                      "eh.sjlj.setjmp.cont");
00396 
00397     // Populate the Function Context
00398     //   1. LSDA address
00399     //   2. Personality function address
00400     //   3. jmpbuf (save FP and call eh.sjlj.setjmp)
00401 
00402     // LSDA address
00403     Idxs[0] = Zero;
00404     Idxs[1] = ConstantInt::get(Int32Ty, 4);
00405     Value *LSDAFieldPtr =
00406       GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
00407                                 "lsda_gep",
00408                                 EntryBB->getTerminator());
00409     Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
00410                                    EntryBB->getTerminator());
00411     new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
00412 
00413     Idxs[1] = ConstantInt::get(Int32Ty, 3);
00414     Value *PersonalityFieldPtr =
00415       GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
00416                                 "lsda_gep",
00417                                 EntryBB->getTerminator());
00418     new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
00419                   EntryBB->getTerminator());
00420 
00421     //   Save the frame pointer.
00422     Idxs[1] = ConstantInt::get(Int32Ty, 5);
00423     Value *FieldPtr
00424       = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
00425                                   "jbuf_gep",
00426                                   EntryBB->getTerminator());
00427     Idxs[1] = ConstantInt::get(Int32Ty, 0);
00428     Value *ElemPtr =
00429       GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
00430                                 EntryBB->getTerminator());
00431 
00432     Value *Val = CallInst::Create(FrameAddrFn,
00433                                   ConstantInt::get(Int32Ty, 0),
00434                                   "fp",
00435                                   EntryBB->getTerminator());
00436     new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
00437     // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
00438     Value *SetjmpArg =
00439       CastInst::Create(Instruction::BitCast, FieldPtr,
00440                         Type::getInt8Ty(F.getContext())->getPointerTo(), "",
00441                         EntryBB->getTerminator());
00442     Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
00443                                           "dispatch",
00444                                           EntryBB->getTerminator());
00445     // check the return value of the setjmp. non-zero goes to dispatcher
00446     Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
00447                                    ICmpInst::ICMP_EQ, DispatchVal, Zero,
00448                                    "notunwind");
00449     // Nuke the uncond branch.
00450     EntryBB->getTerminator()->eraseFromParent();
00451 
00452     // Put in a new condbranch in its place.
00453     BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
00454 
00455     // Register the function context and make sure it's known to not throw
00456     CallInst *Register =
00457       CallInst::Create(RegisterFn, FunctionContext, "",
00458                        ContBlock->getTerminator());
00459     Register->setDoesNotThrow();
00460 
00461     // At this point, we are all set up. Update the invoke instructions
00462     // to mark their call_site values, and fill in the dispatch switch
00463     // accordingly.
00464     DenseMap<BasicBlock*,unsigned> PadSites;
00465     unsigned NextCallSiteValue = 1;
00466     for (SmallVector<InvokeInst*,16>::iterator I = Invokes.begin(),
00467          E = Invokes.end(); I < E; ++I) {
00468       unsigned CallSiteValue;
00469       BasicBlock *LandingPad = (*I)->getSuccessor(1);
00470       // landing pads can be shared. If we see a landing pad again, we
00471       // want to make sure to use the same call site index so the dispatch
00472       // will go to the right place.
00473       CallSiteValue = PadSites[LandingPad];
00474       if (!CallSiteValue) {
00475         CallSiteValue = NextCallSiteValue++;
00476         PadSites[LandingPad] = CallSiteValue;
00477         // Add a switch case to our unwind block. The runtime comes back
00478         // to the dispatcher with the call_site - 1 in the context. Odd,
00479         // but there it is.
00480         ConstantInt *SwitchValC =
00481           ConstantInt::get(Type::getInt32Ty((*I)->getContext()),
00482                            CallSiteValue - 1);
00483         DispatchSwitch->addCase(SwitchValC, (*I)->getUnwindDest());
00484       }
00485       markInvokeCallSite(*I, CallSiteValue, CallSite);
00486     }
00487 
00488     // The front end has likely added calls to _Unwind_Resume. We need
00489     // to find those calls and mark the call_site as -1 immediately prior.
00490     // resume is a noreturn function, so any block that has a call to it
00491     // should end in an 'unreachable' instruction with the call immediately
00492     // prior. That's how we'll search.
00493     // ??? There's got to be a better way. this is fugly.
00494     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00495       if ((dyn_cast<UnreachableInst>(BB->getTerminator()))) {
00496         BasicBlock::iterator I = BB->getTerminator();
00497         // Check the previous instruction and see if it's a resume call
00498         if (I == BB->begin()) continue;
00499         if (CallInst *CI = dyn_cast<CallInst>(--I)) {
00500           if (CI->getCalledFunction() == ResumeFn) {
00501             Value *NegativeOne = Constant::getAllOnesValue(Int32Ty);
00502             new StoreInst(NegativeOne, CallSite, true, I);  // volatile
00503           }
00504         }
00505       }
00506 
00507     // Replace all unwinds with a branch to the unwind handler.
00508     // ??? Should this ever happen with sjlj exceptions?
00509     for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
00510       BranchInst::Create(UnwindBlock, Unwinds[i]);
00511       Unwinds[i]->eraseFromParent();
00512     }
00513 
00514     // Scan the whole function for values that are live across unwind edges.
00515     // Each value that is live across an unwind edge we spill into a stack
00516     // location, guaranteeing that there is nothing live across the unwind
00517     // edge.  This process also splits all critical edges coming out of 
00518     // invoke's.
00519     splitLiveRangesLiveAcrossInvokes(Invokes);
00520 
00521     // Finally, for any returns from this function, if this function contains an
00522     // invoke, add a call to unregister the function context.
00523     for (unsigned i = 0, e = Returns.size(); i != e; ++i)
00524       CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
00525   }
00526 
00527   return true;
00528 }
00529 
00530 bool SjLjEHPass::runOnFunction(Function &F) {
00531   bool Res = insertSjLjEHSupport(F);
00532   return Res;
00533 }