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