blob: e5ced3e6ae575f4557476a640109c0ed9f5ed17c [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 Wendlingd36b3e32011-08-22 18:44:49 +000033#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000035#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000036using namespace llvm;
37
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000038static cl::opt<bool> DisableOldSjLjEH("disable-old-sjlj-eh", cl::Hidden,
39 cl::desc("Disable the old SjLj EH preparation pass"));
40
Jim Grosbach8b818d72009-08-17 16:41:22 +000041STATISTIC(NumInvokes, "Number of invokes replaced");
42STATISTIC(NumUnwinds, "Number of unwinds replaced");
43STATISTIC(NumSpilled, "Number of registers live across unwind edges");
44
45namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000046 class SjLjEHPass : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000047 const TargetLowering *TLI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000048 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000049 Constant *RegisterFn;
50 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000051 Constant *BuiltinSetjmpFn;
52 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000053 Constant *StackAddrFn;
54 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000055 Constant *LSDAAddrFn;
56 Value *PersonalityFn;
Duncan Sandsb01bbdc2009-10-14 16:11:37 +000057 Constant *SelectorFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000058 Constant *ExceptionFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000059 Constant *CallSiteFn;
Jim Grosbache4ad3872010-10-19 23:27:08 +000060 Constant *DispatchSetupFn;
Bill Wendlingcc8cf972011-09-28 21:56:53 +000061 Constant *FuncCtxFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000062 Value *CallSite;
Bill Wendlingaef508d2011-08-22 23:38:40 +000063 DenseMap<InvokeInst*, BasicBlock*> LPadSuccMap;
Jim Grosbach8b818d72009-08-17 16:41:22 +000064 public:
65 static char ID; // Pass identification, replacement for typeid
66 explicit SjLjEHPass(const TargetLowering *tli = NULL)
Owen Anderson90c579d2010-08-06 18:33:48 +000067 : FunctionPass(ID), TLI(tli) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000068 bool doInitialization(Module &M);
69 bool runOnFunction(Function &F);
70
Bill Wendlingd36b3e32011-08-22 18:44:49 +000071 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000072 const char *getPassName() const {
73 return "SJLJ Exception Handling preparation";
74 }
75
76 private:
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000077 bool setupEntryBlockAndCallSites(Function &F);
Bill Wendling631d1172011-10-03 21:15:28 +000078 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000079
Jim Grosbachb58a59b2010-03-04 22:07:46 +000080 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
81 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
Jim Grosbach0bb61c52009-08-31 01:35:03 +000082 SwitchInst *CatchSwitch);
Jim Grosbach288694f2010-06-15 18:53:34 +000083 void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
Bill Wendling36699152011-09-12 21:56:59 +000084 void splitLandingPad(InvokeInst *II);
Jim Grosbach8b818d72009-08-17 16:41:22 +000085 bool insertSjLjEHSupport(Function &F);
86 };
87} // end anonymous namespace
88
89char SjLjEHPass::ID = 0;
90
91// Public Interface To the SjLjEHPass pass.
92FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
93 return new SjLjEHPass(TLI);
94}
Jim Grosbacha235d132009-08-23 18:13:48 +000095// doInitialization - Set up decalarations and types needed to process
96// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000097bool SjLjEHPass::doInitialization(Module &M) {
98 // Build the function context structure.
99 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +0000100 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
101 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000102 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +0000103 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +0000104 Int32Ty, // call_site
105 ArrayType::get(Int32Ty, 4), // __data
106 VoidPtrTy, // __personality
107 VoidPtrTy, // __lsda
108 ArrayType::get(VoidPtrTy, 5), // __jbuf
109 NULL);
110 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
111 Type::getVoidTy(M.getContext()),
112 PointerType::getUnqual(FunctionContextTy),
113 (Type *)0);
114 UnregisterFn =
115 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
116 Type::getVoidTy(M.getContext()),
117 PointerType::getUnqual(FunctionContextTy),
118 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000119 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000120 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
121 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000122 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
123 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000124 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000125 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000126 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000127 DispatchSetupFn
128 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000129 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Jim Grosbacha235d132009-08-23 18:13:48 +0000130 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000131
132 return true;
133}
134
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000135/// insertCallSiteStore - Insert a store of the call-site value to the
136/// function context
137void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
138 Value *CallSite) {
139 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
140 Number);
141 // Insert a store of the call-site number
142 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
143}
144
Bill Wendling36699152011-09-12 21:56:59 +0000145/// splitLandingPad - Split a landing pad. This takes considerable care because
146/// of PHIs and other nasties. The problem is that the jump table needs to jump
147/// to the landing pad block. However, the landing pad block can be jumped to
148/// only by an invoke instruction. So we clone the landingpad instruction into
149/// its own basic block, have the invoke jump to there. The landingpad
150/// instruction's basic block's successor is now the target for the jump table.
151///
152/// But because of PHI nodes, we need to create another basic block for the jump
153/// table to jump to. This is definitely a hack, because the values for the PHI
154/// nodes may not be defined on the edge from the jump table. But that's okay,
155/// because the jump table is simply a construct to mimic what is happening in
156/// the CFG. So the values are mysteriously there, even though there is no value
157/// for the PHI from the jump table's edge (hence calling this a hack).
158void SjLjEHPass::splitLandingPad(InvokeInst *II) {
159 SmallVector<BasicBlock*, 2> NewBBs;
160 SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
161 ".1", ".2", this, NewBBs);
162
163 // Create an empty block so that the jump table has something to jump to
164 // which doesn't have any PHI nodes.
165 BasicBlock *LPad = NewBBs[0];
166 BasicBlock *Succ = *succ_begin(LPad);
167 BasicBlock *JumpTo = BasicBlock::Create(II->getContext(), "jt.land",
168 LPad->getParent(), Succ);
169 LPad->getTerminator()->eraseFromParent();
170 BranchInst::Create(JumpTo, LPad);
171 BranchInst::Create(Succ, JumpTo);
172 LPadSuccMap[II] = JumpTo;
173
174 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
175 PHINode *PN = cast<PHINode>(I);
176 Value *Val = PN->removeIncomingValue(LPad, false);
177 PN->addIncoming(Val, JumpTo);
178 }
179}
180
Jim Grosbach8b818d72009-08-17 16:41:22 +0000181/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000182void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000183 Value *CallSite,
184 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000185 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000186 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000187 // The runtime comes back to the dispatcher with the call_site - 1 in
188 // the context. Odd, but there it is.
189 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
Bill Wendling36699152011-09-12 21:56:59 +0000190 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000191
192 // If the unwind edge has phi nodes, split the edge.
193 if (isa<PHINode>(II->getUnwindDest()->begin())) {
Bill Wendling51fb91c2011-08-26 21:18:55 +0000194 // FIXME: New EH - This if-condition will be always true in the new scheme.
Bill Wendling36699152011-09-12 21:56:59 +0000195 if (II->getUnwindDest()->isLandingPad())
196 splitLandingPad(II);
197 else
Bill Wendling51fb91c2011-08-26 21:18:55 +0000198 SplitCriticalEdge(II, 1, this);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000199
200 // If there are any phi nodes left, they must have a single predecessor.
201 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
202 PN->replaceAllUsesWith(PN->getIncomingValue(0));
203 PN->eraseFromParent();
204 }
205 }
206
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000207 // Insert the store of the call site value
208 insertCallSiteStore(II, InvokeNo, CallSite);
209
210 // Record the call site value for the back end so it stays associated with
211 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000212 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000213
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000214 // Add a switch case to our unwind block.
Bill Wendlingaef508d2011-08-22 23:38:40 +0000215 if (BasicBlock *SuccBB = LPadSuccMap[II]) {
216 CatchSwitch->addCase(SwitchValC, SuccBB);
217 } else {
218 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
219 }
220
Jim Grosbachca752c92010-01-28 01:45:32 +0000221 // We still want this to look like an invoke so we emit the LSDA properly,
222 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000223}
224
225/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
226/// we reach blocks we've already seen.
227static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
228 if (!LiveBBs.insert(BB).second) return; // already been here.
229
230 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
231 MarkBlocksLiveIn(*PI, LiveBBs);
232}
233
Jim Grosbach606f3d62009-08-17 21:40:03 +0000234/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
235/// we spill into a stack location, guaranteeing that there is nothing live
236/// across the unwind edge. This process also splits all critical edges
237/// coming out of invoke's.
Jim Grosbach2f3257e2010-06-01 18:06:35 +0000238/// FIXME: Move this function to a common utility file (Local.cpp?) so
239/// both SjLj and LowerInvoke can use it.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000240void SjLjEHPass::
Jim Grosbach288694f2010-06-15 18:53:34 +0000241splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000242 // First step, split all critical edges from invoke instructions.
243 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
244 InvokeInst *II = Invokes[i];
245 SplitCriticalEdge(II, 0, this);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000246
247 // FIXME: New EH - This if-condition will be always true in the new scheme.
Bill Wendling36699152011-09-12 21:56:59 +0000248 if (II->getUnwindDest()->isLandingPad())
249 splitLandingPad(II);
250 else
Bill Wendlingaef508d2011-08-22 23:38:40 +0000251 SplitCriticalEdge(II, 1, this);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000252
Jim Grosbach8b818d72009-08-17 16:41:22 +0000253 assert(!isa<PHINode>(II->getNormalDest()) &&
254 !isa<PHINode>(II->getUnwindDest()) &&
Bill Wendlingd36b3e32011-08-22 18:44:49 +0000255 "Critical edge splitting left single entry phi nodes?");
Jim Grosbach8b818d72009-08-17 16:41:22 +0000256 }
257
258 Function *F = Invokes.back()->getParent()->getParent();
259
260 // To avoid having to handle incoming arguments specially, we lower each arg
261 // to a copy instruction in the entry block. This ensures that the argument
262 // value itself cannot be live across the entry block.
263 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
264 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
265 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
266 ++AfterAllocaInsertPt;
267 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
268 AI != E; ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000269 Type *Ty = AI->getType();
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000270 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbachdc58b252010-06-01 18:04:09 +0000271 // to handle them differently. We use an extract/insert pair as a
272 // lightweight method to achieve the same goal.
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000273 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
274 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbachdc58b252010-06-01 18:04:09 +0000275 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
276 NI->insertAfter(EI);
277 AI->replaceAllUsesWith(NI);
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000278 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbachdc58b252010-06-01 18:04:09 +0000279 EI->setOperand(0, AI);
280 NI->setOperand(0, AI);
281 } else {
282 // This is always a no-op cast because we're casting AI to AI->getType()
283 // so src and destination types are identical. BitCast is the only
284 // possibility.
285 CastInst *NC = new BitCastInst(
286 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
287 AI->replaceAllUsesWith(NC);
288 // Set the operand of the cast instruction back to the AllocaInst.
289 // Normally it's forbidden to replace a CastInst's operand because it
290 // could cause the opcode to reflect an illegal conversion. However,
291 // we're replacing it here with the same value it was constructed with.
292 // We do this because the above replaceAllUsesWith() clobbered the
293 // operand, but we want this one to remain.
294 NC->setOperand(0, AI);
295 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000296 }
297
298 // Finally, scan the code looking for instructions with bad live ranges.
299 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
300 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
301 // Ignore obvious cases we don't have to handle. In particular, most
302 // instructions either have no uses or only have a single use inside the
303 // current block. Ignore them quickly.
304 Instruction *Inst = II;
305 if (Inst->use_empty()) continue;
306 if (Inst->hasOneUse() &&
307 cast<Instruction>(Inst->use_back())->getParent() == BB &&
308 !isa<PHINode>(Inst->use_back())) continue;
309
310 // If this is an alloca in the entry block, it's not a real register
311 // value.
312 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
313 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
314 continue;
315
316 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000317 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000318 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
319 UI != E; ++UI) {
320 Instruction *User = cast<Instruction>(*UI);
321 if (User->getParent() != BB || isa<PHINode>(User))
322 Users.push_back(User);
323 }
324
Jim Grosbach8b818d72009-08-17 16:41:22 +0000325 // Find all of the blocks that this value is live in.
326 std::set<BasicBlock*> LiveBBs;
327 LiveBBs.insert(Inst->getParent());
328 while (!Users.empty()) {
329 Instruction *U = Users.back();
330 Users.pop_back();
331
332 if (!isa<PHINode>(U)) {
333 MarkBlocksLiveIn(U->getParent(), LiveBBs);
334 } else {
335 // Uses for a PHI node occur in their predecessor block.
336 PHINode *PN = cast<PHINode>(U);
337 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
338 if (PN->getIncomingValue(i) == Inst)
339 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
340 }
341 }
342
343 // Now that we know all of the blocks that this thing is live in, see if
344 // it includes any of the unwind locations.
345 bool NeedsSpill = false;
346 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
347 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
348 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
349 NeedsSpill = true;
350 }
351 }
352
353 // If we decided we need a spill, do it.
Jim Grosbach956352e2010-06-16 18:45:08 +0000354 // FIXME: Spilling this way is overkill, as it forces all uses of
355 // the value to be reloaded from the stack slot, even those that aren't
356 // in the unwind blocks. We should be more selective.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000357 if (NeedsSpill) {
358 ++NumSpilled;
359 DemoteRegToStack(*Inst, true);
360 }
361 }
362}
363
Bill Wendlingaef508d2011-08-22 23:38:40 +0000364/// CreateLandingPadLoad - Load the exception handling values and insert them
365/// into a structure.
366static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
367 Value *SelAddr,
368 BasicBlock::iterator InsertPt) {
369 Value *Exn = new LoadInst(ExnAddr, "exn", false,
370 InsertPt);
371 Type *Ty = Type::getInt8PtrTy(F.getContext());
372 Exn = CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
373 Value *Sel = new LoadInst(SelAddr, "sel", false, InsertPt);
374
375 Ty = StructType::get(Exn->getType(), Sel->getType(), NULL);
376 InsertValueInst *LPadVal = InsertValueInst::Create(llvm::UndefValue::get(Ty),
377 Exn, 0,
378 "lpad.val", InsertPt);
379 return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
380}
381
382/// ReplaceLandingPadVal - Replace the landingpad instruction's value with a
383/// load from the stored values (via CreateLandingPadLoad). This looks through
384/// PHI nodes, and removes them if they are dead.
385static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *ExnAddr,
386 Value *SelAddr) {
387 if (Inst->use_empty()) return;
388
389 while (!Inst->use_empty()) {
390 Instruction *I = cast<Instruction>(Inst->use_back());
391
392 if (PHINode *PN = dyn_cast<PHINode>(I)) {
393 ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
394 if (PN->use_empty()) PN->eraseFromParent();
395 continue;
396 }
397
Bill Wendlingfc8713f2011-08-23 22:55:03 +0000398 I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I));
Bill Wendlingaef508d2011-08-22 23:38:40 +0000399 }
400}
401
Jim Grosbach8b818d72009-08-17 16:41:22 +0000402bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000403 SmallVector<ReturnInst*,16> Returns;
404 SmallVector<UnwindInst*,16> Unwinds;
405 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000406
407 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000408 // and unwinds.
409 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000410 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
411 // Remember all return instructions in case we insert an invoke into this
412 // function.
413 Returns.push_back(RI);
414 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
415 Invokes.push_back(II);
416 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
417 Unwinds.push_back(UI);
418 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000419 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000420
421 NumInvokes += Invokes.size();
422 NumUnwinds += Unwinds.size();
423
424 // If we don't have any invokes, there's nothing to do.
425 if (Invokes.empty()) return false;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000426
Jim Grosbach0798edd2010-05-27 23:49:24 +0000427 // Find the eh.selector.*, eh.exception and alloca calls.
428 //
429 // Remember any allocas() that aren't in the entry block, as the
430 // jmpbuf saved SP will need to be updated for them.
431 //
432 // We'll use the first eh.selector to determine the right personality
433 // function to use. For SJLJ, we always use the same personality for the
434 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000435 // FIXME: That's a bit ugly. Better way?
436 SmallVector<CallInst*,16> EH_Selectors;
437 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000438 SmallVector<Instruction*,16> JmpbufUpdatePoints;
Bill Wendling8d90b712011-01-07 02:54:45 +0000439
Bill Wendlingcfcccef2011-08-23 22:20:16 +0000440 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
441 // Note: Skip the entry block since there's nothing there that interests
442 // us. eh.selector and eh.exception shouldn't ever be there, and we
443 // want to disregard any allocas that are there.
444 //
445 // FIXME: This is awkward. The new EH scheme won't need to skip the entry
446 // block.
447 if (BB == F.begin()) {
448 if (InvokeInst *II = dyn_cast<InvokeInst>(F.begin()->getTerminator())) {
449 // FIXME: This will be always non-NULL in the new EH.
450 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
451 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
452 }
453
454 continue;
455 }
456
Jim Grosbacha235d132009-08-23 18:13:48 +0000457 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
458 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000459 if (CI->getCalledFunction() == SelectorFn) {
Gabor Greif45c097f2010-06-25 09:36:23 +0000460 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
Jim Grosbacha235d132009-08-23 18:13:48 +0000461 EH_Selectors.push_back(CI);
462 } else if (CI->getCalledFunction() == ExceptionFn) {
463 EH_Exceptions.push_back(CI);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000464 } else if (CI->getCalledFunction() == StackRestoreFn) {
465 JmpbufUpdatePoints.push_back(CI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000466 }
Jim Grosbach0798edd2010-05-27 23:49:24 +0000467 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
468 JmpbufUpdatePoints.push_back(AI);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000469 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
470 // FIXME: This will be always non-NULL in the new EH.
471 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
472 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
Jim Grosbacha235d132009-08-23 18:13:48 +0000473 }
474 }
475 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000476
Jim Grosbacha235d132009-08-23 18:13:48 +0000477 // If we don't have any eh.selector calls, we can't determine the personality
478 // function. Without a personality function, we can't process exceptions.
479 if (!PersonalityFn) return false;
480
Bill Wendling8d90b712011-01-07 02:54:45 +0000481 // We have invokes, so we need to add register/unregister calls to get this
482 // function onto the global unwind stack.
483 //
484 // First thing we need to do is scan the whole function for values that are
485 // live across unwind edges. Each value that is live across an unwind edge we
486 // spill into a stack location, guaranteeing that there is nothing live across
487 // the unwind edge. This process also splits all critical edges coming out of
488 // invoke's.
489 splitLiveRangesAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000490
Bill Wendlingaef508d2011-08-22 23:38:40 +0000491
492 SmallVector<LandingPadInst*, 16> LandingPads;
493 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
494 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
495 // FIXME: This will be always non-NULL in the new EH.
496 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
497 LandingPads.push_back(LPI);
498 }
499
500
Bill Wendling8d90b712011-01-07 02:54:45 +0000501 BasicBlock *EntryBB = F.begin();
502 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
503 // that needs to be restored on all exits from the function. This is an
504 // alloca because the value needs to be added to the global context list.
505 unsigned Align = 4; // FIXME: Should be a TLI check?
506 AllocaInst *FunctionContext =
507 new AllocaInst(FunctionContextTy, 0, Align,
508 "fcn_context", F.begin()->begin());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000509
Bill Wendling8d90b712011-01-07 02:54:45 +0000510 Value *Idxs[2];
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000511 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000512 Value *Zero = ConstantInt::get(Int32Ty, 0);
513 // We need to also keep around a reference to the call_site field
514 Idxs[0] = Zero;
515 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000516 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
Bill Wendling8d90b712011-01-07 02:54:45 +0000517 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000518
Bill Wendling8d90b712011-01-07 02:54:45 +0000519 // The exception selector comes back in context->data[1]
520 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Jay Foada9203102011-07-25 09:48:08 +0000521 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
Bill Wendling8d90b712011-01-07 02:54:45 +0000522 EntryBB->getTerminator());
523 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000524 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000525 "exc_selector_gep",
526 EntryBB->getTerminator());
527 // The exception value comes back in context->data[0]
528 Idxs[1] = Zero;
Jay Foada9203102011-07-25 09:48:08 +0000529 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000530 "exception_gep",
531 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000532
Bill Wendling8d90b712011-01-07 02:54:45 +0000533 // The result of the eh.selector call will be replaced with a a reference to
534 // the selector value returned in the function context. We leave the selector
535 // itself so the EH analysis later can use it.
536 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
537 CallInst *I = EH_Selectors[i];
538 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
539 I->replaceAllUsesWith(SelectorVal);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000540 }
541
Bill Wendling8d90b712011-01-07 02:54:45 +0000542 // eh.exception calls are replaced with references to the proper location in
543 // the context. Unlike eh.selector, the eh.exception calls are removed
544 // entirely.
545 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
546 CallInst *I = EH_Exceptions[i];
547 // Possible for there to be duplicates, so check to make sure the
548 // instruction hasn't already been removed.
549 if (!I->getParent()) continue;
550 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000551 Type *Ty = Type::getInt8PtrTy(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000552 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
553
554 I->replaceAllUsesWith(Val);
555 I->eraseFromParent();
556 }
557
Bill Wendlingaef508d2011-08-22 23:38:40 +0000558 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
559 ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
560
Bill Wendling8d90b712011-01-07 02:54:45 +0000561 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
562 // branch to a dispatch block for non-zero returns. If we return normally,
563 // we're not handling an exception and just register the function context and
564 // continue.
565
566 // Create the dispatch block. The dispatch block is basically a big switch
567 // statement that goes to all of the invoke landing pads.
568 BasicBlock *DispatchBlock =
569 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
570
Bill Wendling8d90b712011-01-07 02:54:45 +0000571 // Insert a load of the callsite in the dispatch block, and a switch on its
Bill Wendlingcc885952011-04-11 21:32:34 +0000572 // value. By default, we issue a trap statement.
573 BasicBlock *TrapBlock =
574 BasicBlock::Create(F.getContext(), "trapbb", &F);
575 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
576 "", TrapBlock);
577 new UnreachableInst(F.getContext(), TrapBlock);
Bill Wendling8d90b712011-01-07 02:54:45 +0000578
579 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
580 DispatchBlock);
581 SwitchInst *DispatchSwitch =
Bill Wendlingcc885952011-04-11 21:32:34 +0000582 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
Bill Wendling8d90b712011-01-07 02:54:45 +0000583 DispatchBlock);
584 // Split the entry block to insert the conditional branch for the setjmp.
585 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
586 "eh.sjlj.setjmp.cont");
587
588 // Populate the Function Context
589 // 1. LSDA address
590 // 2. Personality function address
591 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
592
593 // LSDA address
594 Idxs[0] = Zero;
595 Idxs[1] = ConstantInt::get(Int32Ty, 4);
596 Value *LSDAFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000597 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000598 EntryBB->getTerminator());
599 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
600 EntryBB->getTerminator());
601 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
602
603 Idxs[1] = ConstantInt::get(Int32Ty, 3);
604 Value *PersonalityFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000605 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000606 EntryBB->getTerminator());
607 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
608 EntryBB->getTerminator());
609
610 // Save the frame pointer.
611 Idxs[1] = ConstantInt::get(Int32Ty, 5);
612 Value *JBufPtr
Jay Foada9203102011-07-25 09:48:08 +0000613 = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000614 EntryBB->getTerminator());
615 Idxs[1] = ConstantInt::get(Int32Ty, 0);
616 Value *FramePtr =
Jay Foada9203102011-07-25 09:48:08 +0000617 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000618 EntryBB->getTerminator());
619
620 Value *Val = CallInst::Create(FrameAddrFn,
621 ConstantInt::get(Int32Ty, 0),
622 "fp",
623 EntryBB->getTerminator());
624 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
625
626 // Save the stack pointer.
627 Idxs[1] = ConstantInt::get(Int32Ty, 2);
628 Value *StackPtr =
Jay Foada9203102011-07-25 09:48:08 +0000629 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000630 EntryBB->getTerminator());
631
632 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
633 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
634
635 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
636 Value *SetjmpArg =
637 CastInst::Create(Instruction::BitCast, JBufPtr,
638 Type::getInt8PtrTy(F.getContext()), "",
639 EntryBB->getTerminator());
640 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000641 "",
Bill Wendling8d90b712011-01-07 02:54:45 +0000642 EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000643
644 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
645 // target-specific setup that needs to be done.
Bill Wendling61512ba2011-05-11 01:11:55 +0000646 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000647
Bill Wendling8d90b712011-01-07 02:54:45 +0000648 // check the return value of the setjmp. non-zero goes to dispatcher.
649 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
650 ICmpInst::ICMP_EQ, DispatchVal, Zero,
651 "notunwind");
652 // Nuke the uncond branch.
653 EntryBB->getTerminator()->eraseFromParent();
654
655 // Put in a new condbranch in its place.
656 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
657
658 // Register the function context and make sure it's known to not throw
659 CallInst *Register =
660 CallInst::Create(RegisterFn, FunctionContext, "",
661 ContBlock->getTerminator());
662 Register->setDoesNotThrow();
663
664 // At this point, we are all set up, update the invoke instructions to mark
665 // their call_site values, and fill in the dispatch switch accordingly.
666 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
667 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
668
669 // Mark call instructions that aren't nounwind as no-action (call_site ==
670 // -1). Skip the entry block, as prior to then, no function context has been
671 // created for this function and any unexpected exceptions thrown will go
672 // directly to the caller's context, which is what we want anyway, so no need
673 // to do anything here.
674 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
675 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
676 if (CallInst *CI = dyn_cast<CallInst>(I)) {
677 // Ignore calls to the EH builtins (eh.selector, eh.exception)
678 Constant *Callee = CI->getCalledFunction();
679 if (Callee != SelectorFn && Callee != ExceptionFn
680 && !CI->doesNotThrow())
681 insertCallSiteStore(CI, -1, CallSite);
Bill Wendling3ae96d62011-08-24 00:00:23 +0000682 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
683 insertCallSiteStore(RI, -1, CallSite);
Bill Wendling8d90b712011-01-07 02:54:45 +0000684 }
685 }
686
687 // Replace all unwinds with a branch to the unwind handler.
688 // ??? Should this ever happen with sjlj exceptions?
689 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
Bill Wendlingcc885952011-04-11 21:32:34 +0000690 BranchInst::Create(TrapBlock, Unwinds[i]);
Bill Wendling8d90b712011-01-07 02:54:45 +0000691 Unwinds[i]->eraseFromParent();
692 }
693
694 // Following any allocas not in the entry block, update the saved SP in the
695 // jmpbuf to the new value.
696 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
697 Instruction *AI = JmpbufUpdatePoints[i];
698 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
699 StackAddr->insertAfter(AI);
700 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
701 StoreStackAddr->insertAfter(StackAddr);
702 }
703
704 // Finally, for any returns from this function, if this function contains an
705 // invoke, add a call to unregister the function context.
706 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
707 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
708
Jim Grosbach8b818d72009-08-17 16:41:22 +0000709 return true;
710}
711
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000712/// setupFunctionContext - Allocate the function context on the stack and fill
713/// it with all of the data that we know at this point.
Bill Wendling631d1172011-10-03 21:15:28 +0000714Value *SjLjEHPass::
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000715setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000716 BasicBlock *EntryBB = F.begin();
717
718 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
719 // that needs to be restored on all exits from the function. This is an alloca
720 // because the value needs to be added to the global context list.
721 unsigned Align =
722 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
723 AllocaInst *FuncCtx =
724 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
725
726 // Fill in the function context structure.
727 Value *Idxs[2];
728 Type *Int32Ty = Type::getInt32Ty(F.getContext());
729 Value *Zero = ConstantInt::get(Int32Ty, 0);
730 Value *One = ConstantInt::get(Int32Ty, 1);
731
732 // Keep around a reference to the call_site field.
733 Idxs[0] = Zero;
734 Idxs[1] = One;
735 CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
736 EntryBB->getTerminator());
737
738 // Reference the __data field.
739 Idxs[1] = ConstantInt::get(Int32Ty, 2);
740 Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
741 EntryBB->getTerminator());
742
743 // The exception value comes back in context->__data[0].
744 Idxs[1] = Zero;
745 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
746 "exception_gep",
747 EntryBB->getTerminator());
748
749 // The exception selector comes back in context->__data[1].
750 Idxs[1] = One;
751 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
752 "exn_selector_gep",
753 EntryBB->getTerminator());
754
755 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
756 LandingPadInst *LPI = LPads[I];
757 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
758
759 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
760 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
761 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
762
763 Type *LPadType = LPI->getType();
764 Value *LPadVal = UndefValue::get(LPadType);
765 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
766 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
767
768 LPI->replaceAllUsesWith(LPadVal);
769 }
770
771 // Personality function
772 Idxs[1] = ConstantInt::get(Int32Ty, 3);
773 if (!PersonalityFn)
774 PersonalityFn = LPads[0]->getPersonalityFn();
775 Value *PersonalityFieldPtr =
776 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
777 EntryBB->getTerminator());
778 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
779 EntryBB->getTerminator());
780
781 // LSDA address
782 Idxs[1] = ConstantInt::get(Int32Ty, 4);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000783 Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
784 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000785 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
786 EntryBB->getTerminator());
787 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
788
Bill Wendling631d1172011-10-03 21:15:28 +0000789 return FuncCtx;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000790}
791
792/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
793/// the function context and marking the call sites with the appropriate
794/// values. These values are used by the DWARF EH emitter.
795bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
796 SmallVector<ReturnInst*, 16> Returns;
797 SmallVector<InvokeInst*, 16> Invokes;
798 SmallVector<LandingPadInst*, 16> LPads;
799
800 // Look through the terminators of the basic blocks to find invokes.
801 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
802 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
803 Invokes.push_back(II);
804 LPads.push_back(II->getUnwindDest()->getLandingPadInst());
805 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
806 Returns.push_back(RI);
807 }
808
809 if (Invokes.empty()) return false;
810
Bill Wendling631d1172011-10-03 21:15:28 +0000811 Value *FuncCtx = setupFunctionContext(F, LPads);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000812 BasicBlock *EntryBB = F.begin();
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000813 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling631d1172011-10-03 21:15:28 +0000814
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000815 Value *Idxs[2] = {
Bill Wendling631d1172011-10-03 21:15:28 +0000816 ConstantInt::get(Int32Ty, 0), 0
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000817 };
Bill Wendling631d1172011-10-03 21:15:28 +0000818
819 // Get a reference to the jump buffer.
820 Idxs[1] = ConstantInt::get(Int32Ty, 5);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000821 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
822 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000823
Bill Wendling631d1172011-10-03 21:15:28 +0000824 // Save the frame pointer.
825 Idxs[1] = ConstantInt::get(Int32Ty, 0);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000826 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
827 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000828
829 Value *Val = CallInst::Create(FrameAddrFn,
830 ConstantInt::get(Int32Ty, 0),
831 "fp",
832 EntryBB->getTerminator());
833 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
834
835 // Save the stack pointer.
836 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000837 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
838 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000839
840 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000841 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
842
843 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000844 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
845 Type::getInt8PtrTy(F.getContext()), "",
846 EntryBB->getTerminator());
Bill Wendlingf8520d52011-10-03 22:42:40 +0000847 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000848
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000849 // Store a pointer to the function context so that the back-end will know
850 // where to look for it.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000851 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
852 Type::getInt8PtrTy(F.getContext()), "",
853 EntryBB->getTerminator());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000854 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000855
856 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendling2130ab02011-10-05 22:04:08 +0000857 // their call_site values.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000858 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
859 insertCallSiteStore(Invokes[I], I + 1, CallSite);
860
861 ConstantInt *CallSiteNum =
862 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
863
864 // Record the call site value for the back end so it stays associated with
865 // the invoke.
866 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
867 }
868
869 // Mark call instructions that aren't nounwind as no-action (call_site ==
870 // -1). Skip the entry block, as prior to then, no function context has been
871 // created for this function and any unexpected exceptions thrown will go
872 // directly to the caller's context, which is what we want anyway, so no need
873 // to do anything here.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000874 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000875 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
876 if (CallInst *CI = dyn_cast<CallInst>(I)) {
877 if (!CI->doesNotThrow())
878 insertCallSiteStore(CI, -1, CallSite);
879 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
880 insertCallSiteStore(RI, -1, CallSite);
881 }
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000882
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000883 // Register the function context and make sure it's known to not throw
Bill Wendling631d1172011-10-03 21:15:28 +0000884 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000885 EntryBB->getTerminator());
886 Register->setDoesNotThrow();
887
888 // Finally, for any returns from this function, if this function contains an
889 // invoke, add a call to unregister the function context.
890 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling631d1172011-10-03 21:15:28 +0000891 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000892
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000893 return true;
894}
895
Jim Grosbach8b818d72009-08-17 16:41:22 +0000896bool SjLjEHPass::runOnFunction(Function &F) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000897 bool Res = false;
898 if (!DisableOldSjLjEH)
899 Res = insertSjLjEHSupport(F);
900 else
901 Res = setupEntryBlockAndCallSites(F);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000902 return Res;
903}