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/Support/raw_ostream.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
41 STATISTIC(NumInvokes, "Number of invokes replaced");
42 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
45 class SjLjEHPass : public FunctionPass {
46 const TargetLowering *TLI;
47 Type *FunctionContextTy;
49 Constant *UnregisterFn;
50 Constant *BuiltinSetjmpFn;
51 Constant *FrameAddrFn;
52 Constant *StackAddrFn;
53 Constant *StackRestoreFn;
60 static char ID; // Pass identification, replacement for typeid
61 explicit SjLjEHPass(const TargetLowering *tli = NULL)
62 : FunctionPass(ID), TLI(tli) { }
63 bool doInitialization(Module &M);
64 bool runOnFunction(Function &F);
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
67 const char *getPassName() const {
68 return "SJLJ Exception Handling preparation";
72 bool setupEntryBlockAndCallSites(Function &F);
73 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
75 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
76 void lowerIncomingArguments(Function &F);
77 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
78 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
80 } // end anonymous namespace
82 char SjLjEHPass::ID = 0;
84 // Public Interface To the SjLjEHPass pass.
85 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
86 return new SjLjEHPass(TLI);
88 // doInitialization - Set up decalarations and types needed to process
90 bool SjLjEHPass::doInitialization(Module &M) {
91 // Build the function context structure.
92 // builtin_setjmp uses a five word jbuf
93 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
94 Type *Int32Ty = Type::getInt32Ty(M.getContext());
96 StructType::get(VoidPtrTy, // __prev
98 ArrayType::get(Int32Ty, 4), // __data
99 VoidPtrTy, // __personality
101 ArrayType::get(VoidPtrTy, 5), // __jbuf
103 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
104 Type::getVoidTy(M.getContext()),
105 PointerType::getUnqual(FunctionContextTy),
108 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
109 Type::getVoidTy(M.getContext()),
110 PointerType::getUnqual(FunctionContextTy),
112 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
113 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
114 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
115 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
116 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
117 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
118 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
124 /// insertCallSiteStore - Insert a store of the call-site value to the
126 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
128 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
130 // Insert a store of the call-site number
131 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
134 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
135 /// we reach blocks we've already seen.
136 static void MarkBlocksLiveIn(BasicBlock *BB,
137 SmallPtrSet<BasicBlock*, 64> &LiveBBs) {
138 if (!LiveBBs.insert(BB)) return; // already been here.
140 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
141 MarkBlocksLiveIn(*PI, LiveBBs);
144 /// substituteLPadValues - Substitute the values returned by the landingpad
145 /// instruction with those returned by the personality function.
146 void SjLjEHPass::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
148 SmallVector<Value*, 8> UseWorkList(LPI->use_begin(), LPI->use_end());
149 while (!UseWorkList.empty()) {
150 Value *Val = UseWorkList.pop_back_val();
151 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
153 if (EVI->getNumIndices() != 1) continue;
154 if (*EVI->idx_begin() == 0)
155 EVI->replaceAllUsesWith(ExnVal);
156 else if (*EVI->idx_begin() == 1)
157 EVI->replaceAllUsesWith(SelVal);
158 if (EVI->getNumUses() == 0)
159 EVI->eraseFromParent();
162 if (LPI->getNumUses() == 0) return;
164 // There are still some uses of LPI. Construct an aggregate with the exception
165 // values and replace the LPI with that aggregate.
166 Type *LPadType = LPI->getType();
167 Value *LPadVal = UndefValue::get(LPadType);
169 Builder(llvm::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
170 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
171 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
173 LPI->replaceAllUsesWith(LPadVal);
176 /// setupFunctionContext - Allocate the function context on the stack and fill
177 /// it with all of the data that we know at this point.
179 setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
180 BasicBlock *EntryBB = F.begin();
182 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
183 // that needs to be restored on all exits from the function. This is an alloca
184 // because the value needs to be added to the global context list.
186 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
187 AllocaInst *FuncCtx =
188 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
190 // Fill in the function context structure.
192 Type *Int32Ty = Type::getInt32Ty(F.getContext());
193 Value *Zero = ConstantInt::get(Int32Ty, 0);
194 Value *One = ConstantInt::get(Int32Ty, 1);
196 // Keep around a reference to the call_site field.
199 CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
200 EntryBB->getTerminator());
202 // Reference the __data field.
203 Idxs[1] = ConstantInt::get(Int32Ty, 2);
204 Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
205 EntryBB->getTerminator());
207 // The exception value comes back in context->__data[0].
209 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
211 EntryBB->getTerminator());
213 // The exception selector comes back in context->__data[1].
215 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
217 EntryBB->getTerminator());
219 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
220 LandingPadInst *LPI = LPads[I];
221 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
223 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
224 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
225 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
227 substituteLPadValues(LPI, ExnVal, SelVal);
230 // Personality function
231 Idxs[1] = ConstantInt::get(Int32Ty, 3);
233 PersonalityFn = LPads[0]->getPersonalityFn();
234 Value *PersonalityFieldPtr =
235 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
236 EntryBB->getTerminator());
237 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
238 EntryBB->getTerminator());
241 Idxs[1] = ConstantInt::get(Int32Ty, 4);
242 Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
243 EntryBB->getTerminator());
244 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
245 EntryBB->getTerminator());
246 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
251 /// lowerIncomingArguments - To avoid having to handle incoming arguments
252 /// specially, we lower each arg to a copy instruction in the entry block. This
253 /// ensures that the argument value itself cannot be live out of the entry
255 void SjLjEHPass::lowerIncomingArguments(Function &F) {
256 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
257 while (isa<AllocaInst>(AfterAllocaInsPt) &&
258 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
261 for (Function::arg_iterator
262 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
263 Type *Ty = AI->getType();
265 // Aggregate types can't be cast, but are legal argument types, so we have
266 // to handle them differently. We use an extract/insert pair as a
267 // lightweight method to achieve the same goal.
268 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
269 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
270 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
272 AI->replaceAllUsesWith(NI);
274 // Set the operand of the instructions back to the AllocaInst.
275 EI->setOperand(0, AI);
276 NI->setOperand(0, AI);
278 // This is always a no-op cast because we're casting AI to AI->getType()
279 // so src and destination types are identical. BitCast is the only
282 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
284 AI->replaceAllUsesWith(NC);
286 // Set the operand of the cast instruction back to the AllocaInst.
287 // Normally it's forbidden to replace a CastInst's operand because it
288 // could cause the opcode to reflect an illegal conversion. However, we're
289 // replacing it here with the same value it was constructed with. We do
290 // this because the above replaceAllUsesWith() clobbered the operand, but
291 // we want this one to remain.
292 NC->setOperand(0, AI);
297 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
298 /// edge and spill them.
299 void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
300 ArrayRef<InvokeInst*> Invokes) {
301 // Finally, scan the code looking for instructions with bad live ranges.
302 for (Function::iterator
303 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
304 for (BasicBlock::iterator
305 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
306 // Ignore obvious cases we don't have to handle. In particular, most
307 // instructions either have no uses or only have a single use inside the
308 // current block. Ignore them quickly.
309 Instruction *Inst = II;
310 if (Inst->use_empty()) continue;
311 if (Inst->hasOneUse() &&
312 cast<Instruction>(Inst->use_back())->getParent() == BB &&
313 !isa<PHINode>(Inst->use_back())) continue;
315 // If this is an alloca in the entry block, it's not a real register
317 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
318 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
321 // Avoid iterator invalidation by copying users to a temporary vector.
322 SmallVector<Instruction*, 16> Users;
323 for (Value::use_iterator
324 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
325 Instruction *User = cast<Instruction>(*UI);
326 if (User->getParent() != BB || isa<PHINode>(User))
327 Users.push_back(User);
330 // Find all of the blocks that this value is live in.
331 SmallPtrSet<BasicBlock*, 64> LiveBBs;
332 LiveBBs.insert(Inst->getParent());
333 while (!Users.empty()) {
334 Instruction *U = Users.back();
337 if (!isa<PHINode>(U)) {
338 MarkBlocksLiveIn(U->getParent(), LiveBBs);
340 // Uses for a PHI node occur in their predecessor block.
341 PHINode *PN = cast<PHINode>(U);
342 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
343 if (PN->getIncomingValue(i) == Inst)
344 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
348 // Now that we know all of the blocks that this thing is live in, see if
349 // it includes any of the unwind locations.
350 bool NeedsSpill = false;
351 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
352 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
353 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
354 DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
355 << UnwindBlock->getName() << "\n");
361 // If we decided we need a spill, do it.
362 // FIXME: Spilling this way is overkill, as it forces all uses of
363 // the value to be reloaded from the stack slot, even those that aren't
364 // in the unwind blocks. We should be more selective.
366 DemoteRegToStack(*Inst, true);
372 // Go through the landing pads and remove any PHIs there.
373 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
374 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
375 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
377 // Place PHIs into a set to avoid invalidating the iterator.
378 SmallPtrSet<PHINode*, 8> PHIsToDemote;
379 for (BasicBlock::iterator
380 PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
381 PHIsToDemote.insert(cast<PHINode>(PN));
382 if (PHIsToDemote.empty()) continue;
384 // Demote the PHIs to the stack.
385 for (SmallPtrSet<PHINode*, 8>::iterator
386 I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
387 DemotePHIToStack(*I);
389 // Move the landingpad instruction back to the top of the landing pad block.
390 LPI->moveBefore(UnwindBlock->begin());
394 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
395 /// the function context and marking the call sites with the appropriate
396 /// values. These values are used by the DWARF EH emitter.
397 bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
398 SmallVector<ReturnInst*, 16> Returns;
399 SmallVector<InvokeInst*, 16> Invokes;
400 SmallSetVector<LandingPadInst*, 16> LPads;
402 // Look through the terminators of the basic blocks to find invokes.
403 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
404 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
405 Invokes.push_back(II);
406 LPads.insert(II->getUnwindDest()->getLandingPadInst());
407 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
408 Returns.push_back(RI);
411 if (Invokes.empty()) return false;
413 NumInvokes += Invokes.size();
415 lowerIncomingArguments(F);
416 lowerAcrossUnwindEdges(F, Invokes);
419 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
420 BasicBlock *EntryBB = F.begin();
421 Type *Int32Ty = Type::getInt32Ty(F.getContext());
424 ConstantInt::get(Int32Ty, 0), 0
427 // Get a reference to the jump buffer.
428 Idxs[1] = ConstantInt::get(Int32Ty, 5);
429 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
430 EntryBB->getTerminator());
432 // Save the frame pointer.
433 Idxs[1] = ConstantInt::get(Int32Ty, 0);
434 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
435 EntryBB->getTerminator());
437 Value *Val = CallInst::Create(FrameAddrFn,
438 ConstantInt::get(Int32Ty, 0),
440 EntryBB->getTerminator());
441 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
443 // Save the stack pointer.
444 Idxs[1] = ConstantInt::get(Int32Ty, 2);
445 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
446 EntryBB->getTerminator());
448 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
449 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
451 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
452 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
453 Type::getInt8PtrTy(F.getContext()), "",
454 EntryBB->getTerminator());
455 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
457 // Store a pointer to the function context so that the back-end will know
458 // where to look for it.
459 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
460 Type::getInt8PtrTy(F.getContext()), "",
461 EntryBB->getTerminator());
462 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
464 // At this point, we are all set up, update the invoke instructions to mark
465 // their call_site values.
466 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
467 insertCallSiteStore(Invokes[I], I + 1, CallSite);
469 ConstantInt *CallSiteNum =
470 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
472 // Record the call site value for the back end so it stays associated with
474 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
477 // Mark call instructions that aren't nounwind as no-action (call_site ==
478 // -1). Skip the entry block, as prior to then, no function context has been
479 // created for this function and any unexpected exceptions thrown will go
480 // directly to the caller's context, which is what we want anyway, so no need
481 // to do anything here.
482 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
483 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
484 if (CallInst *CI = dyn_cast<CallInst>(I)) {
485 if (!CI->doesNotThrow())
486 insertCallSiteStore(CI, -1, CallSite);
487 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
488 insertCallSiteStore(RI, -1, CallSite);
491 // Register the function context and make sure it's known to not throw
492 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
493 EntryBB->getTerminator());
494 Register->setDoesNotThrow();
496 // Following any allocas not in the entry block, update the saved SP in the
497 // jmpbuf to the new value.
498 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
501 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
502 if (CallInst *CI = dyn_cast<CallInst>(I)) {
503 if (CI->getCalledFunction() != StackRestoreFn)
505 } else if (!isa<AllocaInst>(I)) {
508 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
509 StackAddr->insertAfter(I);
510 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
511 StoreStackAddr->insertAfter(StackAddr);
515 // Finally, for any returns from this function, if this function contains an
516 // invoke, add a call to unregister the function context.
517 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
518 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
523 bool SjLjEHPass::runOnFunction(Function &F) {
524 bool Res = setupEntryBlockAndCallSites(F);