blob: ac88441bf9af599d1f2caab2e2ccef3c104c3c04 [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"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000025#include "llvm/Target/TargetData.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000026#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28#include "llvm/Transforms/Utils/Local.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000029#include "llvm/Support/CommandLine.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000030#include "llvm/Support/Debug.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000031#include "llvm/Support/IRBuilder.h"
Bill Wendlingaef508d2011-08-22 23:38:40 +000032#include "llvm/ADT/DenseMap.h"
Bill Wendlingd2dae0c2011-10-24 17:12:36 +000033#include "llvm/ADT/SmallPtrSet.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000034#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000036#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000037using namespace llvm;
38
39STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach8b818d72009-08-17 16:41:22 +000040STATISTIC(NumSpilled, "Number of registers live across unwind edges");
41
42namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000043 class SjLjEHPass : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000044 const TargetLowering *TLI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000045 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000046 Constant *RegisterFn;
47 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000048 Constant *BuiltinSetjmpFn;
49 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000050 Constant *StackAddrFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000051 Constant *LSDAAddrFn;
52 Value *PersonalityFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000053 Constant *CallSiteFn;
Jim Grosbache4ad3872010-10-19 23:27:08 +000054 Constant *DispatchSetupFn;
Bill Wendlingcc8cf972011-09-28 21:56:53 +000055 Constant *FuncCtxFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000056 Value *CallSite;
57 public:
58 static char ID; // Pass identification, replacement for typeid
59 explicit SjLjEHPass(const TargetLowering *tli = NULL)
Owen Anderson90c579d2010-08-06 18:33:48 +000060 : FunctionPass(ID), TLI(tli) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000061 bool doInitialization(Module &M);
62 bool runOnFunction(Function &F);
63
Bill Wendlingd36b3e32011-08-22 18:44:49 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000065 const char *getPassName() const {
66 return "SJLJ Exception Handling preparation";
67 }
68
69 private:
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000070 bool setupEntryBlockAndCallSites(Function &F);
Bill Wendling631d1172011-10-03 21:15:28 +000071 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
Bill Wendlingd5d17002011-10-08 00:56:47 +000072 void lowerIncomingArguments(Function &F);
73 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
Jim Grosbachb58a59b2010-03-04 22:07:46 +000074 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
Jim Grosbach8b818d72009-08-17 16:41:22 +000075 };
76} // end anonymous namespace
77
78char SjLjEHPass::ID = 0;
79
80// Public Interface To the SjLjEHPass pass.
81FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
82 return new SjLjEHPass(TLI);
83}
Jim Grosbacha235d132009-08-23 18:13:48 +000084// doInitialization - Set up decalarations and types needed to process
85// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000086bool SjLjEHPass::doInitialization(Module &M) {
87 // Build the function context structure.
88 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +000089 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
90 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000091 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +000092 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +000093 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);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000108 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000109 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000110 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
111 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Jim Grosbachca752c92010-01-28 01:45:32 +0000112 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000113 DispatchSetupFn
114 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000115 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Jim Grosbacha235d132009-08-23 18:13:48 +0000116 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000117
118 return true;
119}
120
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000121/// insertCallSiteStore - Insert a store of the call-site value to the
122/// function context
123void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
124 Value *CallSite) {
125 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
126 Number);
127 // Insert a store of the call-site number
128 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
129}
130
Jim Grosbach8b818d72009-08-17 16:41:22 +0000131/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
132/// we reach blocks we've already seen.
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000133static void MarkBlocksLiveIn(BasicBlock *BB,
134 SmallPtrSet<BasicBlock*, 64> &LiveBBs) {
135 if (!LiveBBs.insert(BB)) return; // already been here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000136
137 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
138 MarkBlocksLiveIn(*PI, LiveBBs);
139}
140
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000141/// setupFunctionContext - Allocate the function context on the stack and fill
142/// it with all of the data that we know at this point.
Bill Wendling631d1172011-10-03 21:15:28 +0000143Value *SjLjEHPass::
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000144setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000145 BasicBlock *EntryBB = F.begin();
146
147 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
148 // that needs to be restored on all exits from the function. This is an alloca
149 // because the value needs to be added to the global context list.
150 unsigned Align =
151 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
152 AllocaInst *FuncCtx =
153 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
154
155 // Fill in the function context structure.
156 Value *Idxs[2];
157 Type *Int32Ty = Type::getInt32Ty(F.getContext());
158 Value *Zero = ConstantInt::get(Int32Ty, 0);
159 Value *One = ConstantInt::get(Int32Ty, 1);
160
161 // Keep around a reference to the call_site field.
162 Idxs[0] = Zero;
163 Idxs[1] = One;
164 CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
165 EntryBB->getTerminator());
166
167 // Reference the __data field.
168 Idxs[1] = ConstantInt::get(Int32Ty, 2);
169 Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
170 EntryBB->getTerminator());
171
172 // The exception value comes back in context->__data[0].
173 Idxs[1] = Zero;
174 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
175 "exception_gep",
176 EntryBB->getTerminator());
177
178 // The exception selector comes back in context->__data[1].
179 Idxs[1] = One;
180 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
181 "exn_selector_gep",
182 EntryBB->getTerminator());
183
184 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
185 LandingPadInst *LPI = LPads[I];
186 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
187
188 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
189 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
190 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
191
192 Type *LPadType = LPI->getType();
193 Value *LPadVal = UndefValue::get(LPadType);
194 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
195 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
196
197 LPI->replaceAllUsesWith(LPadVal);
198 }
199
200 // Personality function
201 Idxs[1] = ConstantInt::get(Int32Ty, 3);
202 if (!PersonalityFn)
203 PersonalityFn = LPads[0]->getPersonalityFn();
204 Value *PersonalityFieldPtr =
205 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
206 EntryBB->getTerminator());
207 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
208 EntryBB->getTerminator());
209
210 // LSDA address
211 Idxs[1] = ConstantInt::get(Int32Ty, 4);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000212 Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
213 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000214 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
215 EntryBB->getTerminator());
216 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
217
Bill Wendling631d1172011-10-03 21:15:28 +0000218 return FuncCtx;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000219}
220
Bill Wendlingd5d17002011-10-08 00:56:47 +0000221/// lowerIncomingArguments - To avoid having to handle incoming arguments
222/// specially, we lower each arg to a copy instruction in the entry block. This
223/// ensures that the argument value itself cannot be live out of the entry
224/// block.
225void SjLjEHPass::lowerIncomingArguments(Function &F) {
226 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
227 while (isa<AllocaInst>(AfterAllocaInsPt) &&
228 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
229 ++AfterAllocaInsPt;
230
231 for (Function::arg_iterator
232 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
233 Type *Ty = AI->getType();
234
235 // Aggregate types can't be cast, but are legal argument types, so we have
236 // to handle them differently. We use an extract/insert pair as a
237 // lightweight method to achieve the same goal.
238 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
239 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
240 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
241 NI->insertAfter(EI);
242 AI->replaceAllUsesWith(NI);
243
244 // Set the operand of the instructions back to the AllocaInst.
245 EI->setOperand(0, AI);
246 NI->setOperand(0, AI);
247 } else {
248 // This is always a no-op cast because we're casting AI to AI->getType()
249 // so src and destination types are identical. BitCast is the only
250 // possibility.
251 CastInst *NC =
252 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
253 AfterAllocaInsPt);
254 AI->replaceAllUsesWith(NC);
255
256 // Set the operand of the cast instruction back to the AllocaInst.
257 // Normally it's forbidden to replace a CastInst's operand because it
258 // could cause the opcode to reflect an illegal conversion. However, we're
259 // replacing it here with the same value it was constructed with. We do
260 // this because the above replaceAllUsesWith() clobbered the operand, but
261 // we want this one to remain.
262 NC->setOperand(0, AI);
263 }
264 }
265}
266
267/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
268/// edge and spill them.
269void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
270 ArrayRef<InvokeInst*> Invokes) {
271 // Finally, scan the code looking for instructions with bad live ranges.
272 for (Function::iterator
273 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
274 for (BasicBlock::iterator
275 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
276 // Ignore obvious cases we don't have to handle. In particular, most
277 // instructions either have no uses or only have a single use inside the
278 // current block. Ignore them quickly.
279 Instruction *Inst = II;
280 if (Inst->use_empty()) continue;
281 if (Inst->hasOneUse() &&
282 cast<Instruction>(Inst->use_back())->getParent() == BB &&
283 !isa<PHINode>(Inst->use_back())) continue;
284
285 // If this is an alloca in the entry block, it's not a real register
286 // value.
287 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
288 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
289 continue;
290
291 // Avoid iterator invalidation by copying users to a temporary vector.
292 SmallVector<Instruction*, 16> Users;
293 for (Value::use_iterator
294 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
295 Instruction *User = cast<Instruction>(*UI);
296 if (User->getParent() != BB || isa<PHINode>(User))
297 Users.push_back(User);
298 }
299
300 // Find all of the blocks that this value is live in.
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000301 SmallPtrSet<BasicBlock*, 64> LiveBBs;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000302 LiveBBs.insert(Inst->getParent());
303 while (!Users.empty()) {
304 Instruction *U = Users.back();
305 Users.pop_back();
306
307 if (!isa<PHINode>(U)) {
308 MarkBlocksLiveIn(U->getParent(), LiveBBs);
309 } else {
310 // Uses for a PHI node occur in their predecessor block.
311 PHINode *PN = cast<PHINode>(U);
312 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
313 if (PN->getIncomingValue(i) == Inst)
314 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
315 }
316 }
317
318 // Now that we know all of the blocks that this thing is live in, see if
319 // it includes any of the unwind locations.
320 bool NeedsSpill = false;
321 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
322 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
323 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
324 NeedsSpill = true;
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000325 break;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000326 }
327 }
328
329 // If we decided we need a spill, do it.
330 // FIXME: Spilling this way is overkill, as it forces all uses of
331 // the value to be reloaded from the stack slot, even those that aren't
332 // in the unwind blocks. We should be more selective.
333 if (NeedsSpill) {
Bill Wendlingd5d17002011-10-08 00:56:47 +0000334 DemoteRegToStack(*Inst, true);
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000335 ++NumSpilled;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000336 }
337 }
338 }
Bill Wendling0ad56122011-10-21 22:08:56 +0000339
340 // Go through the landing pads and remove any PHIs there.
341 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
342 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
343 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
344
345 // Place PHIs into a set to avoid invalidating the iterator.
346 SmallPtrSet<PHINode*, 8> PHIsToDemote;
347 for (BasicBlock::iterator
348 PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
349 PHIsToDemote.insert(cast<PHINode>(PN));
350 if (PHIsToDemote.empty()) continue;
351
352 // Demote the PHIs to the stack.
353 for (SmallPtrSet<PHINode*, 8>::iterator
354 I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
355 DemotePHIToStack(*I);
356
357 // Move the landingpad instruction back to the top of the landing pad block.
358 LPI->moveBefore(UnwindBlock->begin());
359 }
Bill Wendlingd5d17002011-10-08 00:56:47 +0000360}
361
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000362/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
363/// the function context and marking the call sites with the appropriate
364/// values. These values are used by the DWARF EH emitter.
365bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
366 SmallVector<ReturnInst*, 16> Returns;
367 SmallVector<InvokeInst*, 16> Invokes;
368 SmallVector<LandingPadInst*, 16> LPads;
369
370 // Look through the terminators of the basic blocks to find invokes.
371 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
372 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
373 Invokes.push_back(II);
374 LPads.push_back(II->getUnwindDest()->getLandingPadInst());
375 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
376 Returns.push_back(RI);
377 }
378
379 if (Invokes.empty()) return false;
380
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000381 NumInvokes += Invokes.size();
382
Bill Wendlingd5d17002011-10-08 00:56:47 +0000383 lowerIncomingArguments(F);
384 lowerAcrossUnwindEdges(F, Invokes);
385
Bill Wendling631d1172011-10-03 21:15:28 +0000386 Value *FuncCtx = setupFunctionContext(F, LPads);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000387 BasicBlock *EntryBB = F.begin();
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000388 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling631d1172011-10-03 21:15:28 +0000389
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000390 Value *Idxs[2] = {
Bill Wendling631d1172011-10-03 21:15:28 +0000391 ConstantInt::get(Int32Ty, 0), 0
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000392 };
Bill Wendling631d1172011-10-03 21:15:28 +0000393
394 // Get a reference to the jump buffer.
395 Idxs[1] = ConstantInt::get(Int32Ty, 5);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000396 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
397 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000398
Bill Wendling631d1172011-10-03 21:15:28 +0000399 // Save the frame pointer.
400 Idxs[1] = ConstantInt::get(Int32Ty, 0);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000401 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
402 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000403
404 Value *Val = CallInst::Create(FrameAddrFn,
405 ConstantInt::get(Int32Ty, 0),
406 "fp",
407 EntryBB->getTerminator());
408 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
409
410 // Save the stack pointer.
411 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000412 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
413 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000414
415 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000416 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
417
418 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000419 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
420 Type::getInt8PtrTy(F.getContext()), "",
421 EntryBB->getTerminator());
Bill Wendlingf8520d52011-10-03 22:42:40 +0000422 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000423
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000424 // Store a pointer to the function context so that the back-end will know
425 // where to look for it.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000426 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
427 Type::getInt8PtrTy(F.getContext()), "",
428 EntryBB->getTerminator());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000429 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000430
431 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendling2130ab02011-10-05 22:04:08 +0000432 // their call_site values.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000433 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
434 insertCallSiteStore(Invokes[I], I + 1, CallSite);
435
436 ConstantInt *CallSiteNum =
437 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
438
439 // Record the call site value for the back end so it stays associated with
440 // the invoke.
441 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
442 }
443
444 // Mark call instructions that aren't nounwind as no-action (call_site ==
445 // -1). Skip the entry block, as prior to then, no function context has been
446 // created for this function and any unexpected exceptions thrown will go
447 // directly to the caller's context, which is what we want anyway, so no need
448 // to do anything here.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000449 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000450 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
451 if (CallInst *CI = dyn_cast<CallInst>(I)) {
452 if (!CI->doesNotThrow())
453 insertCallSiteStore(CI, -1, CallSite);
454 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
455 insertCallSiteStore(RI, -1, CallSite);
456 }
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000457
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000458 // Register the function context and make sure it's known to not throw
Bill Wendling631d1172011-10-03 21:15:28 +0000459 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000460 EntryBB->getTerminator());
461 Register->setDoesNotThrow();
462
463 // Finally, for any returns from this function, if this function contains an
464 // invoke, add a call to unregister the function context.
465 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling631d1172011-10-03 21:15:28 +0000466 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000467
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000468 return true;
469}
470
Jim Grosbach8b818d72009-08-17 16:41:22 +0000471bool SjLjEHPass::runOnFunction(Function &F) {
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000472 bool Res = setupEntryBlockAndCallSites(F);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000473 return Res;
474}