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/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/IRBuilder.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
39 STATISTIC(NumInvokes, "Number of invokes replaced");
40 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
43 class SjLjEHPass : public FunctionPass {
44 const TargetLowering *TLI;
45 Type *FunctionContextTy;
47 Constant *UnregisterFn;
48 Constant *BuiltinSetjmpFn;
49 Constant *FrameAddrFn;
50 Constant *StackAddrFn;
51 Constant *StackRestoreFn;
58 static char ID; // Pass identification, replacement for typeid
59 explicit SjLjEHPass(const TargetLowering *tli = NULL)
60 : FunctionPass(ID), TLI(tli) { }
61 bool doInitialization(Module &M);
62 bool runOnFunction(Function &F);
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
65 const char *getPassName() const {
66 return "SJLJ Exception Handling preparation";
70 bool setupEntryBlockAndCallSites(Function &F);
71 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
72 void lowerIncomingArguments(Function &F);
73 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
74 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
76 } // end anonymous namespace
78 char SjLjEHPass::ID = 0;
80 // Public Interface To the SjLjEHPass pass.
81 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
82 return new SjLjEHPass(TLI);
84 // doInitialization - Set up decalarations and types needed to process
86 bool SjLjEHPass::doInitialization(Module &M) {
87 // Build the function context structure.
88 // builtin_setjmp uses a five word jbuf
89 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
90 Type *Int32Ty = Type::getInt32Ty(M.getContext());
92 StructType::get(VoidPtrTy, // __prev
94 ArrayType::get(Int32Ty, 4), // __data
95 VoidPtrTy, // __personality
97 ArrayType::get(VoidPtrTy, 5), // __jbuf
99 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
100 Type::getVoidTy(M.getContext()),
101 PointerType::getUnqual(FunctionContextTy),
104 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
105 Type::getVoidTy(M.getContext()),
106 PointerType::getUnqual(FunctionContextTy),
108 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
109 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
110 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
111 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
112 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
113 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
114 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
120 /// insertCallSiteStore - Insert a store of the call-site value to the
122 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
124 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
126 // Insert a store of the call-site number
127 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
130 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
131 /// we reach blocks we've already seen.
132 static void MarkBlocksLiveIn(BasicBlock *BB,
133 SmallPtrSet<BasicBlock*, 64> &LiveBBs) {
134 if (!LiveBBs.insert(BB)) return; // already been here.
136 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
137 MarkBlocksLiveIn(*PI, LiveBBs);
140 /// setupFunctionContext - Allocate the function context on the stack and fill
141 /// it with all of the data that we know at this point.
143 setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
144 BasicBlock *EntryBB = F.begin();
146 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
147 // that needs to be restored on all exits from the function. This is an alloca
148 // because the value needs to be added to the global context list.
150 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
151 AllocaInst *FuncCtx =
152 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
154 // Fill in the function context structure.
156 Type *Int32Ty = Type::getInt32Ty(F.getContext());
157 Value *Zero = ConstantInt::get(Int32Ty, 0);
158 Value *One = ConstantInt::get(Int32Ty, 1);
160 // Keep around a reference to the call_site field.
163 CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
164 EntryBB->getTerminator());
166 // Reference the __data field.
167 Idxs[1] = ConstantInt::get(Int32Ty, 2);
168 Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
169 EntryBB->getTerminator());
171 // The exception value comes back in context->__data[0].
173 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
175 EntryBB->getTerminator());
177 // The exception selector comes back in context->__data[1].
179 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
181 EntryBB->getTerminator());
183 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
184 LandingPadInst *LPI = LPads[I];
185 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
187 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
188 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
189 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
191 Type *LPadType = LPI->getType();
192 Value *LPadVal = UndefValue::get(LPadType);
193 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
194 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
196 LPI->replaceAllUsesWith(LPadVal);
199 // Personality function
200 Idxs[1] = ConstantInt::get(Int32Ty, 3);
202 PersonalityFn = LPads[0]->getPersonalityFn();
203 Value *PersonalityFieldPtr =
204 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
205 EntryBB->getTerminator());
206 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
207 EntryBB->getTerminator());
210 Idxs[1] = ConstantInt::get(Int32Ty, 4);
211 Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
212 EntryBB->getTerminator());
213 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
214 EntryBB->getTerminator());
215 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
220 /// lowerIncomingArguments - To avoid having to handle incoming arguments
221 /// specially, we lower each arg to a copy instruction in the entry block. This
222 /// ensures that the argument value itself cannot be live out of the entry
224 void SjLjEHPass::lowerIncomingArguments(Function &F) {
225 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
226 while (isa<AllocaInst>(AfterAllocaInsPt) &&
227 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
230 for (Function::arg_iterator
231 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
232 Type *Ty = AI->getType();
234 // Aggregate types can't be cast, but are legal argument types, so we have
235 // to handle them differently. We use an extract/insert pair as a
236 // lightweight method to achieve the same goal.
237 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
238 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
239 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
241 AI->replaceAllUsesWith(NI);
243 // Set the operand of the instructions back to the AllocaInst.
244 EI->setOperand(0, AI);
245 NI->setOperand(0, AI);
247 // This is always a no-op cast because we're casting AI to AI->getType()
248 // so src and destination types are identical. BitCast is the only
251 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
253 AI->replaceAllUsesWith(NC);
255 // Set the operand of the cast instruction back to the AllocaInst.
256 // Normally it's forbidden to replace a CastInst's operand because it
257 // could cause the opcode to reflect an illegal conversion. However, we're
258 // replacing it here with the same value it was constructed with. We do
259 // this because the above replaceAllUsesWith() clobbered the operand, but
260 // we want this one to remain.
261 NC->setOperand(0, AI);
266 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
267 /// edge and spill them.
268 void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
269 ArrayRef<InvokeInst*> Invokes) {
270 // Finally, scan the code looking for instructions with bad live ranges.
271 for (Function::iterator
272 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
273 for (BasicBlock::iterator
274 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
275 // Ignore obvious cases we don't have to handle. In particular, most
276 // instructions either have no uses or only have a single use inside the
277 // current block. Ignore them quickly.
278 Instruction *Inst = II;
279 if (Inst->use_empty()) continue;
280 if (Inst->hasOneUse() &&
281 cast<Instruction>(Inst->use_back())->getParent() == BB &&
282 !isa<PHINode>(Inst->use_back())) continue;
284 // If this is an alloca in the entry block, it's not a real register
286 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
287 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
290 // Avoid iterator invalidation by copying users to a temporary vector.
291 SmallVector<Instruction*, 16> Users;
292 for (Value::use_iterator
293 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
294 Instruction *User = cast<Instruction>(*UI);
295 if (User->getParent() != BB || isa<PHINode>(User))
296 Users.push_back(User);
299 // Find all of the blocks that this value is live in.
300 SmallPtrSet<BasicBlock*, 64> LiveBBs;
301 LiveBBs.insert(Inst->getParent());
302 while (!Users.empty()) {
303 Instruction *U = Users.back();
306 if (!isa<PHINode>(U)) {
307 MarkBlocksLiveIn(U->getParent(), LiveBBs);
309 // Uses for a PHI node occur in their predecessor block.
310 PHINode *PN = cast<PHINode>(U);
311 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
312 if (PN->getIncomingValue(i) == Inst)
313 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
317 // Now that we know all of the blocks that this thing is live in, see if
318 // it includes any of the unwind locations.
319 bool NeedsSpill = false;
320 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
321 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
322 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
328 // If we decided we need a spill, do it.
329 // FIXME: Spilling this way is overkill, as it forces all uses of
330 // the value to be reloaded from the stack slot, even those that aren't
331 // in the unwind blocks. We should be more selective.
333 DemoteRegToStack(*Inst, true);
339 // Go through the landing pads and remove any PHIs there.
340 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
341 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
342 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
344 // Place PHIs into a set to avoid invalidating the iterator.
345 SmallPtrSet<PHINode*, 8> PHIsToDemote;
346 for (BasicBlock::iterator
347 PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
348 PHIsToDemote.insert(cast<PHINode>(PN));
349 if (PHIsToDemote.empty()) continue;
351 // Demote the PHIs to the stack.
352 for (SmallPtrSet<PHINode*, 8>::iterator
353 I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
354 DemotePHIToStack(*I);
356 // Move the landingpad instruction back to the top of the landing pad block.
357 LPI->moveBefore(UnwindBlock->begin());
361 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
362 /// the function context and marking the call sites with the appropriate
363 /// values. These values are used by the DWARF EH emitter.
364 bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
365 SmallVector<ReturnInst*, 16> Returns;
366 SmallVector<InvokeInst*, 16> Invokes;
367 SmallVector<LandingPadInst*, 16> LPads;
369 // Look through the terminators of the basic blocks to find invokes.
370 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
371 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
372 Invokes.push_back(II);
373 LPads.push_back(II->getUnwindDest()->getLandingPadInst());
374 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
375 Returns.push_back(RI);
378 if (Invokes.empty()) return false;
380 NumInvokes += Invokes.size();
382 lowerIncomingArguments(F);
383 lowerAcrossUnwindEdges(F, Invokes);
385 Value *FuncCtx = setupFunctionContext(F, LPads);
386 BasicBlock *EntryBB = F.begin();
387 Type *Int32Ty = Type::getInt32Ty(F.getContext());
390 ConstantInt::get(Int32Ty, 0), 0
393 // Get a reference to the jump buffer.
394 Idxs[1] = ConstantInt::get(Int32Ty, 5);
395 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
396 EntryBB->getTerminator());
398 // Save the frame pointer.
399 Idxs[1] = ConstantInt::get(Int32Ty, 0);
400 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
401 EntryBB->getTerminator());
403 Value *Val = CallInst::Create(FrameAddrFn,
404 ConstantInt::get(Int32Ty, 0),
406 EntryBB->getTerminator());
407 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
409 // Save the stack pointer.
410 Idxs[1] = ConstantInt::get(Int32Ty, 2);
411 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
412 EntryBB->getTerminator());
414 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
415 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
417 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
418 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
419 Type::getInt8PtrTy(F.getContext()), "",
420 EntryBB->getTerminator());
421 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
423 // Store a pointer to the function context so that the back-end will know
424 // where to look for it.
425 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
426 Type::getInt8PtrTy(F.getContext()), "",
427 EntryBB->getTerminator());
428 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
430 // At this point, we are all set up, update the invoke instructions to mark
431 // their call_site values.
432 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
433 insertCallSiteStore(Invokes[I], I + 1, CallSite);
435 ConstantInt *CallSiteNum =
436 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
438 // Record the call site value for the back end so it stays associated with
440 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
443 // Mark call instructions that aren't nounwind as no-action (call_site ==
444 // -1). Skip the entry block, as prior to then, no function context has been
445 // created for this function and any unexpected exceptions thrown will go
446 // directly to the caller's context, which is what we want anyway, so no need
447 // to do anything here.
448 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
449 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
450 if (CallInst *CI = dyn_cast<CallInst>(I)) {
451 if (!CI->doesNotThrow())
452 insertCallSiteStore(CI, -1, CallSite);
453 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
454 insertCallSiteStore(RI, -1, CallSite);
457 // Register the function context and make sure it's known to not throw
458 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
459 EntryBB->getTerminator());
460 Register->setDoesNotThrow();
462 // Following any allocas not in the entry block, update the saved SP in the
463 // jmpbuf to the new value.
464 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
467 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
468 if (CallInst *CI = dyn_cast<CallInst>(I)) {
469 if (CI->getCalledFunction() != StackRestoreFn)
471 } else if (!isa<AllocaInst>(I)) {
474 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
475 StackAddr->insertAfter(I);
476 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
477 StoreStackAddr->insertAfter(StackAddr);
481 // Finally, for any returns from this function, if this function contains an
482 // invoke, add a call to unregister the function context.
483 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
484 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
489 bool SjLjEHPass::runOnFunction(Function &F) {
490 bool Res = setupEntryBlockAndCallSites(F);