Add a pre-dispatch SjLj EH hook on the unwind edge for targets to do any
[oota-llvm.git] / lib / CodeGen / SjLjEHPrepare.cpp
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/Transforms/Utils/BasicBlockUtils.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetLowering.h"
33 using namespace llvm;
34
35 STATISTIC(NumInvokes, "Number of invokes replaced");
36 STATISTIC(NumUnwinds, "Number of unwinds replaced");
37 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
38
39 namespace {
40   class SjLjEHPass : public FunctionPass {
41
42     const TargetLowering *TLI;
43
44     const Type *FunctionContextTy;
45     Constant *RegisterFn;
46     Constant *UnregisterFn;
47     Constant *BuiltinSetjmpFn;
48     Constant *FrameAddrFn;
49     Constant *StackAddrFn;
50     Constant *StackRestoreFn;
51     Constant *LSDAAddrFn;
52     Value *PersonalityFn;
53     Constant *SelectorFn;
54     Constant *ExceptionFn;
55     Constant *CallSiteFn;
56     Constant *DispatchSetupFn;
57
58     Value *CallSite;
59   public:
60     static char ID; // Pass identification, replacement for typeid
61     explicit SjLjEHPass(const TargetLowering *tli = NULL)
62       : FunctionPass(ID), TLI(tli) { }
63     bool doInitialization(Module &M);
64     bool runOnFunction(Function &F);
65
66     virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
67     const char *getPassName() const {
68       return "SJLJ Exception Handling preparation";
69     }
70
71   private:
72     void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
73     void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
74                             SwitchInst *CatchSwitch);
75     void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
76     bool insertSjLjEHSupport(Function &F);
77   };
78 } // end anonymous namespace
79
80 char SjLjEHPass::ID = 0;
81
82 // Public Interface To the SjLjEHPass pass.
83 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
84   return new SjLjEHPass(TLI);
85 }
86 // doInitialization - Set up decalarations and types needed to process
87 // exceptions.
88 bool SjLjEHPass::doInitialization(Module &M) {
89   // Build the function context structure.
90   // builtin_setjmp uses a five word jbuf
91   const Type *VoidPtrTy =
92           Type::getInt8PtrTy(M.getContext());
93   const Type *Int32Ty = Type::getInt32Ty(M.getContext());
94   FunctionContextTy =
95     StructType::get(M.getContext(),
96                     VoidPtrTy,                        // __prev
97                     Int32Ty,                          // call_site
98                     ArrayType::get(Int32Ty, 4),       // __data
99                     VoidPtrTy,                        // __personality
100                     VoidPtrTy,                        // __lsda
101                     ArrayType::get(VoidPtrTy, 5),     // __jbuf
102                     NULL);
103   RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
104                                      Type::getVoidTy(M.getContext()),
105                                      PointerType::getUnqual(FunctionContextTy),
106                                      (Type *)0);
107   UnregisterFn =
108     M.getOrInsertFunction("_Unwind_SjLj_Unregister",
109                           Type::getVoidTy(M.getContext()),
110                           PointerType::getUnqual(FunctionContextTy),
111                           (Type *)0);
112   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
113   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
114   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
115   BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
116   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
117   SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
118   ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
119   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
120   DispatchSetupFn
121     = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
122   PersonalityFn = 0;
123
124   return true;
125 }
126
127 /// insertCallSiteStore - Insert a store of the call-site value to the
128 /// function context
129 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
130                                      Value *CallSite) {
131   ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
132                                               Number);
133   // Insert a store of the call-site number
134   new StoreInst(CallSiteNoC, CallSite, true, I);  // volatile
135 }
136
137 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
138 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
139                                     Value *CallSite,
140                                     SwitchInst *CatchSwitch) {
141   ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
142                                               InvokeNo);
143   // The runtime comes back to the dispatcher with the call_site - 1 in
144   // the context. Odd, but there it is.
145   ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
146                                             InvokeNo - 1);
147
148   // If the unwind edge has phi nodes, split the edge.
149   if (isa<PHINode>(II->getUnwindDest()->begin())) {
150     SplitCriticalEdge(II, 1, this);
151
152     // If there are any phi nodes left, they must have a single predecessor.
153     while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
154       PN->replaceAllUsesWith(PN->getIncomingValue(0));
155       PN->eraseFromParent();
156     }
157   }
158
159   // Insert the store of the call site value
160   insertCallSiteStore(II, InvokeNo, CallSite);
161
162   // Record the call site value for the back end so it stays associated with
163   // the invoke.
164   CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
165
166   // Add a switch case to our unwind block.
167   CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
168   // We still want this to look like an invoke so we emit the LSDA properly,
169   // so we don't transform the invoke into a call here.
170 }
171
172 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
173 /// we reach blocks we've already seen.
174 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
175   if (!LiveBBs.insert(BB).second) return; // already been here.
176
177   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
178     MarkBlocksLiveIn(*PI, LiveBBs);
179 }
180
181 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
182 /// we spill into a stack location, guaranteeing that there is nothing live
183 /// across the unwind edge.  This process also splits all critical edges
184 /// coming out of invoke's.
185 /// FIXME: Move this function to a common utility file (Local.cpp?) so
186 /// both SjLj and LowerInvoke can use it.
187 void SjLjEHPass::
188 splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
189   // First step, split all critical edges from invoke instructions.
190   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
191     InvokeInst *II = Invokes[i];
192     SplitCriticalEdge(II, 0, this);
193     SplitCriticalEdge(II, 1, this);
194     assert(!isa<PHINode>(II->getNormalDest()) &&
195            !isa<PHINode>(II->getUnwindDest()) &&
196            "critical edge splitting left single entry phi nodes?");
197   }
198
199   Function *F = Invokes.back()->getParent()->getParent();
200
201   // To avoid having to handle incoming arguments specially, we lower each arg
202   // to a copy instruction in the entry block.  This ensures that the argument
203   // value itself cannot be live across the entry block.
204   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
205   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
206         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
207     ++AfterAllocaInsertPt;
208   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
209        AI != E; ++AI) {
210     const Type *Ty = AI->getType();
211     // Aggregate types can't be cast, but are legal argument types, so we have
212     // to handle them differently. We use an extract/insert pair as a
213     // lightweight method to achieve the same goal.
214     if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
215       Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
216       Instruction *NI = InsertValueInst::Create(AI, EI, 0);
217       NI->insertAfter(EI);
218       AI->replaceAllUsesWith(NI);
219       // Set the operand of the instructions back to the AllocaInst.
220       EI->setOperand(0, AI);
221       NI->setOperand(0, AI);
222     } else {
223       // This is always a no-op cast because we're casting AI to AI->getType()
224       // so src and destination types are identical. BitCast is the only
225       // possibility.
226       CastInst *NC = new BitCastInst(
227         AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
228       AI->replaceAllUsesWith(NC);
229       // Set the operand of the cast instruction back to the AllocaInst.
230       // Normally it's forbidden to replace a CastInst's operand because it
231       // could cause the opcode to reflect an illegal conversion. However,
232       // we're replacing it here with the same value it was constructed with.
233       // We do this because the above replaceAllUsesWith() clobbered the
234       // operand, but we want this one to remain.
235       NC->setOperand(0, AI);
236     }
237   }
238
239   // Finally, scan the code looking for instructions with bad live ranges.
240   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
241     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
242       // Ignore obvious cases we don't have to handle.  In particular, most
243       // instructions either have no uses or only have a single use inside the
244       // current block.  Ignore them quickly.
245       Instruction *Inst = II;
246       if (Inst->use_empty()) continue;
247       if (Inst->hasOneUse() &&
248           cast<Instruction>(Inst->use_back())->getParent() == BB &&
249           !isa<PHINode>(Inst->use_back())) continue;
250
251       // If this is an alloca in the entry block, it's not a real register
252       // value.
253       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
254         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
255           continue;
256
257       // Avoid iterator invalidation by copying users to a temporary vector.
258       SmallVector<Instruction*,16> Users;
259       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
260            UI != E; ++UI) {
261         Instruction *User = cast<Instruction>(*UI);
262         if (User->getParent() != BB || isa<PHINode>(User))
263           Users.push_back(User);
264       }
265
266       // Find all of the blocks that this value is live in.
267       std::set<BasicBlock*> LiveBBs;
268       LiveBBs.insert(Inst->getParent());
269       while (!Users.empty()) {
270         Instruction *U = Users.back();
271         Users.pop_back();
272
273         if (!isa<PHINode>(U)) {
274           MarkBlocksLiveIn(U->getParent(), LiveBBs);
275         } else {
276           // Uses for a PHI node occur in their predecessor block.
277           PHINode *PN = cast<PHINode>(U);
278           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
279             if (PN->getIncomingValue(i) == Inst)
280               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
281         }
282       }
283
284       // Now that we know all of the blocks that this thing is live in, see if
285       // it includes any of the unwind locations.
286       bool NeedsSpill = false;
287       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
288         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
289         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
290           NeedsSpill = true;
291         }
292       }
293
294       // If we decided we need a spill, do it.
295       // FIXME: Spilling this way is overkill, as it forces all uses of
296       // the value to be reloaded from the stack slot, even those that aren't
297       // in the unwind blocks. We should be more selective.
298       if (NeedsSpill) {
299         ++NumSpilled;
300         DemoteRegToStack(*Inst, true);
301       }
302     }
303 }
304
305 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
306   SmallVector<ReturnInst*,16> Returns;
307   SmallVector<UnwindInst*,16> Unwinds;
308   SmallVector<InvokeInst*,16> Invokes;
309
310   // Look through the terminators of the basic blocks to find invokes, returns
311   // and unwinds.
312   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
313     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
314       // Remember all return instructions in case we insert an invoke into this
315       // function.
316       Returns.push_back(RI);
317     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
318       Invokes.push_back(II);
319     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
320       Unwinds.push_back(UI);
321     }
322   }
323   // If we don't have any invokes or unwinds, there's nothing to do.
324   if (Unwinds.empty() && Invokes.empty()) return false;
325
326   // Find the eh.selector.*, eh.exception and alloca calls.
327   //
328   // Remember any allocas() that aren't in the entry block, as the
329   // jmpbuf saved SP will need to be updated for them.
330   //
331   // We'll use the first eh.selector to determine the right personality
332   // function to use. For SJLJ, we always use the same personality for the
333   // whole function, not on a per-selector basis.
334   // FIXME: That's a bit ugly. Better way?
335   SmallVector<CallInst*,16> EH_Selectors;
336   SmallVector<CallInst*,16> EH_Exceptions;
337   SmallVector<Instruction*,16> JmpbufUpdatePoints;
338   // Note: Skip the entry block since there's nothing there that interests
339   // us. eh.selector and eh.exception shouldn't ever be there, and we
340   // want to disregard any allocas that are there.
341   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
342     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
343       if (CallInst *CI = dyn_cast<CallInst>(I)) {
344         if (CI->getCalledFunction() == SelectorFn) {
345           if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
346           EH_Selectors.push_back(CI);
347         } else if (CI->getCalledFunction() == ExceptionFn) {
348           EH_Exceptions.push_back(CI);
349         } else if (CI->getCalledFunction() == StackRestoreFn) {
350           JmpbufUpdatePoints.push_back(CI);
351         }
352       } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
353         JmpbufUpdatePoints.push_back(AI);
354       }
355     }
356   }
357   // If we don't have any eh.selector calls, we can't determine the personality
358   // function. Without a personality function, we can't process exceptions.
359   if (!PersonalityFn) return false;
360
361   NumInvokes += Invokes.size();
362   NumUnwinds += Unwinds.size();
363
364   if (!Invokes.empty()) {
365     // We have invokes, so we need to add register/unregister calls to get
366     // this function onto the global unwind stack.
367     //
368     // First thing we need to do is scan the whole function for values that are
369     // live across unwind edges.  Each value that is live across an unwind edge
370     // we spill into a stack location, guaranteeing that there is nothing live
371     // across the unwind edge.  This process also splits all critical edges
372     // coming out of invoke's.
373     splitLiveRangesAcrossInvokes(Invokes);
374
375     BasicBlock *EntryBB = F.begin();
376     // Create an alloca for the incoming jump buffer ptr and the new jump buffer
377     // that needs to be restored on all exits from the function.  This is an
378     // alloca because the value needs to be added to the global context list.
379     unsigned Align = 4; // FIXME: Should be a TLI check?
380     AllocaInst *FunctionContext =
381       new AllocaInst(FunctionContextTy, 0, Align,
382                      "fcn_context", F.begin()->begin());
383
384     Value *Idxs[2];
385     const Type *Int32Ty = Type::getInt32Ty(F.getContext());
386     Value *Zero = ConstantInt::get(Int32Ty, 0);
387     // We need to also keep around a reference to the call_site field
388     Idxs[0] = Zero;
389     Idxs[1] = ConstantInt::get(Int32Ty, 1);
390     CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
391                                          "call_site",
392                                          EntryBB->getTerminator());
393
394     // The exception selector comes back in context->data[1]
395     Idxs[1] = ConstantInt::get(Int32Ty, 2);
396     Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
397                                               "fc_data",
398                                               EntryBB->getTerminator());
399     Idxs[1] = ConstantInt::get(Int32Ty, 1);
400     Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
401                                                     "exc_selector_gep",
402                                                     EntryBB->getTerminator());
403     // The exception value comes back in context->data[0]
404     Idxs[1] = Zero;
405     Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
406                                                      "exception_gep",
407                                                      EntryBB->getTerminator());
408
409     // The result of the eh.selector call will be replaced with a
410     // a reference to the selector value returned in the function
411     // context. We leave the selector itself so the EH analysis later
412     // can use it.
413     for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
414       CallInst *I = EH_Selectors[i];
415       Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
416       I->replaceAllUsesWith(SelectorVal);
417     }
418     // eh.exception calls are replaced with references to the proper
419     // location in the context. Unlike eh.selector, the eh.exception
420     // calls are removed entirely.
421     for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
422       CallInst *I = EH_Exceptions[i];
423       // Possible for there to be duplicates, so check to make sure
424       // the instruction hasn't already been removed.
425       if (!I->getParent()) continue;
426       Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
427       const Type *Ty = Type::getInt8PtrTy(F.getContext());
428       Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
429
430       I->replaceAllUsesWith(Val);
431       I->eraseFromParent();
432     }
433
434     // The entry block changes to have the eh.sjlj.setjmp, with a conditional
435     // branch to a dispatch block for non-zero returns. If we return normally,
436     // we're not handling an exception and just register the function context
437     // and continue.
438
439     // Create the dispatch block.  The dispatch block is basically a big switch
440     // statement that goes to all of the invoke landing pads.
441     BasicBlock *DispatchBlock =
442             BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
443
444     // Add a call to dispatch_setup at the start of the dispatch block. This
445     // is expanded to any target-specific setup that needs to be done.
446     Value *SetupArg =
447       CastInst::Create(Instruction::BitCast, FunctionContext,
448                        Type::getInt8PtrTy(F.getContext()), "",
449                        DispatchBlock);
450     CallInst::Create(DispatchSetupFn, SetupArg, "", DispatchBlock);
451
452     // Insert a load of the callsite in the dispatch block, and a switch on
453     // its value.  By default, we go to a block that just does an unwind
454     // (which is the correct action for a standard call).
455     BasicBlock *UnwindBlock =
456       BasicBlock::Create(F.getContext(), "unwindbb", &F);
457     Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
458
459     Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
460                                        DispatchBlock);
461     SwitchInst *DispatchSwitch =
462       SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
463                          DispatchBlock);
464     // Split the entry block to insert the conditional branch for the setjmp.
465     BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
466                                                      "eh.sjlj.setjmp.cont");
467
468     // Populate the Function Context
469     //   1. LSDA address
470     //   2. Personality function address
471     //   3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
472
473     // LSDA address
474     Idxs[0] = Zero;
475     Idxs[1] = ConstantInt::get(Int32Ty, 4);
476     Value *LSDAFieldPtr =
477       GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
478                                 "lsda_gep",
479                                 EntryBB->getTerminator());
480     Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
481                                    EntryBB->getTerminator());
482     new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
483
484     Idxs[1] = ConstantInt::get(Int32Ty, 3);
485     Value *PersonalityFieldPtr =
486       GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
487                                 "lsda_gep",
488                                 EntryBB->getTerminator());
489     new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
490                   EntryBB->getTerminator());
491
492     // Save the frame pointer.
493     Idxs[1] = ConstantInt::get(Int32Ty, 5);
494     Value *JBufPtr
495       = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
496                                   "jbuf_gep",
497                                   EntryBB->getTerminator());
498     Idxs[1] = ConstantInt::get(Int32Ty, 0);
499     Value *FramePtr =
500       GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_fp_gep",
501                                 EntryBB->getTerminator());
502
503     Value *Val = CallInst::Create(FrameAddrFn,
504                                   ConstantInt::get(Int32Ty, 0),
505                                   "fp",
506                                   EntryBB->getTerminator());
507     new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
508
509     // Save the stack pointer.
510     Idxs[1] = ConstantInt::get(Int32Ty, 2);
511     Value *StackPtr =
512       GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_sp_gep",
513                                 EntryBB->getTerminator());
514
515     Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
516     new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
517
518     // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
519     Value *SetjmpArg =
520       CastInst::Create(Instruction::BitCast, JBufPtr,
521                        Type::getInt8PtrTy(F.getContext()), "",
522                        EntryBB->getTerminator());
523     Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
524                                           "dispatch",
525                                           EntryBB->getTerminator());
526     // check the return value of the setjmp. non-zero goes to dispatcher.
527     Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
528                                    ICmpInst::ICMP_EQ, DispatchVal, Zero,
529                                    "notunwind");
530     // Nuke the uncond branch.
531     EntryBB->getTerminator()->eraseFromParent();
532
533     // Put in a new condbranch in its place.
534     BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
535
536     // Register the function context and make sure it's known to not throw
537     CallInst *Register =
538       CallInst::Create(RegisterFn, FunctionContext, "",
539                        ContBlock->getTerminator());
540     Register->setDoesNotThrow();
541
542     // At this point, we are all set up, update the invoke instructions
543     // to mark their call_site values, and fill in the dispatch switch
544     // accordingly.
545     for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
546       markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
547
548     // Mark call instructions that aren't nounwind as no-action
549     // (call_site == -1). Skip the entry block, as prior to then, no function
550     // context has been created for this function and any unexpected exceptions
551     // thrown will go directly to the caller's context, which is what we want
552     // anyway, so no need to do anything here.
553     for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
554       for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
555         if (CallInst *CI = dyn_cast<CallInst>(I)) {
556           // Ignore calls to the EH builtins (eh.selector, eh.exception)
557           Constant *Callee = CI->getCalledFunction();
558           if (Callee != SelectorFn && Callee != ExceptionFn
559               && !CI->doesNotThrow())
560             insertCallSiteStore(CI, -1, CallSite);
561         }
562     }
563
564     // Replace all unwinds with a branch to the unwind handler.
565     // ??? Should this ever happen with sjlj exceptions?
566     for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
567       BranchInst::Create(UnwindBlock, Unwinds[i]);
568       Unwinds[i]->eraseFromParent();
569     }
570
571     // Following any allocas not in the entry block, update the saved SP
572     // in the jmpbuf to the new value.
573     for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
574       Instruction *AI = JmpbufUpdatePoints[i];
575       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
576       StackAddr->insertAfter(AI);
577       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
578       StoreStackAddr->insertAfter(StackAddr);
579     }
580
581     // Finally, for any returns from this function, if this function contains an
582     // invoke, add a call to unregister the function context.
583     for (unsigned i = 0, e = Returns.size(); i != e; ++i)
584       CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
585   }
586
587   return true;
588 }
589
590 bool SjLjEHPass::runOnFunction(Function &F) {
591   bool Res = insertSjLjEHSupport(F);
592   return Res;
593 }