Implement a more intelligent way of spilling uses across an invoke boundary.
[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/Analysis/Verifier.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/IRBuilder.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SetVector.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Statistic.h"
39 #include <set>
40 using namespace llvm;
41
42 STATISTIC(NumInvokes, "Number of invokes 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 *CallSiteFn;
58     Constant *FuncCtxFn;
59     AllocaInst *FuncCtx;
60   public:
61     static char ID; // Pass identification, replacement for typeid
62     explicit SjLjEHPass(const TargetLowering *tli = NULL)
63       : FunctionPass(ID), TLI(tli) { }
64     bool doInitialization(Module &M);
65     bool runOnFunction(Function &F);
66
67     virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
68     const char *getPassName() const {
69       return "SJLJ Exception Handling preparation";
70     }
71
72   private:
73     bool setupEntryBlockAndCallSites(Function &F);
74     void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
75                               Value *SelVal);
76     Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
77     void lowerIncomingArguments(Function &F);
78     void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
79     void insertCallSiteStore(Instruction *I, int Number);
80   };
81 } // end anonymous namespace
82
83 char SjLjEHPass::ID = 0;
84
85 // Public Interface To the SjLjEHPass pass.
86 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
87   return new SjLjEHPass(TLI);
88 }
89 // doInitialization - Set up decalarations and types needed to process
90 // exceptions.
91 bool SjLjEHPass::doInitialization(Module &M) {
92   // Build the function context structure.
93   // builtin_setjmp uses a five word jbuf
94   Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
95   Type *Int32Ty = Type::getInt32Ty(M.getContext());
96   FunctionContextTy =
97     StructType::get(VoidPtrTy,                        // __prev
98                     Int32Ty,                          // call_site
99                     ArrayType::get(Int32Ty, 4),       // __data
100                     VoidPtrTy,                        // __personality
101                     VoidPtrTy,                        // __lsda
102                     ArrayType::get(VoidPtrTy, 5),     // __jbuf
103                     NULL);
104   RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
105                                      Type::getVoidTy(M.getContext()),
106                                      PointerType::getUnqual(FunctionContextTy),
107                                      (Type *)0);
108   UnregisterFn =
109     M.getOrInsertFunction("_Unwind_SjLj_Unregister",
110                           Type::getVoidTy(M.getContext()),
111                           PointerType::getUnqual(FunctionContextTy),
112                           (Type *)0);
113   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
114   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
115   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
116   BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
117   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
118   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
119   FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
120   PersonalityFn = 0;
121
122   return true;
123 }
124
125 /// insertCallSiteStore - Insert a store of the call-site value to the
126 /// function context
127 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number) {
128   IRBuilder<> Builder(I);
129
130   // Get a reference to the call_site field.
131   Type *Int32Ty = Type::getInt32Ty(I->getContext());
132   Value *Zero = ConstantInt::get(Int32Ty, 0);
133   Value *One = ConstantInt::get(Int32Ty, 1);
134   Value *Idxs[2] = { Zero, One };
135   Value *CallSite = Builder.CreateGEP(FuncCtx, Idxs, "call_site");
136
137   // Insert a store of the call-site number
138   ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
139                                               Number);
140   Builder.CreateStore(CallSiteNoC, CallSite, true/*volatile*/);
141 }
142
143 /// markBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
144 /// we reach blocks we've already seen.
145 static void markBlocksLiveIn(BasicBlock *BB, Instruction *Inst,
146                              SmallPtrSet<BasicBlock*, 64> &LiveBBs,
147                              SmallPtrSet<BasicBlock*, 4> &InvokesCrossed) {
148   if (!LiveBBs.insert(BB)) return; // already been here.
149
150   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
151     BasicBlock *Pred = *PI;
152     if (BB->isLandingPad() && BB != Inst->getParent())
153       InvokesCrossed.insert(Pred);
154     markBlocksLiveIn(Pred, Inst, LiveBBs, InvokesCrossed);
155   }
156 }
157
158 /// substituteLPadValues - Substitute the values returned by the landingpad
159 /// instruction with those returned by the personality function.
160 void SjLjEHPass::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
161                                       Value *SelVal) {
162   SmallVector<Value*, 8> UseWorkList(LPI->use_begin(), LPI->use_end());
163   while (!UseWorkList.empty()) {
164     Value *Val = UseWorkList.pop_back_val();
165     ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
166     if (!EVI) continue;
167     if (EVI->getNumIndices() != 1) continue;
168     if (*EVI->idx_begin() == 0)
169       EVI->replaceAllUsesWith(ExnVal);
170     else if (*EVI->idx_begin() == 1)
171       EVI->replaceAllUsesWith(SelVal);
172     if (EVI->getNumUses() == 0)
173       EVI->eraseFromParent();
174   }
175
176   if (LPI->getNumUses() == 0)  return;
177
178   // There are still some uses of LPI. Construct an aggregate with the exception
179   // values and replace the LPI with that aggregate.
180   Type *LPadType = LPI->getType();
181   Value *LPadVal = UndefValue::get(LPadType);
182   IRBuilder<>
183     Builder(llvm::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
184   LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
185   LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
186
187   LPI->replaceAllUsesWith(LPadVal);
188 }
189
190 /// setupFunctionContext - Allocate the function context on the stack and fill
191 /// it with all of the data that we know at this point.
192 Value *SjLjEHPass::
193 setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
194   BasicBlock *EntryBB = F.begin();
195
196   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
197   // that needs to be restored on all exits from the function. This is an alloca
198   // because the value needs to be added to the global context list.
199   unsigned Align =
200     TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
201   FuncCtx =
202     new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
203
204   // Fill in the function context structure.
205   Type *Int32Ty = Type::getInt32Ty(F.getContext());
206   Value *Zero = ConstantInt::get(Int32Ty, 0);
207   Value *One = ConstantInt::get(Int32Ty, 1);
208   Value *Two = ConstantInt::get(Int32Ty, 2);
209   Value *Three = ConstantInt::get(Int32Ty, 3);
210   Value *Four = ConstantInt::get(Int32Ty, 4);
211
212   Value *Idxs[2] = { Zero, 0 };
213
214   for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
215     LandingPadInst *LPI = LPads[I];
216     IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
217
218     // Reference the __data field.
219     Idxs[1] = Two;
220     Value *FCData = Builder.CreateGEP(FuncCtx, Idxs, "__data");
221
222     // The exception values come back in context->__data[0].
223     Idxs[1] = Zero;
224     Value *ExceptionAddr = Builder.CreateGEP(FCData, Idxs, "exception_gep");
225     Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
226     ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
227
228     Idxs[1] = One;
229     Value *SelectorAddr = Builder.CreateGEP(FCData, Idxs, "exn_selector_gep");
230     Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
231
232     substituteLPadValues(LPI, ExnVal, SelVal);
233   }
234
235   // Personality function
236   Idxs[1] = Three;
237   if (!PersonalityFn)
238     PersonalityFn = LPads[0]->getPersonalityFn();
239   Value *PersonalityFieldPtr =
240     GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
241                               EntryBB->getTerminator());
242   new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
243                 EntryBB->getTerminator());
244
245   // LSDA address
246   Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
247                                  EntryBB->getTerminator());
248   Idxs[1] = Four;
249   Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
250                                                   EntryBB->getTerminator());
251   new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
252
253   return FuncCtx;
254 }
255
256 /// lowerIncomingArguments - To avoid having to handle incoming arguments
257 /// specially, we lower each arg to a copy instruction in the entry block. This
258 /// ensures that the argument value itself cannot be live out of the entry
259 /// block.
260 void SjLjEHPass::lowerIncomingArguments(Function &F) {
261   BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
262   while (isa<AllocaInst>(AfterAllocaInsPt) &&
263          isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
264     ++AfterAllocaInsPt;
265
266   for (Function::arg_iterator
267          AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
268     Type *Ty = AI->getType();
269
270     // Aggregate types can't be cast, but are legal argument types, so we have
271     // to handle them differently. We use an extract/insert pair as a
272     // lightweight method to achieve the same goal.
273     if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
274       Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
275       Instruction *NI = InsertValueInst::Create(AI, EI, 0);
276       NI->insertAfter(EI);
277       AI->replaceAllUsesWith(NI);
278
279       // Set the operand of the instructions back to the AllocaInst.
280       EI->setOperand(0, AI);
281       NI->setOperand(0, AI);
282     } else {
283       // This is always a no-op cast because we're casting AI to AI->getType()
284       // so src and destination types are identical. BitCast is the only
285       // possibility.
286       CastInst *NC =
287         new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
288                         AfterAllocaInsPt);
289       AI->replaceAllUsesWith(NC);
290
291       // Set the operand of the cast instruction back to the AllocaInst.
292       // Normally it's forbidden to replace a CastInst's operand because it
293       // could cause the opcode to reflect an illegal conversion. However, we're
294       // replacing it here with the same value it was constructed with.  We do
295       // this because the above replaceAllUsesWith() clobbered the operand, but
296       // we want this one to remain.
297       NC->setOperand(0, AI);
298     }
299   }
300 }
301
302 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
303 /// edge and spill them.
304 void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
305                                         ArrayRef<InvokeInst*> Invokes) {
306   SmallVector<std::pair<Instruction*, Instruction*>, 32> ReloadUsers;
307   DenseMap<std::pair<Instruction*, Instruction*>, AllocaInst*> AllocaMap;
308
309   // Finally, scan the code looking for instructions with bad live ranges.
310   for (Function::iterator
311          BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
312     for (BasicBlock::iterator
313            II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
314       // Ignore obvious cases we don't have to handle. In particular, most
315       // instructions either have no uses or only have a single use inside the
316       // current block. Ignore them quickly.
317       Instruction *Inst = II;
318       if (Inst->use_empty()) continue;
319       if (Inst->hasOneUse() &&
320           cast<Instruction>(Inst->use_back())->getParent() == BB &&
321           !isa<PHINode>(Inst->use_back())) continue;
322
323       // If this is an alloca in the entry block, it's not a real register
324       // value.
325       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
326         if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
327           continue;
328
329       // Avoid iterator invalidation by copying users to a temporary vector.
330       SmallVector<Instruction*, 16> Users;
331       for (Value::use_iterator
332              UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
333         Instruction *User = cast<Instruction>(*UI);
334         if (User->getParent() != BB || isa<PHINode>(User))
335           Users.push_back(User);
336       }
337
338       // Find all of the blocks that this value is live in.
339       std::map<Instruction*, SmallPtrSet<BasicBlock*, 4> > InvokesCrossed;
340       std::map<Instruction*, SmallPtrSet<BasicBlock*, 64> > LiveBBs;
341       while (!Users.empty()) {
342         Instruction *U = Users.pop_back_val();
343         LiveBBs[U].insert(Inst->getParent());
344
345         if (PHINode *PN = dyn_cast<PHINode>(U)) {
346           // Uses for a PHI node occur in their predecessor block.
347           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
348             if (PN->getIncomingValue(i) == Inst)
349               markBlocksLiveIn(PN->getIncomingBlock(i), Inst, LiveBBs[U],
350                                InvokesCrossed[U]);
351         } else {
352           markBlocksLiveIn(U->getParent(), Inst, LiveBBs[U], InvokesCrossed[U]);
353         }
354       }
355
356       // Go through the invokes the value crosses and insert a spill right
357       // before the invoke.
358       for (std::map<Instruction*, SmallPtrSet<BasicBlock*, 4> >::iterator
359              MI = InvokesCrossed.begin(), ME = InvokesCrossed.end();
360            MI != ME; ++MI) {
361         Instruction *User = MI->first;
362         SmallPtrSet<BasicBlock*, 4> &Crossings = MI->second;
363         if (Crossings.empty()) continue;
364
365         ReloadUsers.push_back(std::make_pair(Inst, User));
366
367         AllocaInst *&Slot = AllocaMap[std::make_pair(Inst, User)];
368         if (!Slot)
369           Slot = new AllocaInst(Inst->getType(), 0,
370                                 Inst->getName() + ".reg2mem",
371                                 F.getEntryBlock().begin());
372
373         for (SmallPtrSet<BasicBlock*, 4>::iterator
374                CI = Crossings.begin(), CE = Crossings.end(); CI != CE; ++CI) {
375           new StoreInst(Inst, Slot, (*CI)->getTerminator());
376           ++NumSpilled;
377         }
378       }
379     }
380   }
381
382   // Now go through the instructions which were spilled and replace their uses
383   // after a crossed invoke with a reload instruction.
384   for (SmallVectorImpl<std::pair<Instruction*, Instruction*> >::iterator
385          I = ReloadUsers.begin(), E = ReloadUsers.end(); I != E; ++I) {
386     Instruction *User = I->second;
387     AllocaInst *Slot = AllocaMap[*I];
388     assert(Slot && "A spill slot hasn't been allocated yet!");
389
390     if (PHINode *PN = dyn_cast<PHINode>(User)) {
391       // If this is a PHI node, we can't insert a load of the value before the
392       // use. Instead insert the load in the predecessor block corresponding to
393       // the incoming value.
394       //
395       // Note that if there are multiple edges from a basic block to this PHI
396       // node that we cannot have multiple loads. The problem is that the
397       // resulting PHI node will have multiple values (from each load) coming in
398       // from the same block, which is illegal SSA form. For this reason, we
399       // keep track of and reuse loads we insert.
400       DenseMap<BasicBlock*, Value*> Loads;
401       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
402         if (PN->getIncomingValue(i) == I->first) {
403           Value *&V = Loads[PN->getIncomingBlock(i)];
404           if (V == 0)
405             // Insert the load into the predecessor block
406             V = new LoadInst(Slot, I->first->getName() + ".reload", true,
407                              PN->getIncomingBlock(i)->getTerminator());
408
409           PN->setIncomingValue(i, V);
410         }
411     } else {
412       LoadInst *Reload = new LoadInst(Slot, Slot->getName() + ".reload", User);
413       User->replaceUsesOfWith(I->first, Reload);
414     }
415   }
416
417   // Go through the landing pads and remove any PHIs there.
418   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
419     BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
420     LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
421
422     // Place PHIs into a set to avoid invalidating the iterator.
423     SmallPtrSet<PHINode*, 8> PHIsToDemote;
424     for (BasicBlock::iterator
425            PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
426       PHIsToDemote.insert(cast<PHINode>(PN));
427     if (PHIsToDemote.empty()) continue;
428
429     // Demote the PHIs to the stack.
430     for (SmallPtrSet<PHINode*, 8>::iterator
431            I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
432       DemotePHIToStack(*I);
433
434     // Move the landingpad instruction back to the top of the landing pad block.
435     LPI->moveBefore(UnwindBlock->begin());
436   }
437 }
438
439 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
440 /// the function context and marking the call sites with the appropriate
441 /// values. These values are used by the DWARF EH emitter.
442 bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
443   SmallVector<ReturnInst*,     16> Returns;
444   SmallVector<InvokeInst*,     16> Invokes;
445   SmallSetVector<LandingPadInst*, 16> LPads;
446
447   // Look through the terminators of the basic blocks to find invokes.
448   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
449     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
450       Invokes.push_back(II);
451       LPads.insert(II->getUnwindDest()->getLandingPadInst());
452     } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
453       Returns.push_back(RI);
454     }
455
456   if (Invokes.empty()) return false;
457
458   NumInvokes += Invokes.size();
459
460   lowerIncomingArguments(F);
461   lowerAcrossUnwindEdges(F, Invokes);
462
463   Value *FuncCtx =
464     setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
465   BasicBlock *EntryBB = F.begin();
466   Type *Int32Ty = Type::getInt32Ty(F.getContext());
467
468   Value *Idxs[2] = {
469     ConstantInt::get(Int32Ty, 0), 0
470   };
471
472   // Get a reference to the jump buffer.
473   Idxs[1] = ConstantInt::get(Int32Ty, 5);
474   Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
475                                              EntryBB->getTerminator());
476
477   // Save the frame pointer.
478   Idxs[1] = ConstantInt::get(Int32Ty, 0);
479   Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
480                                               EntryBB->getTerminator());
481
482   Value *Val = CallInst::Create(FrameAddrFn,
483                                 ConstantInt::get(Int32Ty, 0),
484                                 "fp",
485                                 EntryBB->getTerminator());
486   new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
487
488   // Save the stack pointer.
489   Idxs[1] = ConstantInt::get(Int32Ty, 2);
490   Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
491                                               EntryBB->getTerminator());
492
493   Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
494   new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
495
496   // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
497   Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
498                                       Type::getInt8PtrTy(F.getContext()), "",
499                                       EntryBB->getTerminator());
500   CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
501
502   // Store a pointer to the function context so that the back-end will know
503   // where to look for it.
504   Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
505                                        Type::getInt8PtrTy(F.getContext()), "",
506                                        EntryBB->getTerminator());
507   CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
508
509   // At this point, we are all set up, update the invoke instructions to mark
510   // their call_site values.
511   for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
512     insertCallSiteStore(Invokes[I], I + 1);
513
514     ConstantInt *CallSiteNum =
515       ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
516
517     // Record the call site value for the back end so it stays associated with
518     // the invoke.
519     CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
520   }
521
522   // Mark call instructions that aren't nounwind as no-action (call_site ==
523   // -1). Skip the entry block, as prior to then, no function context has been
524   // created for this function and any unexpected exceptions thrown will go
525   // directly to the caller's context, which is what we want anyway, so no need
526   // to do anything here.
527   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
528     for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
529       if (CallInst *CI = dyn_cast<CallInst>(I)) {
530         if (!CI->doesNotThrow())
531           insertCallSiteStore(CI, -1);
532       } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
533         insertCallSiteStore(RI, -1);
534       }
535
536   // Register the function context and make sure it's known to not throw
537   CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
538                                         EntryBB->getTerminator());
539   Register->setDoesNotThrow();
540
541   // Following any allocas not in the entry block, update the saved SP in the
542   // jmpbuf to the new value.
543   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
544     if (BB == F.begin())
545       continue;
546     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
547       if (CallInst *CI = dyn_cast<CallInst>(I)) {
548         if (CI->getCalledFunction() != StackRestoreFn)
549           continue;
550       } else if (!isa<AllocaInst>(I)) {
551         continue;
552       }
553       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
554       StackAddr->insertAfter(I);
555       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
556       StoreStackAddr->insertAfter(StackAddr);
557     }
558   }
559
560   // Finally, for any returns from this function, if this function contains an
561   // invoke, add a call to unregister the function context.
562   for (unsigned I = 0, E = Returns.size(); I != E; ++I)
563     CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
564
565   return true;
566 }
567
568 bool SjLjEHPass::runOnFunction(Function &F) {
569   bool Res = setupEntryBlockAndCallSites(F);
570   DEBUG({
571       if (verifyFunction(F))
572         report_fatal_error("verifyFunction failed!");
573     });
574   return Res;
575 }