blob: 61f13abcdaf017bd5cd025cee77ea79bd9e99b1f [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"
Jim Grosbach8fc3b692009-08-20 01:03:48 +000027#include "llvm/ADT/DenseMap.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000028#include "llvm/ADT/Statistic.h"
Jim Grosbach606f3d62009-08-17 21:40:03 +000029#include "llvm/ADT/SmallVector.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Compiler.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000035using namespace llvm;
36
37STATISTIC(NumInvokes, "Number of invokes replaced");
38STATISTIC(NumUnwinds, "Number of unwinds replaced");
39STATISTIC(NumSpilled, "Number of registers live across unwind edges");
40
41namespace {
42 class VISIBILITY_HIDDEN SjLjEHPass : public FunctionPass {
43
44 const TargetLowering *TLI;
45
46 const Type *FunctionContextTy;
47 Constant *RegisterFn;
48 Constant *UnregisterFn;
49 Constant *ResumeFn;
50 Constant *BuiltinSetjmpFn;
51 Constant *FrameAddrFn;
52 Constant *LSDAAddrFn;
53 Value *PersonalityFn;
54 Constant *Selector32Fn;
55 Constant *Selector64Fn;
56 Constant *ExceptionFn;
57
58 Value *CallSite;
59 public:
60 static char ID; // Pass identification, replacement for typeid
61 explicit SjLjEHPass(const TargetLowering *tli = NULL)
62 : FunctionPass(&ID), TLI(tli) { }
63 bool doInitialization(Module &M);
64 bool runOnFunction(Function &F);
65
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
67 const char *getPassName() const {
68 return "SJLJ Exception Handling preparation";
69 }
70
71 private:
72 void markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
Jim Grosbach8fc3b692009-08-20 01:03:48 +000073 Value *CallSite);
Jim Grosbach606f3d62009-08-17 21:40:03 +000074 void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +000075 bool insertSjLjEHSupport(Function &F);
76 };
77} // end anonymous namespace
78
79char SjLjEHPass::ID = 0;
80
81// Public Interface To the SjLjEHPass pass.
82FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
83 return new SjLjEHPass(TLI);
84}
Jim Grosbacha235d132009-08-23 18:13:48 +000085// doInitialization - Set up decalarations and types needed to process
86// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000087bool SjLjEHPass::doInitialization(Module &M) {
88 // Build the function context structure.
89 // builtin_setjmp uses a five word jbuf
90 const Type *VoidPtrTy =
91 PointerType::getUnqual(Type::getInt8Ty(M.getContext()));
92 const Type *Int32Ty = Type::getInt32Ty(M.getContext());
93 FunctionContextTy =
94 StructType::get(M.getContext(),
95 VoidPtrTy, // __prev
96 Int32Ty, // call_site
97 ArrayType::get(Int32Ty, 4), // __data
98 VoidPtrTy, // __personality
99 VoidPtrTy, // __lsda
100 ArrayType::get(VoidPtrTy, 5), // __jbuf
101 NULL);
102 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
103 Type::getVoidTy(M.getContext()),
104 PointerType::getUnqual(FunctionContextTy),
105 (Type *)0);
106 UnregisterFn =
107 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
108 Type::getVoidTy(M.getContext()),
109 PointerType::getUnqual(FunctionContextTy),
110 (Type *)0);
111 ResumeFn =
112 M.getOrInsertFunction("_Unwind_SjLj_Resume",
113 Type::getVoidTy(M.getContext()),
114 VoidPtrTy,
115 (Type *)0);
116 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
117 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
118 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
119 Selector32Fn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector_i32);
120 Selector64Fn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector_i64);
121 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbacha235d132009-08-23 18:13:48 +0000122 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000123
124 return true;
125}
126
127/// markInvokeCallSite - Insert code to mark the call_site for this invoke
128void SjLjEHPass::markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
Jim Grosbach8fc3b692009-08-20 01:03:48 +0000129 Value *CallSite) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000130 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
131 InvokeNo);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000132
133 // If the unwind edge has phi nodes, split the edge.
134 if (isa<PHINode>(II->getUnwindDest()->begin())) {
135 SplitCriticalEdge(II, 1, this);
136
137 // If there are any phi nodes left, they must have a single predecessor.
138 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
139 PN->replaceAllUsesWith(PN->getIncomingValue(0));
140 PN->eraseFromParent();
141 }
142 }
143
144 // Insert a store of the invoke num before the invoke and store zero into the
145 // location afterward.
146 new StoreInst(CallSiteNoC, CallSite, true, II); // volatile
147
Jim Grosbach8b818d72009-08-17 16:41:22 +0000148 // We still want this to look like an invoke so we emit the LSDA properly
149 // FIXME: ??? Or will this cause strangeness with mis-matched IDs like
150 // when it was in the front end?
151}
152
153/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
154/// we reach blocks we've already seen.
155static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
156 if (!LiveBBs.insert(BB).second) return; // already been here.
157
158 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
159 MarkBlocksLiveIn(*PI, LiveBBs);
160}
161
Jim Grosbach606f3d62009-08-17 21:40:03 +0000162/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
163/// we spill into a stack location, guaranteeing that there is nothing live
164/// across the unwind edge. This process also splits all critical edges
165/// coming out of invoke's.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000166void SjLjEHPass::
Jim Grosbach606f3d62009-08-17 21:40:03 +0000167splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000168 // First step, split all critical edges from invoke instructions.
169 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
170 InvokeInst *II = Invokes[i];
171 SplitCriticalEdge(II, 0, this);
172 SplitCriticalEdge(II, 1, this);
173 assert(!isa<PHINode>(II->getNormalDest()) &&
174 !isa<PHINode>(II->getUnwindDest()) &&
175 "critical edge splitting left single entry phi nodes?");
176 }
177
178 Function *F = Invokes.back()->getParent()->getParent();
179
180 // To avoid having to handle incoming arguments specially, we lower each arg
181 // to a copy instruction in the entry block. This ensures that the argument
182 // value itself cannot be live across the entry block.
183 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
184 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
185 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
186 ++AfterAllocaInsertPt;
187 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
188 AI != E; ++AI) {
189 // This is always a no-op cast because we're casting AI to AI->getType() so
190 // src and destination types are identical. BitCast is the only possibility.
191 CastInst *NC = new BitCastInst(
192 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
193 AI->replaceAllUsesWith(NC);
194 // Normally its is forbidden to replace a CastInst's operand because it
195 // could cause the opcode to reflect an illegal conversion. However, we're
196 // replacing it here with the same value it was constructed with to simply
197 // make NC its user.
198 NC->setOperand(0, AI);
199 }
200
201 // Finally, scan the code looking for instructions with bad live ranges.
202 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
203 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
204 // Ignore obvious cases we don't have to handle. In particular, most
205 // instructions either have no uses or only have a single use inside the
206 // current block. Ignore them quickly.
207 Instruction *Inst = II;
208 if (Inst->use_empty()) continue;
209 if (Inst->hasOneUse() &&
210 cast<Instruction>(Inst->use_back())->getParent() == BB &&
211 !isa<PHINode>(Inst->use_back())) continue;
212
213 // If this is an alloca in the entry block, it's not a real register
214 // value.
215 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
216 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
217 continue;
218
219 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000220 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000221 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
222 UI != E; ++UI) {
223 Instruction *User = cast<Instruction>(*UI);
224 if (User->getParent() != BB || isa<PHINode>(User))
225 Users.push_back(User);
226 }
227
Jim Grosbach8b818d72009-08-17 16:41:22 +0000228 // Find all of the blocks that this value is live in.
229 std::set<BasicBlock*> LiveBBs;
230 LiveBBs.insert(Inst->getParent());
231 while (!Users.empty()) {
232 Instruction *U = Users.back();
233 Users.pop_back();
234
235 if (!isa<PHINode>(U)) {
236 MarkBlocksLiveIn(U->getParent(), LiveBBs);
237 } else {
238 // Uses for a PHI node occur in their predecessor block.
239 PHINode *PN = cast<PHINode>(U);
240 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
241 if (PN->getIncomingValue(i) == Inst)
242 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
243 }
244 }
245
246 // Now that we know all of the blocks that this thing is live in, see if
247 // it includes any of the unwind locations.
248 bool NeedsSpill = false;
249 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
250 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
251 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
252 NeedsSpill = true;
253 }
254 }
255
256 // If we decided we need a spill, do it.
257 if (NeedsSpill) {
258 ++NumSpilled;
259 DemoteRegToStack(*Inst, true);
260 }
261 }
262}
263
264bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000265 SmallVector<ReturnInst*,16> Returns;
266 SmallVector<UnwindInst*,16> Unwinds;
267 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000268
269 // Look through the terminators of the basic blocks to find invokes, returns
270 // and unwinds
271 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
272 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
273 // Remember all return instructions in case we insert an invoke into this
274 // function.
275 Returns.push_back(RI);
276 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
277 Invokes.push_back(II);
278 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
279 Unwinds.push_back(UI);
280 }
281 // If we don't have any invokes or unwinds, there's nothing to do.
282 if (Unwinds.empty() && Invokes.empty()) return false;
283
Jim Grosbacha235d132009-08-23 18:13:48 +0000284 // Find the eh.selector.* and eh.exception calls. We'll use the first
285 // eh.selector to determine the right personality function to use. For
286 // SJLJ, we always use the same personality for the whole function,
287 // not on a per-selector basis.
288 // FIXME: That's a bit ugly. Better way?
289 SmallVector<CallInst*,16> EH_Selectors;
290 SmallVector<CallInst*,16> EH_Exceptions;
291 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
292 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
293 if (CallInst *CI = dyn_cast<CallInst>(I)) {
294 if (CI->getCalledFunction() == Selector32Fn ||
295 CI->getCalledFunction() == Selector64Fn) {
296 if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
297 EH_Selectors.push_back(CI);
298 } else if (CI->getCalledFunction() == ExceptionFn) {
299 EH_Exceptions.push_back(CI);
300 }
301 }
302 }
303 }
304 // If we don't have any eh.selector calls, we can't determine the personality
305 // function. Without a personality function, we can't process exceptions.
306 if (!PersonalityFn) return false;
307
Jim Grosbach8b818d72009-08-17 16:41:22 +0000308 NumInvokes += Invokes.size();
309 NumUnwinds += Unwinds.size();
310
Jim Grosbach8b818d72009-08-17 16:41:22 +0000311 if (!Invokes.empty()) {
312 // We have invokes, so we need to add register/unregister calls to get
313 // this function onto the global unwind stack.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000314
315 BasicBlock *EntryBB = F.begin();
316 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
317 // that needs to be restored on all exits from the function. This is an
318 // alloca because the value needs to be added to the global context list.
319 unsigned Align = 4; // FIXME: Should be a TLI check?
320 AllocaInst *FunctionContext =
321 new AllocaInst(FunctionContextTy, 0, Align,
322 "fcn_context", F.begin()->begin());
323
324 Value *Idxs[2];
325 const Type *Int32Ty = Type::getInt32Ty(F.getContext());
326 Value *Zero = ConstantInt::get(Int32Ty, 0);
327 // We need to also keep around a reference to the call_site field
328 Idxs[0] = Zero;
329 Idxs[1] = ConstantInt::get(Int32Ty, 1);
330 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
331 "call_site",
332 EntryBB->getTerminator());
333
334 // The exception selector comes back in context->data[1]
335 Idxs[1] = ConstantInt::get(Int32Ty, 2);
336 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
337 "fc_data",
338 EntryBB->getTerminator());
339 Idxs[1] = ConstantInt::get(Int32Ty, 1);
340 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
341 "exc_selector_gep",
342 EntryBB->getTerminator());
343 // The exception value comes back in context->data[0]
344 Idxs[1] = Zero;
345 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
346 "exception_gep",
347 EntryBB->getTerminator());
348
Jim Grosbach8b818d72009-08-17 16:41:22 +0000349 // The result of the eh.selector call will be replaced with a
350 // a reference to the selector value returned in the function
351 // context. We leave the selector itself so the EH analysis later
352 // can use it.
353 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
354 CallInst *I = EH_Selectors[i];
355 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
356 I->replaceAllUsesWith(SelectorVal);
357 }
358 // eh.exception calls are replaced with references to the proper
359 // location in the context. Unlike eh.selector, the eh.exception
360 // calls are removed entirely.
361 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
362 CallInst *I = EH_Exceptions[i];
363 // Possible for there to be duplicates, so check to make sure
364 // the instruction hasn't already been removed.
365 if (!I->getParent()) continue;
366 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Jim Grosbach606f3d62009-08-17 21:40:03 +0000367 Type *Ty = PointerType::getUnqual(Type::getInt8Ty(F.getContext()));
368 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000369
370 I->replaceAllUsesWith(Val);
371 I->eraseFromParent();
372 }
373
374
375
376
377 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
378 // branch to a dispatch block for non-zero returns. If we return normally,
379 // we're not handling an exception and just register the function context
380 // and continue.
381
382 // Create the dispatch block. The dispatch block is basically a big switch
383 // statement that goes to all of the invoke landing pads.
384 BasicBlock *DispatchBlock =
385 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
386
387 // Insert a load in the Catch block, and a switch on its value. By default,
388 // we go to a block that just does an unwind (which is the correct action
389 // for a standard call).
390 BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwindbb", &F);
391 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
392
393 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
394 DispatchBlock);
395 SwitchInst *DispatchSwitch =
396 SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(), DispatchBlock);
397 // Split the entry block to insert the conditional branch for the setjmp.
398 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
399 "eh.sjlj.setjmp.cont");
400
401 // Populate the Function Context
402 // 1. LSDA address
403 // 2. Personality function address
404 // 3. jmpbuf (save FP and call eh.sjlj.setjmp)
405
406 // LSDA address
407 Idxs[0] = Zero;
408 Idxs[1] = ConstantInt::get(Int32Ty, 4);
409 Value *LSDAFieldPtr =
410 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
411 "lsda_gep",
412 EntryBB->getTerminator());
413 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
414 EntryBB->getTerminator());
415 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
416
417 Idxs[1] = ConstantInt::get(Int32Ty, 3);
418 Value *PersonalityFieldPtr =
419 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
420 "lsda_gep",
421 EntryBB->getTerminator());
422 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
423 EntryBB->getTerminator());
424
425 // Save the frame pointer.
426 Idxs[1] = ConstantInt::get(Int32Ty, 5);
427 Value *FieldPtr
428 = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
429 "jbuf_gep",
430 EntryBB->getTerminator());
431 Idxs[1] = ConstantInt::get(Int32Ty, 0);
432 Value *ElemPtr =
433 GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
434 EntryBB->getTerminator());
435
436 Value *Val = CallInst::Create(FrameAddrFn,
437 ConstantInt::get(Int32Ty, 0),
438 "fp",
439 EntryBB->getTerminator());
440 new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
441 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
442 Value *SetjmpArg =
443 CastInst::Create(Instruction::BitCast, FieldPtr,
444 Type::getInt8Ty(F.getContext())->getPointerTo(), "",
445 EntryBB->getTerminator());
446 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
447 "dispatch",
448 EntryBB->getTerminator());
449 // check the return value of the setjmp. non-zero goes to dispatcher
450 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
451 ICmpInst::ICMP_EQ, DispatchVal, Zero,
452 "notunwind");
453 // Nuke the uncond branch.
454 EntryBB->getTerminator()->eraseFromParent();
455
456 // Put in a new condbranch in its place.
457 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
458
459 // Register the function context and make sure it's known to not throw
460 CallInst *Register =
461 CallInst::Create(RegisterFn, FunctionContext, "",
462 ContBlock->getTerminator());
463 Register->setDoesNotThrow();
464
Jim Grosbach8fc3b692009-08-20 01:03:48 +0000465 // At this point, we are all set up. Update the invoke instructions
Jim Grosbach8b818d72009-08-17 16:41:22 +0000466 // to mark their call_site values, and fill in the dispatch switch
467 // accordingly.
Jim Grosbach8fc3b692009-08-20 01:03:48 +0000468 DenseMap<BasicBlock*,unsigned> PadSites;
469 unsigned NextCallSiteValue = 1;
470 for (SmallVector<InvokeInst*,16>::iterator I = Invokes.begin(),
471 E = Invokes.end(); I < E; ++I) {
472 unsigned CallSiteValue;
473 BasicBlock *LandingPad = (*I)->getSuccessor(1);
474 // landing pads can be shared. If we see a landing pad again, we
475 // want to make sure to use the same call site index so the dispatch
476 // will go to the right place.
477 CallSiteValue = PadSites[LandingPad];
478 if (!CallSiteValue) {
479 CallSiteValue = NextCallSiteValue++;
480 PadSites[LandingPad] = CallSiteValue;
481 // Add a switch case to our unwind block. The runtime comes back
482 // to the dispatcher with the call_site - 1 in the context. Odd,
483 // but there it is.
484 ConstantInt *SwitchValC =
485 ConstantInt::get(Type::getInt32Ty((*I)->getContext()),
486 CallSiteValue - 1);
487 DispatchSwitch->addCase(SwitchValC, (*I)->getUnwindDest());
488 }
489 markInvokeCallSite(*I, CallSiteValue, CallSite);
490 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000491
492 // The front end has likely added calls to _Unwind_Resume. We need
493 // to find those calls and mark the call_site as -1 immediately prior.
494 // resume is a noreturn function, so any block that has a call to it
495 // should end in an 'unreachable' instruction with the call immediately
496 // prior. That's how we'll search.
497 // ??? There's got to be a better way. this is fugly.
498 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
499 if ((dyn_cast<UnreachableInst>(BB->getTerminator()))) {
500 BasicBlock::iterator I = BB->getTerminator();
501 // Check the previous instruction and see if it's a resume call
502 if (I == BB->begin()) continue;
503 if (CallInst *CI = dyn_cast<CallInst>(--I)) {
504 if (CI->getCalledFunction() == ResumeFn) {
Daniel Dunbar5d17edd2009-08-17 18:41:42 +0000505 Value *NegativeOne = Constant::getAllOnesValue(Int32Ty);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000506 new StoreInst(NegativeOne, CallSite, true, I); // volatile
507 }
508 }
509 }
510
511 // Replace all unwinds with a branch to the unwind handler.
512 // ??? Should this ever happen with sjlj exceptions?
513 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
514 BranchInst::Create(UnwindBlock, Unwinds[i]);
515 Unwinds[i]->eraseFromParent();
516 }
517
Jim Grosbach8fc3b692009-08-20 01:03:48 +0000518 // Scan the whole function for values that are live across unwind edges.
519 // Each value that is live across an unwind edge we spill into a stack
520 // location, guaranteeing that there is nothing live across the unwind
521 // edge. This process also splits all critical edges coming out of
522 // invoke's.
523 splitLiveRangesLiveAcrossInvokes(Invokes);
524
Jim Grosbach8b818d72009-08-17 16:41:22 +0000525 // Finally, for any returns from this function, if this function contains an
526 // invoke, add a call to unregister the function context.
527 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
528 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
529 }
530
531 return true;
532}
533
534bool SjLjEHPass::runOnFunction(Function &F) {
535 bool Res = insertSjLjEHSupport(F);
536 return Res;
537}