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