blob: 059e8d6c19aa51663be9e069a5294ae107f0a3c8 [file] [log] [blame]
Jim Grosbach8b818d72009-08-17 16:41:22 +00001//===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This transformation is designed for use by code generators which use SjLj
11// based exception handling.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "sjljehprepare"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/LLVMContext.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/CodeGen/Passes.h"
25#include "llvm/Transforms/Utils/BasicBlockUtils.h"
26#include "llvm/Transforms/Utils/Local.h"
27#include "llvm/ADT/Statistic.h"
Jim Grosbach606f3d62009-08-17 21:40:03 +000028#include "llvm/ADT/SmallVector.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000029#include "llvm/Support/CommandLine.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000030#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000033using namespace llvm;
34
35STATISTIC(NumInvokes, "Number of invokes replaced");
36STATISTIC(NumUnwinds, "Number of unwinds replaced");
37STATISTIC(NumSpilled, "Number of registers live across unwind edges");
38
39namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000040 class SjLjEHPass : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000041
42 const TargetLowering *TLI;
43
44 const Type *FunctionContextTy;
45 Constant *RegisterFn;
46 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000047 Constant *BuiltinSetjmpFn;
48 Constant *FrameAddrFn;
49 Constant *LSDAAddrFn;
50 Value *PersonalityFn;
Duncan Sandsb01bbdc2009-10-14 16:11:37 +000051 Constant *SelectorFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000052 Constant *ExceptionFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000053 Constant *CallSiteFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000054
55 Value *CallSite;
56 public:
57 static char ID; // Pass identification, replacement for typeid
58 explicit SjLjEHPass(const TargetLowering *tli = NULL)
59 : FunctionPass(&ID), TLI(tli) { }
60 bool doInitialization(Module &M);
61 bool runOnFunction(Function &F);
62
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
64 const char *getPassName() const {
65 return "SJLJ Exception Handling preparation";
66 }
67
68 private:
Jim Grosbachb58a59b2010-03-04 22:07:46 +000069 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
70 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
Jim Grosbach0bb61c52009-08-31 01:35:03 +000071 SwitchInst *CatchSwitch);
Jim Grosbach606f3d62009-08-17 21:40:03 +000072 void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +000073 bool insertSjLjEHSupport(Function &F);
74 };
75} // end anonymous namespace
76
77char SjLjEHPass::ID = 0;
78
79// Public Interface To the SjLjEHPass pass.
80FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
81 return new SjLjEHPass(TLI);
82}
Jim Grosbacha235d132009-08-23 18:13:48 +000083// doInitialization - Set up decalarations and types needed to process
84// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000085bool SjLjEHPass::doInitialization(Module &M) {
86 // Build the function context structure.
87 // builtin_setjmp uses a five word jbuf
88 const Type *VoidPtrTy =
Duncan Sandsac53a0b2009-10-06 15:40:36 +000089 Type::getInt8PtrTy(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000090 const Type *Int32Ty = Type::getInt32Ty(M.getContext());
91 FunctionContextTy =
92 StructType::get(M.getContext(),
93 VoidPtrTy, // __prev
94 Int32Ty, // call_site
95 ArrayType::get(Int32Ty, 4), // __data
96 VoidPtrTy, // __personality
97 VoidPtrTy, // __lsda
98 ArrayType::get(VoidPtrTy, 5), // __jbuf
99 NULL);
100 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
101 Type::getVoidTy(M.getContext()),
102 PointerType::getUnqual(FunctionContextTy),
103 (Type *)0);
104 UnregisterFn =
105 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
106 Type::getVoidTy(M.getContext()),
107 PointerType::getUnqual(FunctionContextTy),
108 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000109 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
110 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
111 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000112 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000113 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000114 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbacha235d132009-08-23 18:13:48 +0000115 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000116
117 return true;
118}
119
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000120/// insertCallSiteStore - Insert a store of the call-site value to the
121/// function context
122void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
123 Value *CallSite) {
124 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
125 Number);
126 // Insert a store of the call-site number
127 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
128}
129
Jim Grosbach8b818d72009-08-17 16:41:22 +0000130/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000131void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000132 Value *CallSite,
133 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000134 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000135 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000136 // The runtime comes back to the dispatcher with the call_site - 1 in
137 // the context. Odd, but there it is.
138 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
139 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000140
141 // If the unwind edge has phi nodes, split the edge.
142 if (isa<PHINode>(II->getUnwindDest()->begin())) {
143 SplitCriticalEdge(II, 1, this);
144
145 // If there are any phi nodes left, they must have a single predecessor.
146 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
147 PN->replaceAllUsesWith(PN->getIncomingValue(0));
148 PN->eraseFromParent();
149 }
150 }
151
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000152 // Insert the store of the call site value
153 insertCallSiteStore(II, InvokeNo, CallSite);
154
155 // Record the call site value for the back end so it stays associated with
156 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000157 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000158
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000159 // Add a switch case to our unwind block.
160 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
Jim Grosbachca752c92010-01-28 01:45:32 +0000161 // We still want this to look like an invoke so we emit the LSDA properly,
162 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000163}
164
165/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
166/// we reach blocks we've already seen.
167static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
168 if (!LiveBBs.insert(BB).second) return; // already been here.
169
170 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
171 MarkBlocksLiveIn(*PI, LiveBBs);
172}
173
Jim Grosbach606f3d62009-08-17 21:40:03 +0000174/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
175/// we spill into a stack location, guaranteeing that there is nothing live
176/// across the unwind edge. This process also splits all critical edges
177/// coming out of invoke's.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000178void SjLjEHPass::
Jim Grosbach606f3d62009-08-17 21:40:03 +0000179splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000180 // First step, split all critical edges from invoke instructions.
181 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
182 InvokeInst *II = Invokes[i];
183 SplitCriticalEdge(II, 0, this);
184 SplitCriticalEdge(II, 1, this);
185 assert(!isa<PHINode>(II->getNormalDest()) &&
186 !isa<PHINode>(II->getUnwindDest()) &&
187 "critical edge splitting left single entry phi nodes?");
188 }
189
190 Function *F = Invokes.back()->getParent()->getParent();
191
192 // To avoid having to handle incoming arguments specially, we lower each arg
193 // to a copy instruction in the entry block. This ensures that the argument
194 // value itself cannot be live across the entry block.
195 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
196 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
197 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
198 ++AfterAllocaInsertPt;
199 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
200 AI != E; ++AI) {
201 // This is always a no-op cast because we're casting AI to AI->getType() so
202 // src and destination types are identical. BitCast is the only possibility.
203 CastInst *NC = new BitCastInst(
204 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
205 AI->replaceAllUsesWith(NC);
206 // Normally its is forbidden to replace a CastInst's operand because it
207 // could cause the opcode to reflect an illegal conversion. However, we're
208 // replacing it here with the same value it was constructed with to simply
209 // make NC its user.
210 NC->setOperand(0, AI);
211 }
212
213 // Finally, scan the code looking for instructions with bad live ranges.
214 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
215 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
216 // Ignore obvious cases we don't have to handle. In particular, most
217 // instructions either have no uses or only have a single use inside the
218 // current block. Ignore them quickly.
219 Instruction *Inst = II;
220 if (Inst->use_empty()) continue;
221 if (Inst->hasOneUse() &&
222 cast<Instruction>(Inst->use_back())->getParent() == BB &&
223 !isa<PHINode>(Inst->use_back())) continue;
224
225 // If this is an alloca in the entry block, it's not a real register
226 // value.
227 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
228 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
229 continue;
230
231 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000232 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000233 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
234 UI != E; ++UI) {
235 Instruction *User = cast<Instruction>(*UI);
236 if (User->getParent() != BB || isa<PHINode>(User))
237 Users.push_back(User);
238 }
239
Jim Grosbach8b818d72009-08-17 16:41:22 +0000240 // Find all of the blocks that this value is live in.
241 std::set<BasicBlock*> LiveBBs;
242 LiveBBs.insert(Inst->getParent());
243 while (!Users.empty()) {
244 Instruction *U = Users.back();
245 Users.pop_back();
246
247 if (!isa<PHINode>(U)) {
248 MarkBlocksLiveIn(U->getParent(), LiveBBs);
249 } else {
250 // Uses for a PHI node occur in their predecessor block.
251 PHINode *PN = cast<PHINode>(U);
252 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
253 if (PN->getIncomingValue(i) == Inst)
254 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
255 }
256 }
257
258 // Now that we know all of the blocks that this thing is live in, see if
259 // it includes any of the unwind locations.
260 bool NeedsSpill = false;
261 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
262 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
263 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
264 NeedsSpill = true;
265 }
266 }
267
268 // If we decided we need a spill, do it.
269 if (NeedsSpill) {
270 ++NumSpilled;
271 DemoteRegToStack(*Inst, true);
272 }
273 }
274}
275
276bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000277 SmallVector<ReturnInst*,16> Returns;
278 SmallVector<UnwindInst*,16> Unwinds;
279 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000280
281 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000282 // and unwinds.
283 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000284 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
285 // Remember all return instructions in case we insert an invoke into this
286 // function.
287 Returns.push_back(RI);
288 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
289 Invokes.push_back(II);
290 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
291 Unwinds.push_back(UI);
292 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000293 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000294 // If we don't have any invokes or unwinds, there's nothing to do.
295 if (Unwinds.empty() && Invokes.empty()) return false;
296
Jim Grosbacha235d132009-08-23 18:13:48 +0000297 // Find the eh.selector.* and eh.exception calls. We'll use the first
298 // eh.selector to determine the right personality function to use. For
299 // SJLJ, we always use the same personality for the whole function,
300 // not on a per-selector basis.
301 // FIXME: That's a bit ugly. Better way?
302 SmallVector<CallInst*,16> EH_Selectors;
303 SmallVector<CallInst*,16> EH_Exceptions;
304 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
305 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
306 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000307 if (CI->getCalledFunction() == SelectorFn) {
Eric Christopher551754c2010-04-16 23:37:20 +0000308 if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
Jim Grosbacha235d132009-08-23 18:13:48 +0000309 EH_Selectors.push_back(CI);
310 } else if (CI->getCalledFunction() == ExceptionFn) {
311 EH_Exceptions.push_back(CI);
312 }
313 }
314 }
315 }
316 // If we don't have any eh.selector calls, we can't determine the personality
317 // function. Without a personality function, we can't process exceptions.
318 if (!PersonalityFn) return false;
319
Jim Grosbach8b818d72009-08-17 16:41:22 +0000320 NumInvokes += Invokes.size();
321 NumUnwinds += Unwinds.size();
322
Jim Grosbach8b818d72009-08-17 16:41:22 +0000323 if (!Invokes.empty()) {
324 // We have invokes, so we need to add register/unregister calls to get
325 // this function onto the global unwind stack.
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000326 //
327 // First thing we need to do is scan the whole function for values that are
328 // live across unwind edges. Each value that is live across an unwind edge
329 // we spill into a stack location, guaranteeing that there is nothing live
330 // across the unwind edge. This process also splits all critical edges
331 // coming out of invoke's.
332 splitLiveRangesLiveAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000333
334 BasicBlock *EntryBB = F.begin();
335 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
336 // that needs to be restored on all exits from the function. This is an
337 // alloca because the value needs to be added to the global context list.
338 unsigned Align = 4; // FIXME: Should be a TLI check?
339 AllocaInst *FunctionContext =
340 new AllocaInst(FunctionContextTy, 0, Align,
341 "fcn_context", F.begin()->begin());
342
343 Value *Idxs[2];
344 const Type *Int32Ty = Type::getInt32Ty(F.getContext());
345 Value *Zero = ConstantInt::get(Int32Ty, 0);
346 // We need to also keep around a reference to the call_site field
347 Idxs[0] = Zero;
348 Idxs[1] = ConstantInt::get(Int32Ty, 1);
349 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
350 "call_site",
351 EntryBB->getTerminator());
352
353 // The exception selector comes back in context->data[1]
354 Idxs[1] = ConstantInt::get(Int32Ty, 2);
355 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
356 "fc_data",
357 EntryBB->getTerminator());
358 Idxs[1] = ConstantInt::get(Int32Ty, 1);
359 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
360 "exc_selector_gep",
361 EntryBB->getTerminator());
362 // The exception value comes back in context->data[0]
363 Idxs[1] = Zero;
364 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
365 "exception_gep",
366 EntryBB->getTerminator());
367
Jim Grosbach8b818d72009-08-17 16:41:22 +0000368 // The result of the eh.selector call will be replaced with a
369 // a reference to the selector value returned in the function
370 // context. We leave the selector itself so the EH analysis later
371 // can use it.
372 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
373 CallInst *I = EH_Selectors[i];
374 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
375 I->replaceAllUsesWith(SelectorVal);
376 }
377 // eh.exception calls are replaced with references to the proper
378 // location in the context. Unlike eh.selector, the eh.exception
379 // calls are removed entirely.
380 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
381 CallInst *I = EH_Exceptions[i];
382 // Possible for there to be duplicates, so check to make sure
383 // the instruction hasn't already been removed.
384 if (!I->getParent()) continue;
385 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000386 const Type *Ty = Type::getInt8PtrTy(F.getContext());
Jim Grosbach606f3d62009-08-17 21:40:03 +0000387 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000388
389 I->replaceAllUsesWith(Val);
390 I->eraseFromParent();
391 }
392
Jim Grosbach8b818d72009-08-17 16:41:22 +0000393 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
394 // branch to a dispatch block for non-zero returns. If we return normally,
395 // we're not handling an exception and just register the function context
396 // and continue.
397
398 // Create the dispatch block. The dispatch block is basically a big switch
399 // statement that goes to all of the invoke landing pads.
400 BasicBlock *DispatchBlock =
401 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
402
403 // Insert a load in the Catch block, and a switch on its value. By default,
404 // we go to a block that just does an unwind (which is the correct action
405 // for a standard call).
Jim Grosbach03825f82010-01-15 00:32:47 +0000406 BasicBlock *UnwindBlock =
407 BasicBlock::Create(F.getContext(), "unwindbb", &F);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000408 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
409
410 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
411 DispatchBlock);
412 SwitchInst *DispatchSwitch =
Jim Grosbach03825f82010-01-15 00:32:47 +0000413 SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
414 DispatchBlock);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000415 // Split the entry block to insert the conditional branch for the setjmp.
416 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
417 "eh.sjlj.setjmp.cont");
418
419 // Populate the Function Context
420 // 1. LSDA address
421 // 2. Personality function address
422 // 3. jmpbuf (save FP and call eh.sjlj.setjmp)
423
424 // LSDA address
425 Idxs[0] = Zero;
426 Idxs[1] = ConstantInt::get(Int32Ty, 4);
427 Value *LSDAFieldPtr =
428 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
429 "lsda_gep",
430 EntryBB->getTerminator());
431 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
432 EntryBB->getTerminator());
433 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
434
435 Idxs[1] = ConstantInt::get(Int32Ty, 3);
436 Value *PersonalityFieldPtr =
437 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
438 "lsda_gep",
439 EntryBB->getTerminator());
440 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
441 EntryBB->getTerminator());
442
443 // Save the frame pointer.
444 Idxs[1] = ConstantInt::get(Int32Ty, 5);
445 Value *FieldPtr
446 = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
447 "jbuf_gep",
448 EntryBB->getTerminator());
449 Idxs[1] = ConstantInt::get(Int32Ty, 0);
450 Value *ElemPtr =
451 GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
452 EntryBB->getTerminator());
453
454 Value *Val = CallInst::Create(FrameAddrFn,
455 ConstantInt::get(Int32Ty, 0),
456 "fp",
457 EntryBB->getTerminator());
458 new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
459 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
460 Value *SetjmpArg =
461 CastInst::Create(Instruction::BitCast, FieldPtr,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000462 Type::getInt8PtrTy(F.getContext()), "",
463 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000464 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
465 "dispatch",
466 EntryBB->getTerminator());
467 // check the return value of the setjmp. non-zero goes to dispatcher
468 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
469 ICmpInst::ICMP_EQ, DispatchVal, Zero,
470 "notunwind");
471 // Nuke the uncond branch.
472 EntryBB->getTerminator()->eraseFromParent();
473
474 // Put in a new condbranch in its place.
475 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
476
477 // Register the function context and make sure it's known to not throw
478 CallInst *Register =
479 CallInst::Create(RegisterFn, FunctionContext, "",
480 ContBlock->getTerminator());
481 Register->setDoesNotThrow();
482
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000483 // At this point, we are all set up, update the invoke instructions
Jim Grosbach8b818d72009-08-17 16:41:22 +0000484 // to mark their call_site values, and fill in the dispatch switch
485 // accordingly.
Jim Grosbachf38a33c2010-01-21 20:10:22 +0000486 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000487 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000488
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000489 // Mark call instructions that aren't nounwind as no-action
490 // (call_site == -1). Skip the entry block, as prior to then, no function
491 // context has been created for this function and any unexpected exceptions
492 // thrown will go directly to the caller's context, which is what we want
493 // anyway, so no need to do anything here.
494 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
495 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
496 if (CallInst *CI = dyn_cast<CallInst>(I)) {
497 // Ignore calls to the EH builtins (eh.selector, eh.exception)
498 Constant *Callee = CI->getCalledFunction();
499 if (Callee != SelectorFn && Callee != ExceptionFn
500 && !CI->doesNotThrow())
501 insertCallSiteStore(CI, -1, CallSite);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000502 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000503 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000504
505 // Replace all unwinds with a branch to the unwind handler.
506 // ??? Should this ever happen with sjlj exceptions?
507 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
508 BranchInst::Create(UnwindBlock, Unwinds[i]);
509 Unwinds[i]->eraseFromParent();
510 }
511
Jim Grosbach8b818d72009-08-17 16:41:22 +0000512 // Finally, for any returns from this function, if this function contains an
513 // invoke, add a call to unregister the function context.
514 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
515 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
516 }
517
518 return true;
519}
520
521bool SjLjEHPass::runOnFunction(Function &F) {
522 bool Res = insertSjLjEHSupport(F);
523 return Res;
524}