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