blob: ed0202551274d5dad7a35deb9f5ada4ce6332142 [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"
Benjamin Kramerf7888542010-11-06 11:45:59 +000025#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
27#include "llvm/Transforms/Utils/Local.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000028#include "llvm/Support/Debug.h"
Bill Wendlingaef508d2011-08-22 23:38:40 +000029#include "llvm/ADT/DenseMap.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000030#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000032#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000033using namespace llvm;
34
35STATISTIC(NumInvokes, "Number of invokes replaced");
36STATISTIC(NumUnwinds, "Number of unwinds replaced");
37STATISTIC(NumSpilled, "Number of registers live across unwind edges");
38
39namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000040 class SjLjEHPass : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000041 const TargetLowering *TLI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000042 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000043 Constant *RegisterFn;
44 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000045 Constant *BuiltinSetjmpFn;
46 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000047 Constant *StackAddrFn;
48 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000049 Constant *LSDAAddrFn;
50 Value *PersonalityFn;
Duncan Sandsb01bbdc2009-10-14 16:11:37 +000051 Constant *SelectorFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000052 Constant *ExceptionFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000053 Constant *CallSiteFn;
Jim Grosbache4ad3872010-10-19 23:27:08 +000054 Constant *DispatchSetupFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000055 Value *CallSite;
Bill Wendlingaef508d2011-08-22 23:38:40 +000056 DenseMap<InvokeInst*, BasicBlock*> LPadSuccMap;
Jim Grosbach8b818d72009-08-17 16:41:22 +000057 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:
Jim Grosbachb58a59b2010-03-04 22:07:46 +000070 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
71 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
Jim Grosbach0bb61c52009-08-31 01:35:03 +000072 SwitchInst *CatchSwitch);
Jim Grosbach288694f2010-06-15 18:53:34 +000073 void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +000074 bool insertSjLjEHSupport(Function &F);
75 };
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);
110 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000111 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
112 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000113 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000114 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000115 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000116 DispatchSetupFn
117 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Jim Grosbacha235d132009-08-23 18:13:48 +0000118 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000119
120 return true;
121}
122
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000123/// insertCallSiteStore - Insert a store of the call-site value to the
124/// function context
125void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
126 Value *CallSite) {
127 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
128 Number);
129 // Insert a store of the call-site number
130 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
131}
132
Jim Grosbach8b818d72009-08-17 16:41:22 +0000133/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000134void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000135 Value *CallSite,
136 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000137 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000138 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000139 // The runtime comes back to the dispatcher with the call_site - 1 in
140 // the context. Odd, but there it is.
141 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
142 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000143
144 // If the unwind edge has phi nodes, split the edge.
145 if (isa<PHINode>(II->getUnwindDest()->begin())) {
Bill Wendling51fb91c2011-08-26 21:18:55 +0000146 // FIXME: New EH - This if-condition will be always true in the new scheme.
147 if (II->getUnwindDest()->isLandingPad()) {
Bill Wendling8557e6c2011-08-27 04:40:37 +0000148 SmallVector<BasicBlock*, 2> NewBBs;
149 SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
150 ".1", ".2", this, NewBBs);
151 LPadSuccMap[II] = *succ_begin(NewBBs[0]);
Bill Wendling51fb91c2011-08-26 21:18:55 +0000152 } else {
153 SplitCriticalEdge(II, 1, this);
154 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000155
156 // If there are any phi nodes left, they must have a single predecessor.
157 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
158 PN->replaceAllUsesWith(PN->getIncomingValue(0));
159 PN->eraseFromParent();
160 }
161 }
162
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000163 // Insert the store of the call site value
164 insertCallSiteStore(II, InvokeNo, CallSite);
165
166 // Record the call site value for the back end so it stays associated with
167 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000168 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000169
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000170 // Add a switch case to our unwind block.
Bill Wendlingaef508d2011-08-22 23:38:40 +0000171 if (BasicBlock *SuccBB = LPadSuccMap[II]) {
172 CatchSwitch->addCase(SwitchValC, SuccBB);
173 } else {
174 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
175 }
176
Jim Grosbachca752c92010-01-28 01:45:32 +0000177 // We still want this to look like an invoke so we emit the LSDA properly,
178 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000179}
180
181/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
182/// we reach blocks we've already seen.
183static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
184 if (!LiveBBs.insert(BB).second) return; // already been here.
185
186 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
187 MarkBlocksLiveIn(*PI, LiveBBs);
188}
189
Jim Grosbach606f3d62009-08-17 21:40:03 +0000190/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
191/// we spill into a stack location, guaranteeing that there is nothing live
192/// across the unwind edge. This process also splits all critical edges
193/// coming out of invoke's.
Jim Grosbach2f3257e2010-06-01 18:06:35 +0000194/// FIXME: Move this function to a common utility file (Local.cpp?) so
195/// both SjLj and LowerInvoke can use it.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000196void SjLjEHPass::
Jim Grosbach288694f2010-06-15 18:53:34 +0000197splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000198 // First step, split all critical edges from invoke instructions.
199 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
200 InvokeInst *II = Invokes[i];
201 SplitCriticalEdge(II, 0, this);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000202
203 // FIXME: New EH - This if-condition will be always true in the new scheme.
204 if (II->getUnwindDest()->isLandingPad()) {
Bill Wendling8557e6c2011-08-27 04:40:37 +0000205 SmallVector<BasicBlock*, 2> NewBBs;
206 SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
207 ".1", ".2", this, NewBBs);
208 LPadSuccMap[II] = *succ_begin(NewBBs[0]);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000209 } else {
210 SplitCriticalEdge(II, 1, this);
211 }
212
Jim Grosbach8b818d72009-08-17 16:41:22 +0000213 assert(!isa<PHINode>(II->getNormalDest()) &&
214 !isa<PHINode>(II->getUnwindDest()) &&
Bill Wendlingd36b3e32011-08-22 18:44:49 +0000215 "Critical edge splitting left single entry phi nodes?");
Jim Grosbach8b818d72009-08-17 16:41:22 +0000216 }
217
218 Function *F = Invokes.back()->getParent()->getParent();
219
220 // To avoid having to handle incoming arguments specially, we lower each arg
221 // to a copy instruction in the entry block. This ensures that the argument
222 // value itself cannot be live across the entry block.
223 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
224 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
225 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
226 ++AfterAllocaInsertPt;
227 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
228 AI != E; ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000229 Type *Ty = AI->getType();
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000230 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbachdc58b252010-06-01 18:04:09 +0000231 // to handle them differently. We use an extract/insert pair as a
232 // lightweight method to achieve the same goal.
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000233 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
234 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbachdc58b252010-06-01 18:04:09 +0000235 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
236 NI->insertAfter(EI);
237 AI->replaceAllUsesWith(NI);
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000238 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbachdc58b252010-06-01 18:04:09 +0000239 EI->setOperand(0, AI);
240 NI->setOperand(0, AI);
241 } else {
242 // This is always a no-op cast because we're casting AI to AI->getType()
243 // so src and destination types are identical. BitCast is the only
244 // possibility.
245 CastInst *NC = new BitCastInst(
246 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
247 AI->replaceAllUsesWith(NC);
248 // Set the operand of the cast instruction back to the AllocaInst.
249 // Normally it's forbidden to replace a CastInst's operand because it
250 // could cause the opcode to reflect an illegal conversion. However,
251 // we're replacing it here with the same value it was constructed with.
252 // We do this because the above replaceAllUsesWith() clobbered the
253 // operand, but we want this one to remain.
254 NC->setOperand(0, AI);
255 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000256 }
257
258 // Finally, scan the code looking for instructions with bad live ranges.
259 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
260 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
261 // Ignore obvious cases we don't have to handle. In particular, most
262 // instructions either have no uses or only have a single use inside the
263 // current block. Ignore them quickly.
264 Instruction *Inst = II;
265 if (Inst->use_empty()) continue;
266 if (Inst->hasOneUse() &&
267 cast<Instruction>(Inst->use_back())->getParent() == BB &&
268 !isa<PHINode>(Inst->use_back())) continue;
269
270 // If this is an alloca in the entry block, it's not a real register
271 // value.
272 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
273 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
274 continue;
275
276 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000277 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000278 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
279 UI != E; ++UI) {
280 Instruction *User = cast<Instruction>(*UI);
281 if (User->getParent() != BB || isa<PHINode>(User))
282 Users.push_back(User);
283 }
284
Jim Grosbach8b818d72009-08-17 16:41:22 +0000285 // Find all of the blocks that this value is live in.
286 std::set<BasicBlock*> LiveBBs;
287 LiveBBs.insert(Inst->getParent());
288 while (!Users.empty()) {
289 Instruction *U = Users.back();
290 Users.pop_back();
291
292 if (!isa<PHINode>(U)) {
293 MarkBlocksLiveIn(U->getParent(), LiveBBs);
294 } else {
295 // Uses for a PHI node occur in their predecessor block.
296 PHINode *PN = cast<PHINode>(U);
297 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
298 if (PN->getIncomingValue(i) == Inst)
299 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
300 }
301 }
302
303 // Now that we know all of the blocks that this thing is live in, see if
304 // it includes any of the unwind locations.
305 bool NeedsSpill = false;
306 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
307 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
308 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
309 NeedsSpill = true;
310 }
311 }
312
313 // If we decided we need a spill, do it.
Jim Grosbach956352e2010-06-16 18:45:08 +0000314 // FIXME: Spilling this way is overkill, as it forces all uses of
315 // the value to be reloaded from the stack slot, even those that aren't
316 // in the unwind blocks. We should be more selective.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000317 if (NeedsSpill) {
318 ++NumSpilled;
319 DemoteRegToStack(*Inst, true);
320 }
321 }
322}
323
Bill Wendlingaef508d2011-08-22 23:38:40 +0000324/// CreateLandingPadLoad - Load the exception handling values and insert them
325/// into a structure.
326static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
327 Value *SelAddr,
328 BasicBlock::iterator InsertPt) {
329 Value *Exn = new LoadInst(ExnAddr, "exn", false,
330 InsertPt);
331 Type *Ty = Type::getInt8PtrTy(F.getContext());
332 Exn = CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
333 Value *Sel = new LoadInst(SelAddr, "sel", false, InsertPt);
334
335 Ty = StructType::get(Exn->getType(), Sel->getType(), NULL);
336 InsertValueInst *LPadVal = InsertValueInst::Create(llvm::UndefValue::get(Ty),
337 Exn, 0,
338 "lpad.val", InsertPt);
339 return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
340}
341
342/// ReplaceLandingPadVal - Replace the landingpad instruction's value with a
343/// load from the stored values (via CreateLandingPadLoad). This looks through
344/// PHI nodes, and removes them if they are dead.
345static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *ExnAddr,
346 Value *SelAddr) {
347 if (Inst->use_empty()) return;
348
349 while (!Inst->use_empty()) {
350 Instruction *I = cast<Instruction>(Inst->use_back());
351
352 if (PHINode *PN = dyn_cast<PHINode>(I)) {
353 ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
354 if (PN->use_empty()) PN->eraseFromParent();
355 continue;
356 }
357
Bill Wendlingfc8713f2011-08-23 22:55:03 +0000358 I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I));
Bill Wendlingaef508d2011-08-22 23:38:40 +0000359 }
360}
361
Jim Grosbach8b818d72009-08-17 16:41:22 +0000362bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000363 SmallVector<ReturnInst*,16> Returns;
364 SmallVector<UnwindInst*,16> Unwinds;
365 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000366
367 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000368 // and unwinds.
369 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000370 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
371 // Remember all return instructions in case we insert an invoke into this
372 // function.
373 Returns.push_back(RI);
374 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
375 Invokes.push_back(II);
376 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
377 Unwinds.push_back(UI);
378 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000379 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000380
381 NumInvokes += Invokes.size();
382 NumUnwinds += Unwinds.size();
383
384 // If we don't have any invokes, there's nothing to do.
385 if (Invokes.empty()) return false;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000386
Jim Grosbach0798edd2010-05-27 23:49:24 +0000387 // Find the eh.selector.*, eh.exception and alloca calls.
388 //
389 // Remember any allocas() that aren't in the entry block, as the
390 // jmpbuf saved SP will need to be updated for them.
391 //
392 // We'll use the first eh.selector to determine the right personality
393 // function to use. For SJLJ, we always use the same personality for the
394 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000395 // FIXME: That's a bit ugly. Better way?
396 SmallVector<CallInst*,16> EH_Selectors;
397 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000398 SmallVector<Instruction*,16> JmpbufUpdatePoints;
Bill Wendling8d90b712011-01-07 02:54:45 +0000399
Bill Wendlingcfcccef2011-08-23 22:20:16 +0000400 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
401 // Note: Skip the entry block since there's nothing there that interests
402 // us. eh.selector and eh.exception shouldn't ever be there, and we
403 // want to disregard any allocas that are there.
404 //
405 // FIXME: This is awkward. The new EH scheme won't need to skip the entry
406 // block.
407 if (BB == F.begin()) {
408 if (InvokeInst *II = dyn_cast<InvokeInst>(F.begin()->getTerminator())) {
409 // FIXME: This will be always non-NULL in the new EH.
410 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
411 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
412 }
413
414 continue;
415 }
416
Jim Grosbacha235d132009-08-23 18:13:48 +0000417 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
418 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000419 if (CI->getCalledFunction() == SelectorFn) {
Gabor Greif45c097f2010-06-25 09:36:23 +0000420 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
Jim Grosbacha235d132009-08-23 18:13:48 +0000421 EH_Selectors.push_back(CI);
422 } else if (CI->getCalledFunction() == ExceptionFn) {
423 EH_Exceptions.push_back(CI);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000424 } else if (CI->getCalledFunction() == StackRestoreFn) {
425 JmpbufUpdatePoints.push_back(CI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000426 }
Jim Grosbach0798edd2010-05-27 23:49:24 +0000427 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
428 JmpbufUpdatePoints.push_back(AI);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000429 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
430 // FIXME: This will be always non-NULL in the new EH.
431 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
432 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
Jim Grosbacha235d132009-08-23 18:13:48 +0000433 }
434 }
435 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000436
Jim Grosbacha235d132009-08-23 18:13:48 +0000437 // If we don't have any eh.selector calls, we can't determine the personality
438 // function. Without a personality function, we can't process exceptions.
439 if (!PersonalityFn) return false;
440
Bill Wendling8d90b712011-01-07 02:54:45 +0000441 // We have invokes, so we need to add register/unregister calls to get this
442 // function onto the global unwind stack.
443 //
444 // First thing we need to do is scan the whole function for values that are
445 // live across unwind edges. Each value that is live across an unwind edge we
446 // spill into a stack location, guaranteeing that there is nothing live across
447 // the unwind edge. This process also splits all critical edges coming out of
448 // invoke's.
449 splitLiveRangesAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000450
Bill Wendlingaef508d2011-08-22 23:38:40 +0000451
452 SmallVector<LandingPadInst*, 16> LandingPads;
453 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
454 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
455 // FIXME: This will be always non-NULL in the new EH.
456 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
457 LandingPads.push_back(LPI);
458 }
459
460
Bill Wendling8d90b712011-01-07 02:54:45 +0000461 BasicBlock *EntryBB = F.begin();
462 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
463 // that needs to be restored on all exits from the function. This is an
464 // alloca because the value needs to be added to the global context list.
465 unsigned Align = 4; // FIXME: Should be a TLI check?
466 AllocaInst *FunctionContext =
467 new AllocaInst(FunctionContextTy, 0, Align,
468 "fcn_context", F.begin()->begin());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000469
Bill Wendling8d90b712011-01-07 02:54:45 +0000470 Value *Idxs[2];
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000471 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000472 Value *Zero = ConstantInt::get(Int32Ty, 0);
473 // We need to also keep around a reference to the call_site field
474 Idxs[0] = Zero;
475 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000476 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
Bill Wendling8d90b712011-01-07 02:54:45 +0000477 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000478
Bill Wendling8d90b712011-01-07 02:54:45 +0000479 // The exception selector comes back in context->data[1]
480 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Jay Foada9203102011-07-25 09:48:08 +0000481 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
Bill Wendling8d90b712011-01-07 02:54:45 +0000482 EntryBB->getTerminator());
483 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000484 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000485 "exc_selector_gep",
486 EntryBB->getTerminator());
487 // The exception value comes back in context->data[0]
488 Idxs[1] = Zero;
Jay Foada9203102011-07-25 09:48:08 +0000489 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000490 "exception_gep",
491 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000492
Bill Wendling8d90b712011-01-07 02:54:45 +0000493 // The result of the eh.selector call will be replaced with a a reference to
494 // the selector value returned in the function context. We leave the selector
495 // itself so the EH analysis later can use it.
496 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
497 CallInst *I = EH_Selectors[i];
498 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
499 I->replaceAllUsesWith(SelectorVal);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000500 }
501
Bill Wendling8d90b712011-01-07 02:54:45 +0000502 // eh.exception calls are replaced with references to the proper location in
503 // the context. Unlike eh.selector, the eh.exception calls are removed
504 // entirely.
505 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
506 CallInst *I = EH_Exceptions[i];
507 // Possible for there to be duplicates, so check to make sure the
508 // instruction hasn't already been removed.
509 if (!I->getParent()) continue;
510 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000511 Type *Ty = Type::getInt8PtrTy(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000512 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
513
514 I->replaceAllUsesWith(Val);
515 I->eraseFromParent();
516 }
517
Bill Wendlingaef508d2011-08-22 23:38:40 +0000518 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
519 ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
520
Bill Wendling8d90b712011-01-07 02:54:45 +0000521 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
522 // branch to a dispatch block for non-zero returns. If we return normally,
523 // we're not handling an exception and just register the function context and
524 // continue.
525
526 // Create the dispatch block. The dispatch block is basically a big switch
527 // statement that goes to all of the invoke landing pads.
528 BasicBlock *DispatchBlock =
529 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
530
Bill Wendling8d90b712011-01-07 02:54:45 +0000531 // Insert a load of the callsite in the dispatch block, and a switch on its
Bill Wendlingcc885952011-04-11 21:32:34 +0000532 // value. By default, we issue a trap statement.
533 BasicBlock *TrapBlock =
534 BasicBlock::Create(F.getContext(), "trapbb", &F);
535 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
536 "", TrapBlock);
537 new UnreachableInst(F.getContext(), TrapBlock);
Bill Wendling8d90b712011-01-07 02:54:45 +0000538
539 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
540 DispatchBlock);
541 SwitchInst *DispatchSwitch =
Bill Wendlingcc885952011-04-11 21:32:34 +0000542 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
Bill Wendling8d90b712011-01-07 02:54:45 +0000543 DispatchBlock);
544 // Split the entry block to insert the conditional branch for the setjmp.
545 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
546 "eh.sjlj.setjmp.cont");
547
548 // Populate the Function Context
549 // 1. LSDA address
550 // 2. Personality function address
551 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
552
553 // LSDA address
554 Idxs[0] = Zero;
555 Idxs[1] = ConstantInt::get(Int32Ty, 4);
556 Value *LSDAFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000557 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000558 EntryBB->getTerminator());
559 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
560 EntryBB->getTerminator());
561 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
562
563 Idxs[1] = ConstantInt::get(Int32Ty, 3);
564 Value *PersonalityFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000565 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000566 EntryBB->getTerminator());
567 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
568 EntryBB->getTerminator());
569
570 // Save the frame pointer.
571 Idxs[1] = ConstantInt::get(Int32Ty, 5);
572 Value *JBufPtr
Jay Foada9203102011-07-25 09:48:08 +0000573 = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000574 EntryBB->getTerminator());
575 Idxs[1] = ConstantInt::get(Int32Ty, 0);
576 Value *FramePtr =
Jay Foada9203102011-07-25 09:48:08 +0000577 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000578 EntryBB->getTerminator());
579
580 Value *Val = CallInst::Create(FrameAddrFn,
581 ConstantInt::get(Int32Ty, 0),
582 "fp",
583 EntryBB->getTerminator());
584 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
585
586 // Save the stack pointer.
587 Idxs[1] = ConstantInt::get(Int32Ty, 2);
588 Value *StackPtr =
Jay Foada9203102011-07-25 09:48:08 +0000589 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000590 EntryBB->getTerminator());
591
592 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
593 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
594
595 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
596 Value *SetjmpArg =
597 CastInst::Create(Instruction::BitCast, JBufPtr,
598 Type::getInt8PtrTy(F.getContext()), "",
599 EntryBB->getTerminator());
600 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
601 "dispatch",
602 EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000603
604 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
605 // target-specific setup that needs to be done.
Bill Wendling61512ba2011-05-11 01:11:55 +0000606 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000607
Bill Wendling8d90b712011-01-07 02:54:45 +0000608 // check the return value of the setjmp. non-zero goes to dispatcher.
609 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
610 ICmpInst::ICMP_EQ, DispatchVal, Zero,
611 "notunwind");
612 // Nuke the uncond branch.
613 EntryBB->getTerminator()->eraseFromParent();
614
615 // Put in a new condbranch in its place.
616 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
617
618 // Register the function context and make sure it's known to not throw
619 CallInst *Register =
620 CallInst::Create(RegisterFn, FunctionContext, "",
621 ContBlock->getTerminator());
622 Register->setDoesNotThrow();
623
624 // At this point, we are all set up, update the invoke instructions to mark
625 // their call_site values, and fill in the dispatch switch accordingly.
626 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
627 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
628
629 // Mark call instructions that aren't nounwind as no-action (call_site ==
630 // -1). Skip the entry block, as prior to then, no function context has been
631 // created for this function and any unexpected exceptions thrown will go
632 // directly to the caller's context, which is what we want anyway, so no need
633 // to do anything here.
634 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
635 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
636 if (CallInst *CI = dyn_cast<CallInst>(I)) {
637 // Ignore calls to the EH builtins (eh.selector, eh.exception)
638 Constant *Callee = CI->getCalledFunction();
639 if (Callee != SelectorFn && Callee != ExceptionFn
640 && !CI->doesNotThrow())
641 insertCallSiteStore(CI, -1, CallSite);
Bill Wendling3ae96d62011-08-24 00:00:23 +0000642 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
643 insertCallSiteStore(RI, -1, CallSite);
Bill Wendling8d90b712011-01-07 02:54:45 +0000644 }
645 }
646
647 // Replace all unwinds with a branch to the unwind handler.
648 // ??? Should this ever happen with sjlj exceptions?
649 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
Bill Wendlingcc885952011-04-11 21:32:34 +0000650 BranchInst::Create(TrapBlock, Unwinds[i]);
Bill Wendling8d90b712011-01-07 02:54:45 +0000651 Unwinds[i]->eraseFromParent();
652 }
653
654 // Following any allocas not in the entry block, update the saved SP in the
655 // jmpbuf to the new value.
656 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
657 Instruction *AI = JmpbufUpdatePoints[i];
658 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
659 StackAddr->insertAfter(AI);
660 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
661 StoreStackAddr->insertAfter(StackAddr);
662 }
663
664 // Finally, for any returns from this function, if this function contains an
665 // invoke, add a call to unregister the function context.
666 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
667 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
668
Jim Grosbach8b818d72009-08-17 16:41:22 +0000669 return true;
670}
671
672bool SjLjEHPass::runOnFunction(Function &F) {
673 bool Res = insertSjLjEHSupport(F);
674 return Res;
675}