1 //===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation is designed for use by code generators which use SjLj
11 // based exception handling.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "sjljehprepare"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetLowering.h"
35 STATISTIC(NumInvokes, "Number of invokes replaced");
36 STATISTIC(NumUnwinds, "Number of unwinds replaced");
37 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
40 class SjLjEHPass : public FunctionPass {
42 const TargetLowering *TLI;
44 const Type *FunctionContextTy;
46 Constant *UnregisterFn;
48 Constant *BuiltinSetjmpFn;
49 Constant *FrameAddrFn;
53 Constant *ExceptionFn;
57 static char ID; // Pass identification, replacement for typeid
58 explicit SjLjEHPass(const TargetLowering *tli = NULL)
59 : FunctionPass(&ID), TLI(tli) { }
60 bool doInitialization(Module &M);
61 bool runOnFunction(Function &F);
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
64 const char *getPassName() const {
65 return "SJLJ Exception Handling preparation";
69 void markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
71 SwitchInst *CatchSwitch);
72 void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
73 bool insertSjLjEHSupport(Function &F);
75 } // end anonymous namespace
77 char SjLjEHPass::ID = 0;
79 // Public Interface To the SjLjEHPass pass.
80 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
81 return new SjLjEHPass(TLI);
83 // doInitialization - Set up decalarations and types needed to process
85 bool SjLjEHPass::doInitialization(Module &M) {
86 // Build the function context structure.
87 // builtin_setjmp uses a five word jbuf
88 const Type *VoidPtrTy =
89 Type::getInt8PtrTy(M.getContext());
90 const Type *Int32Ty = Type::getInt32Ty(M.getContext());
92 StructType::get(M.getContext(),
95 ArrayType::get(Int32Ty, 4), // __data
96 VoidPtrTy, // __personality
98 ArrayType::get(VoidPtrTy, 5), // __jbuf
100 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
101 Type::getVoidTy(M.getContext()),
102 PointerType::getUnqual(FunctionContextTy),
105 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
106 Type::getVoidTy(M.getContext()),
107 PointerType::getUnqual(FunctionContextTy),
110 M.getOrInsertFunction("_Unwind_SjLj_Resume",
111 Type::getVoidTy(M.getContext()),
114 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
115 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
116 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
117 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
118 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
124 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
125 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
127 SwitchInst *CatchSwitch) {
128 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
130 // The runtime comes back to the dispatcher with the call_site - 1 in
131 // the context. Odd, but there it is.
132 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
135 // If the unwind edge has phi nodes, split the edge.
136 if (isa<PHINode>(II->getUnwindDest()->begin())) {
137 SplitCriticalEdge(II, 1, this);
139 // If there are any phi nodes left, they must have a single predecessor.
140 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
141 PN->replaceAllUsesWith(PN->getIncomingValue(0));
142 PN->eraseFromParent();
146 // Insert a store of the invoke num before the invoke and store zero into the
147 // location afterward.
148 new StoreInst(CallSiteNoC, CallSite, true, II); // volatile
150 // Add a switch case to our unwind block.
151 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
152 // We still want this to look like an invoke so we emit the LSDA properly
153 // FIXME: ??? Or will this cause strangeness with mis-matched IDs like
154 // when it was in the front end?
157 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
158 /// we reach blocks we've already seen.
159 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
160 if (!LiveBBs.insert(BB).second) return; // already been here.
162 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
163 MarkBlocksLiveIn(*PI, LiveBBs);
166 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
167 /// we spill into a stack location, guaranteeing that there is nothing live
168 /// across the unwind edge. This process also splits all critical edges
169 /// coming out of invoke's.
171 splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
172 // First step, split all critical edges from invoke instructions.
173 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
174 InvokeInst *II = Invokes[i];
175 SplitCriticalEdge(II, 0, this);
176 SplitCriticalEdge(II, 1, this);
177 assert(!isa<PHINode>(II->getNormalDest()) &&
178 !isa<PHINode>(II->getUnwindDest()) &&
179 "critical edge splitting left single entry phi nodes?");
182 Function *F = Invokes.back()->getParent()->getParent();
184 // To avoid having to handle incoming arguments specially, we lower each arg
185 // to a copy instruction in the entry block. This ensures that the argument
186 // value itself cannot be live across the entry block.
187 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
188 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
189 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
190 ++AfterAllocaInsertPt;
191 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
193 // This is always a no-op cast because we're casting AI to AI->getType() so
194 // src and destination types are identical. BitCast is the only possibility.
195 CastInst *NC = new BitCastInst(
196 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
197 AI->replaceAllUsesWith(NC);
198 // Normally its is forbidden to replace a CastInst's operand because it
199 // could cause the opcode to reflect an illegal conversion. However, we're
200 // replacing it here with the same value it was constructed with to simply
202 NC->setOperand(0, AI);
205 // Finally, scan the code looking for instructions with bad live ranges.
206 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
207 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
208 // Ignore obvious cases we don't have to handle. In particular, most
209 // instructions either have no uses or only have a single use inside the
210 // current block. Ignore them quickly.
211 Instruction *Inst = II;
212 if (Inst->use_empty()) continue;
213 if (Inst->hasOneUse() &&
214 cast<Instruction>(Inst->use_back())->getParent() == BB &&
215 !isa<PHINode>(Inst->use_back())) continue;
217 // If this is an alloca in the entry block, it's not a real register
219 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
220 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
223 // Avoid iterator invalidation by copying users to a temporary vector.
224 SmallVector<Instruction*,16> Users;
225 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
227 Instruction *User = cast<Instruction>(*UI);
228 if (User->getParent() != BB || isa<PHINode>(User))
229 Users.push_back(User);
232 // Find all of the blocks that this value is live in.
233 std::set<BasicBlock*> LiveBBs;
234 LiveBBs.insert(Inst->getParent());
235 while (!Users.empty()) {
236 Instruction *U = Users.back();
239 if (!isa<PHINode>(U)) {
240 MarkBlocksLiveIn(U->getParent(), LiveBBs);
242 // Uses for a PHI node occur in their predecessor block.
243 PHINode *PN = cast<PHINode>(U);
244 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
245 if (PN->getIncomingValue(i) == Inst)
246 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
250 // Now that we know all of the blocks that this thing is live in, see if
251 // it includes any of the unwind locations.
252 bool NeedsSpill = false;
253 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
254 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
255 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
260 // If we decided we need a spill, do it.
263 DemoteRegToStack(*Inst, true);
268 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
269 SmallVector<ReturnInst*,16> Returns;
270 SmallVector<UnwindInst*,16> Unwinds;
271 SmallVector<InvokeInst*,16> Invokes;
273 // Look through the terminators of the basic blocks to find invokes, returns
275 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
276 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
277 // Remember all return instructions in case we insert an invoke into this
279 Returns.push_back(RI);
280 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
281 Invokes.push_back(II);
282 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
283 Unwinds.push_back(UI);
285 // If we don't have any invokes or unwinds, there's nothing to do.
286 if (Unwinds.empty() && Invokes.empty()) return false;
288 // Find the eh.selector.* and eh.exception calls. We'll use the first
289 // eh.selector to determine the right personality function to use. For
290 // SJLJ, we always use the same personality for the whole function,
291 // not on a per-selector basis.
292 // FIXME: That's a bit ugly. Better way?
293 SmallVector<CallInst*,16> EH_Selectors;
294 SmallVector<CallInst*,16> EH_Exceptions;
295 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
296 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
297 if (CallInst *CI = dyn_cast<CallInst>(I)) {
298 if (CI->getCalledFunction() == SelectorFn) {
299 if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
300 EH_Selectors.push_back(CI);
301 } else if (CI->getCalledFunction() == ExceptionFn) {
302 EH_Exceptions.push_back(CI);
307 // If we don't have any eh.selector calls, we can't determine the personality
308 // function. Without a personality function, we can't process exceptions.
309 if (!PersonalityFn) return false;
311 NumInvokes += Invokes.size();
312 NumUnwinds += Unwinds.size();
314 if (!Invokes.empty()) {
315 // We have invokes, so we need to add register/unregister calls to get
316 // this function onto the global unwind stack.
318 // First thing we need to do is scan the whole function for values that are
319 // live across unwind edges. Each value that is live across an unwind edge
320 // we spill into a stack location, guaranteeing that there is nothing live
321 // across the unwind edge. This process also splits all critical edges
322 // coming out of invoke's.
323 splitLiveRangesLiveAcrossInvokes(Invokes);
325 BasicBlock *EntryBB = F.begin();
326 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
327 // that needs to be restored on all exits from the function. This is an
328 // alloca because the value needs to be added to the global context list.
329 unsigned Align = 4; // FIXME: Should be a TLI check?
330 AllocaInst *FunctionContext =
331 new AllocaInst(FunctionContextTy, 0, Align,
332 "fcn_context", F.begin()->begin());
335 const Type *Int32Ty = Type::getInt32Ty(F.getContext());
336 Value *Zero = ConstantInt::get(Int32Ty, 0);
337 // We need to also keep around a reference to the call_site field
339 Idxs[1] = ConstantInt::get(Int32Ty, 1);
340 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
342 EntryBB->getTerminator());
344 // The exception selector comes back in context->data[1]
345 Idxs[1] = ConstantInt::get(Int32Ty, 2);
346 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
348 EntryBB->getTerminator());
349 Idxs[1] = ConstantInt::get(Int32Ty, 1);
350 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
352 EntryBB->getTerminator());
353 // The exception value comes back in context->data[0]
355 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
357 EntryBB->getTerminator());
359 // The result of the eh.selector call will be replaced with a
360 // a reference to the selector value returned in the function
361 // context. We leave the selector itself so the EH analysis later
363 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
364 CallInst *I = EH_Selectors[i];
365 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
366 I->replaceAllUsesWith(SelectorVal);
368 // eh.exception calls are replaced with references to the proper
369 // location in the context. Unlike eh.selector, the eh.exception
370 // calls are removed entirely.
371 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
372 CallInst *I = EH_Exceptions[i];
373 // Possible for there to be duplicates, so check to make sure
374 // the instruction hasn't already been removed.
375 if (!I->getParent()) continue;
376 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
377 const Type *Ty = Type::getInt8PtrTy(F.getContext());
378 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
380 I->replaceAllUsesWith(Val);
381 I->eraseFromParent();
384 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
385 // branch to a dispatch block for non-zero returns. If we return normally,
386 // we're not handling an exception and just register the function context
389 // Create the dispatch block. The dispatch block is basically a big switch
390 // statement that goes to all of the invoke landing pads.
391 BasicBlock *DispatchBlock =
392 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
394 // Insert a load in the Catch block, and a switch on its value. By default,
395 // we go to a block that just does an unwind (which is the correct action
396 // for a standard call).
397 BasicBlock *UnwindBlock =
398 BasicBlock::Create(F.getContext(), "unwindbb", &F);
399 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
401 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
403 SwitchInst *DispatchSwitch =
404 SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
406 // Split the entry block to insert the conditional branch for the setjmp.
407 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
408 "eh.sjlj.setjmp.cont");
410 // Populate the Function Context
412 // 2. Personality function address
413 // 3. jmpbuf (save FP and call eh.sjlj.setjmp)
417 Idxs[1] = ConstantInt::get(Int32Ty, 4);
418 Value *LSDAFieldPtr =
419 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
421 EntryBB->getTerminator());
422 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
423 EntryBB->getTerminator());
424 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
426 Idxs[1] = ConstantInt::get(Int32Ty, 3);
427 Value *PersonalityFieldPtr =
428 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
430 EntryBB->getTerminator());
431 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
432 EntryBB->getTerminator());
434 // Save the frame pointer.
435 Idxs[1] = ConstantInt::get(Int32Ty, 5);
437 = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
439 EntryBB->getTerminator());
440 Idxs[1] = ConstantInt::get(Int32Ty, 0);
442 GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
443 EntryBB->getTerminator());
445 Value *Val = CallInst::Create(FrameAddrFn,
446 ConstantInt::get(Int32Ty, 0),
448 EntryBB->getTerminator());
449 new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
450 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
452 CastInst::Create(Instruction::BitCast, FieldPtr,
453 Type::getInt8PtrTy(F.getContext()), "",
454 EntryBB->getTerminator());
455 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
457 EntryBB->getTerminator());
458 // check the return value of the setjmp. non-zero goes to dispatcher
459 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
460 ICmpInst::ICMP_EQ, DispatchVal, Zero,
462 // Nuke the uncond branch.
463 EntryBB->getTerminator()->eraseFromParent();
465 // Put in a new condbranch in its place.
466 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
468 // Register the function context and make sure it's known to not throw
470 CallInst::Create(RegisterFn, FunctionContext, "",
471 ContBlock->getTerminator());
472 Register->setDoesNotThrow();
474 // At this point, we are all set up, update the invoke instructions
475 // to mark their call_site values, and fill in the dispatch switch
477 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
478 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
480 // The front end has likely added calls to _Unwind_Resume. We need
481 // to find those calls and mark the call_site as -1 immediately prior.
482 // resume is a noreturn function, so any block that has a call to it
483 // should end in an 'unreachable' instruction with the call immediately
484 // prior. That's how we'll search.
485 // ??? There's got to be a better way. this is fugly.
486 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
487 if ((dyn_cast<UnreachableInst>(BB->getTerminator()))) {
488 BasicBlock::iterator I = BB->getTerminator();
489 // Check the previous instruction and see if it's a resume call
490 if (I == BB->begin()) continue;
491 if (CallInst *CI = dyn_cast<CallInst>(--I)) {
492 if (CI->getCalledFunction() == ResumeFn) {
493 Value *NegativeOne = Constant::getAllOnesValue(Int32Ty);
494 new StoreInst(NegativeOne, CallSite, true, I); // volatile
499 // Replace all unwinds with a branch to the unwind handler.
500 // ??? Should this ever happen with sjlj exceptions?
501 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
502 BranchInst::Create(UnwindBlock, Unwinds[i]);
503 Unwinds[i]->eraseFromParent();
506 // Finally, for any returns from this function, if this function contains an
507 // invoke, add a call to unregister the function context.
508 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
509 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
515 bool SjLjEHPass::runOnFunction(Function &F) {
516 bool Res = insertSjLjEHSupport(F);