1 //===- LowerInvoke.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 do not yet
11 // support stack unwinding. This pass supports two models of exception handling
12 // lowering, the 'cheap' support and the 'expensive' support.
14 // 'Cheap' exception handling support gives the program the ability to execute
15 // any program which does not "throw an exception", by turning 'invoke'
16 // instructions into calls and by turning 'unwind' instructions into calls to
17 // abort(). If the program does dynamically use the unwind instruction, the
18 // program will print a message then abort.
20 // 'Expensive' exception handling support gives the full exception handling
21 // support to the program at the cost of making the 'invoke' instruction
22 // really expensive. It basically inserts setjmp/longjmp calls to emulate the
23 // exception handling as necessary.
25 // Because the 'expensive' support slows down programs a lot, and EH is only
26 // used for a subset of the programs, it must be specifically enabled by an
29 // Note that after this pass runs the CFG is not entirely accurate (exceptional
30 // control flow edges are not correct anymore) so only very simple things should
31 // be done after the lowerinvoke pass has run (like generation of native code).
32 // This should not be used as a general purpose "my LLVM-to-LLVM pass doesn't
33 // support the invoke instruction yet" lowering pass.
35 //===----------------------------------------------------------------------===//
37 #define DEBUG_TYPE "lowerinvoke"
38 #include "llvm/Transforms/Scalar.h"
39 #include "llvm/Constants.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/Instructions.h"
42 #include "llvm/Intrinsics.h"
43 #include "llvm/LLVMContext.h"
44 #include "llvm/Module.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Target/TargetLowering.h"
56 STATISTIC(NumInvokes, "Number of invokes replaced");
57 STATISTIC(NumUnwinds, "Number of unwinds replaced");
58 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
60 static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
61 cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
64 class LowerInvoke : public FunctionPass {
65 // Used for both models.
69 unsigned AbortMessageLength;
71 // Used for expensive EH support.
73 GlobalVariable *JBListHead;
74 Constant *SetJmpFn, *LongJmpFn, *StackSaveFn, *StackRestoreFn;
75 bool useExpensiveEHSupport;
77 // We peek in TLI to grab the target's jmp_buf size and alignment
78 const TargetLowering *TLI;
81 static char ID; // Pass identification, replacement for typeid
82 explicit LowerInvoke(const TargetLowering *tli = NULL,
83 bool useExpensiveEHSupport = ExpensiveEHSupport)
84 : FunctionPass(&ID), useExpensiveEHSupport(useExpensiveEHSupport),
86 bool doInitialization(Module &M);
87 bool runOnFunction(Function &F);
89 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
90 // This is a cluster of orthogonal Transforms
91 AU.addPreservedID(PromoteMemoryToRegisterID);
92 AU.addPreservedID(LowerSwitchID);
96 void createAbortMessage(Module *M);
97 void writeAbortMessage(Instruction *IB);
98 bool insertCheapEHSupport(Function &F);
99 void splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*>&Invokes);
100 void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
101 AllocaInst *InvokeNum, AllocaInst *StackPtr,
102 SwitchInst *CatchSwitch);
103 bool insertExpensiveEHSupport(Function &F);
107 char LowerInvoke::ID = 0;
108 static RegisterPass<LowerInvoke>
109 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
111 const PassInfo *const llvm::LowerInvokePassID = &X;
113 // Public Interface To the LowerInvoke pass.
114 FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI) {
115 return new LowerInvoke(TLI, ExpensiveEHSupport);
117 FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI,
118 bool useExpensiveEHSupport) {
119 return new LowerInvoke(TLI, useExpensiveEHSupport);
122 // doInitialization - Make sure that there is a prototype for abort in the
124 bool LowerInvoke::doInitialization(Module &M) {
125 const Type *VoidPtrTy =
126 Type::getInt8PtrTy(M.getContext());
128 if (useExpensiveEHSupport) {
129 // Insert a type for the linked list of jump buffers.
130 unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
131 JBSize = JBSize ? JBSize : 200;
132 const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
134 { // The type is recursive, so use a type holder.
135 std::vector<const Type*> Elements;
136 Elements.push_back(JmpBufTy);
137 OpaqueType *OT = OpaqueType::get(M.getContext());
138 Elements.push_back(PointerType::getUnqual(OT));
139 PATypeHolder JBLType(StructType::get(M.getContext(), Elements));
140 OT->refineAbstractTypeTo(JBLType.get()); // Complete the cycle.
141 JBLinkTy = JBLType.get();
142 M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
145 const Type *PtrJBList = PointerType::getUnqual(JBLinkTy);
147 // Now that we've done that, insert the jmpbuf list head global, unless it
149 if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) {
150 JBListHead = new GlobalVariable(M, PtrJBList, false,
151 GlobalValue::LinkOnceAnyLinkage,
152 Constant::getNullValue(PtrJBList),
153 "llvm.sjljeh.jblist");
156 // VisualStudio defines setjmp as _setjmp via #include <csetjmp> / <setjmp.h>,
157 // so it looks like Intrinsic::_setjmp
158 #if defined(_MSC_VER) && defined(setjmp)
159 #define setjmp_undefined_for_visual_studio
163 SetJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::setjmp);
165 #if defined(_MSC_VER) && defined(setjmp_undefined_for_visual_studio)
166 // let's return it to _setjmp state in case anyone ever needs it after this
167 // point under VisualStudio
168 #define setjmp _setjmp
171 LongJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::longjmp);
172 StackSaveFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
173 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
176 // We need the 'write' and 'abort' functions for both models.
177 AbortFn = M.getOrInsertFunction("abort", Type::getVoidTy(M.getContext()),
179 #if 0 // "write" is Unix-specific.. code is going away soon anyway.
180 WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::Int32Ty,
181 VoidPtrTy, Type::Int32Ty, (Type *)0);
188 void LowerInvoke::createAbortMessage(Module *M) {
189 if (useExpensiveEHSupport) {
190 // The abort message for expensive EH support tells the user that the
191 // program 'unwound' without an 'invoke' instruction.
193 ConstantArray::get(M->getContext(),
194 "ERROR: Exception thrown, but not caught!\n");
195 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
197 GlobalVariable *MsgGV = new GlobalVariable(*M, Msg->getType(), true,
198 GlobalValue::InternalLinkage,
200 Constant *GEPIdx[2] = {
201 ConstantInt::get(Type::getInt32Ty(M->getContext()), 2),
202 Constant::getNullValue(Type::getInt32Ty(M->getContext())) };
203 AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, &GEPIdx[0], 2);
205 // The abort message for cheap EH support tells the user that EH is not
208 ConstantArray::get(M->getContext(),
209 "Exception handler needed, but not enabled."
210 "Recompile program with -enable-correct-eh-support.\n");
211 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
213 GlobalVariable *MsgGV = new GlobalVariable(*M, Msg->getType(), true,
214 GlobalValue::InternalLinkage,
216 Constant *GEPIdx[2] = {
217 ConstantInt::get(Type::getInt32Ty(M->getContext()), 2),
218 Constant::getNullValue(Type::getInt32Ty(M->getContext())) };
219 AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, &GEPIdx[0], 2);
224 void LowerInvoke::writeAbortMessage(Instruction *IB) {
226 if (AbortMessage == 0)
227 createAbortMessage(IB->getParent()->getParent()->getParent());
229 // These are the arguments we WANT...
231 Args[0] = ConstantInt::get(Type::Int32Ty, 2);
232 Args[1] = AbortMessage;
233 Args[2] = ConstantInt::get(Type::Int32Ty, AbortMessageLength);
234 (new CallInst(WriteFn, Args, 3, "", IB))->setTailCall();
238 bool LowerInvoke::insertCheapEHSupport(Function &F) {
239 bool Changed = false;
240 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
241 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
242 SmallVector<Value*,16> CallArgs(II->op_begin(), II->op_end() - 3);
243 // Insert a normal call instruction...
244 CallInst *NewCall = CallInst::Create(II->getCalledValue(),
245 CallArgs.begin(), CallArgs.end(),
247 NewCall->takeName(II);
248 NewCall->setCallingConv(II->getCallingConv());
249 NewCall->setAttributes(II->getAttributes());
250 II->replaceAllUsesWith(NewCall);
252 // Insert an unconditional branch to the normal destination.
253 BranchInst::Create(II->getNormalDest(), II);
255 // Remove any PHI node entries from the exception destination.
256 II->getUnwindDest()->removePredecessor(BB);
258 // Remove the invoke instruction now.
259 BB->getInstList().erase(II);
261 ++NumInvokes; Changed = true;
262 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
263 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
264 writeAbortMessage(UI);
266 // Insert a call to abort()
267 CallInst::Create(AbortFn, "", UI)->setTailCall();
269 // Insert a return instruction. This really should be a "barrier", as it
271 ReturnInst::Create(F.getContext(),
272 F.getReturnType()->isVoidTy() ?
273 0 : Constant::getNullValue(F.getReturnType()), UI);
275 // Remove the unwind instruction now.
276 BB->getInstList().erase(UI);
278 ++NumUnwinds; Changed = true;
283 /// rewriteExpensiveInvoke - Insert code and hack the function to replace the
284 /// specified invoke instruction with a call.
285 void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
286 AllocaInst *InvokeNum,
287 AllocaInst *StackPtr,
288 SwitchInst *CatchSwitch) {
289 ConstantInt *InvokeNoC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
292 // If the unwind edge has phi nodes, split the edge.
293 if (isa<PHINode>(II->getUnwindDest()->begin())) {
294 SplitCriticalEdge(II, 1, this);
296 // If there are any phi nodes left, they must have a single predecessor.
297 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
298 PN->replaceAllUsesWith(PN->getIncomingValue(0));
299 PN->eraseFromParent();
303 // Insert a store of the invoke num before the invoke and store zero into the
304 // location afterward.
305 new StoreInst(InvokeNoC, InvokeNum, true, II); // volatile
307 // Insert a store of the stack ptr before the invoke, so we can restore it
308 // later in the exception case.
309 CallInst* StackSaveRet = CallInst::Create(StackSaveFn, "ssret", II);
310 new StoreInst(StackSaveRet, StackPtr, true, II); // volatile
312 BasicBlock::iterator NI = II->getNormalDest()->getFirstNonPHI();
314 new StoreInst(Constant::getNullValue(Type::getInt32Ty(II->getContext())),
315 InvokeNum, false, NI);
317 Instruction* StackPtrLoad = new LoadInst(StackPtr, "stackptr.restore", true,
318 II->getUnwindDest()->getFirstNonPHI()
320 CallInst::Create(StackRestoreFn, StackPtrLoad, "")->insertAfter(StackPtrLoad);
322 // Add a switch case to our unwind block.
323 CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
325 // Insert a normal call instruction.
326 SmallVector<Value*,16> CallArgs(II->op_begin(), II->op_end() - 3);
327 CallInst *NewCall = CallInst::Create(II->getCalledValue(),
328 CallArgs.begin(), CallArgs.end(), "",
330 NewCall->takeName(II);
331 NewCall->setCallingConv(II->getCallingConv());
332 NewCall->setAttributes(II->getAttributes());
333 II->replaceAllUsesWith(NewCall);
335 // Replace the invoke with an uncond branch.
336 BranchInst::Create(II->getNormalDest(), NewCall->getParent());
337 II->eraseFromParent();
340 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
341 /// we reach blocks we've already seen.
342 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
343 if (!LiveBBs.insert(BB).second) return; // already been here.
345 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
346 MarkBlocksLiveIn(*PI, LiveBBs);
349 // First thing we need to do is scan the whole function for values that are
350 // live across unwind edges. Each value that is live across an unwind edge
351 // we spill into a stack location, guaranteeing that there is nothing live
352 // across the unwind edge. This process also splits all critical edges
353 // coming out of invoke's.
355 splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*> &Invokes) {
356 // First step, split all critical edges from invoke instructions.
357 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
358 InvokeInst *II = Invokes[i];
359 SplitCriticalEdge(II, 0, this);
360 SplitCriticalEdge(II, 1, this);
361 assert(!isa<PHINode>(II->getNormalDest()) &&
362 !isa<PHINode>(II->getUnwindDest()) &&
363 "critical edge splitting left single entry phi nodes?");
366 Function *F = Invokes.back()->getParent()->getParent();
368 // To avoid having to handle incoming arguments specially, we lower each arg
369 // to a copy instruction in the entry block. This ensures that the argument
370 // value itself cannot be live across the entry block.
371 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
372 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
373 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
374 ++AfterAllocaInsertPt;
375 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
377 const Type *Ty = AI->getType();
378 // StructType can't be cast, but is a legal argument type, so we have
379 // to handle them differently. We use an extract/insert pair as a
380 // lightweight method to achieve the same goal.
381 if (isa<StructType>(Ty)) {
382 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsertPt);
383 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
385 AI->replaceAllUsesWith(NI);
386 // Set the struct operand of the instructions back to the AllocaInst.
387 EI->setOperand(0, AI);
388 NI->setOperand(0, AI);
390 // This is always a no-op cast because we're casting AI to AI->getType()
391 // so src and destination types are identical. BitCast is the only
393 CastInst *NC = new BitCastInst(
394 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
395 AI->replaceAllUsesWith(NC);
396 // Set the operand of the cast instruction back to the AllocaInst.
397 // Normally it's forbidden to replace a CastInst's operand because it
398 // could cause the opcode to reflect an illegal conversion. However,
399 // we're replacing it here with the same value it was constructed with.
400 // We do this because the above replaceAllUsesWith() clobbered the
401 // operand, but we want this one to remain.
402 NC->setOperand(0, AI);
406 // Finally, scan the code looking for instructions with bad live ranges.
407 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
408 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
409 // Ignore obvious cases we don't have to handle. In particular, most
410 // instructions either have no uses or only have a single use inside the
411 // current block. Ignore them quickly.
412 Instruction *Inst = II;
413 if (Inst->use_empty()) continue;
414 if (Inst->hasOneUse() &&
415 cast<Instruction>(Inst->use_back())->getParent() == BB &&
416 !isa<PHINode>(Inst->use_back())) continue;
418 // If this is an alloca in the entry block, it's not a real register
420 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
421 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
424 // Avoid iterator invalidation by copying users to a temporary vector.
425 SmallVector<Instruction*,16> Users;
426 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
428 Instruction *User = cast<Instruction>(*UI);
429 if (User->getParent() != BB || isa<PHINode>(User))
430 Users.push_back(User);
433 // Scan all of the uses and see if the live range is live across an unwind
434 // edge. If we find a use live across an invoke edge, create an alloca
435 // and spill the value.
436 std::set<InvokeInst*> InvokesWithStoreInserted;
438 // Find all of the blocks that this value is live in.
439 std::set<BasicBlock*> LiveBBs;
440 LiveBBs.insert(Inst->getParent());
441 while (!Users.empty()) {
442 Instruction *U = Users.back();
445 if (!isa<PHINode>(U)) {
446 MarkBlocksLiveIn(U->getParent(), LiveBBs);
448 // Uses for a PHI node occur in their predecessor block.
449 PHINode *PN = cast<PHINode>(U);
450 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
451 if (PN->getIncomingValue(i) == Inst)
452 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
456 // Now that we know all of the blocks that this thing is live in, see if
457 // it includes any of the unwind locations.
458 bool NeedsSpill = false;
459 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
460 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
461 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
466 // If we decided we need a spill, do it.
469 DemoteRegToStack(*Inst, true);
474 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
475 SmallVector<ReturnInst*,16> Returns;
476 SmallVector<UnwindInst*,16> Unwinds;
477 SmallVector<InvokeInst*,16> Invokes;
479 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
480 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
481 // Remember all return instructions in case we insert an invoke into this
483 Returns.push_back(RI);
484 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
485 Invokes.push_back(II);
486 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
487 Unwinds.push_back(UI);
490 if (Unwinds.empty() && Invokes.empty()) return false;
492 NumInvokes += Invokes.size();
493 NumUnwinds += Unwinds.size();
495 // TODO: This is not an optimal way to do this. In particular, this always
496 // inserts setjmp calls into the entries of functions with invoke instructions
497 // even though there are possibly paths through the function that do not
498 // execute any invokes. In particular, for functions with early exits, e.g.
499 // the 'addMove' method in hexxagon, it would be nice to not have to do the
500 // setjmp stuff on the early exit path. This requires a bit of dataflow, but
501 // would not be too hard to do.
503 // If we have an invoke instruction, insert a setjmp that dominates all
504 // invokes. After the setjmp, use a cond branch that goes to the original
505 // code path on zero, and to a designated 'catch' block of nonzero.
506 Value *OldJmpBufPtr = 0;
507 if (!Invokes.empty()) {
508 // First thing we need to do is scan the whole function for values that are
509 // live across unwind edges. Each value that is live across an unwind edge
510 // we spill into a stack location, guaranteeing that there is nothing live
511 // across the unwind edge. This process also splits all critical edges
512 // coming out of invoke's.
513 splitLiveRangesLiveAcrossInvokes(Invokes);
515 BasicBlock *EntryBB = F.begin();
517 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
518 // that needs to be restored on all exits from the function. This is an
519 // alloca because the value needs to be live across invokes.
520 unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0;
522 new AllocaInst(JBLinkTy, 0, Align,
523 "jblink", F.begin()->begin());
525 Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())),
526 ConstantInt::get(Type::getInt32Ty(F.getContext()), 1) };
527 OldJmpBufPtr = GetElementPtrInst::Create(JmpBuf, &Idx[0], &Idx[2],
529 EntryBB->getTerminator());
531 // Copy the JBListHead to the alloca.
532 Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
533 EntryBB->getTerminator());
534 new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
536 // Add the new jumpbuf to the list.
537 new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
539 // Create the catch block. The catch block is basically a big switch
540 // statement that goes to all of the invoke catch blocks.
541 BasicBlock *CatchBB =
542 BasicBlock::Create(F.getContext(), "setjmp.catch", &F);
544 // Create an alloca which keeps track of the stack pointer before every
545 // invoke, this allows us to properly restore the stack pointer after
547 AllocaInst *StackPtr = new AllocaInst(Type::getInt8PtrTy(F.getContext()), 0,
548 "stackptr", EntryBB->begin());
550 // Create an alloca which keeps track of which invoke is currently
551 // executing. For normal calls it contains zero.
552 AllocaInst *InvokeNum = new AllocaInst(Type::getInt32Ty(F.getContext()), 0,
553 "invokenum",EntryBB->begin());
554 new StoreInst(ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
555 InvokeNum, true, EntryBB->getTerminator());
557 // Insert a load in the Catch block, and a switch on its value. By default,
558 // we go to a block that just does an unwind (which is the correct action
559 // for a standard call).
560 BasicBlock *UnwindBB = BasicBlock::Create(F.getContext(), "unwindbb", &F);
561 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBB));
563 Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
564 SwitchInst *CatchSwitch =
565 SwitchInst::Create(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
567 // Now that things are set up, insert the setjmp call itself.
569 // Split the entry block to insert the conditional branch for the setjmp.
570 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
573 Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 0);
574 Value *JmpBufPtr = GetElementPtrInst::Create(JmpBuf, &Idx[0], &Idx[2],
576 EntryBB->getTerminator());
577 JmpBufPtr = new BitCastInst(JmpBufPtr,
578 Type::getInt8PtrTy(F.getContext()),
579 "tmp", EntryBB->getTerminator());
580 Value *SJRet = CallInst::Create(SetJmpFn, JmpBufPtr, "sjret",
581 EntryBB->getTerminator());
583 // Compare the return value to zero.
584 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
585 ICmpInst::ICMP_EQ, SJRet,
586 Constant::getNullValue(SJRet->getType()),
588 // Nuke the uncond branch.
589 EntryBB->getTerminator()->eraseFromParent();
591 // Put in a new condbranch in its place.
592 BranchInst::Create(ContBlock, CatchBB, IsNormal, EntryBB);
594 // At this point, we are all set up, rewrite each invoke instruction.
595 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
596 rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, StackPtr, CatchSwitch);
599 // We know that there is at least one unwind.
601 // Create three new blocks, the block to load the jmpbuf ptr and compare
602 // against null, the block to do the longjmp, and the error block for if it
603 // is null. Add them at the end of the function because they are not hot.
604 BasicBlock *UnwindHandler = BasicBlock::Create(F.getContext(),
606 BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwind", &F);
607 BasicBlock *TermBlock = BasicBlock::Create(F.getContext(), "unwinderror", &F);
609 // If this function contains an invoke, restore the old jumpbuf ptr.
612 // Before the return, insert a copy from the saved value to the new value.
613 BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
614 new StoreInst(BufPtr, JBListHead, UnwindHandler);
616 BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
619 // Load the JBList, if it's null, then there was no catch!
620 Value *NotNull = new ICmpInst(*UnwindHandler, ICmpInst::ICMP_NE, BufPtr,
621 Constant::getNullValue(BufPtr->getType()),
623 BranchInst::Create(UnwindBlock, TermBlock, NotNull, UnwindHandler);
625 // Create the block to do the longjmp.
626 // Get a pointer to the jmpbuf and longjmp.
627 Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())),
628 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0) };
629 Idx[0] = GetElementPtrInst::Create(BufPtr, &Idx[0], &Idx[2], "JmpBuf",
631 Idx[0] = new BitCastInst(Idx[0],
632 Type::getInt8PtrTy(F.getContext()),
634 Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 1);
635 CallInst::Create(LongJmpFn, &Idx[0], &Idx[2], "", UnwindBlock);
636 new UnreachableInst(F.getContext(), UnwindBlock);
638 // Set up the term block ("throw without a catch").
639 new UnreachableInst(F.getContext(), TermBlock);
641 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
642 writeAbortMessage(TermBlock->getTerminator());
644 // Insert a call to abort()
645 CallInst::Create(AbortFn, "",
646 TermBlock->getTerminator())->setTailCall();
649 // Replace all unwinds with a branch to the unwind handler.
650 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
651 BranchInst::Create(UnwindHandler, Unwinds[i]);
652 Unwinds[i]->eraseFromParent();
655 // Finally, for any returns from this function, if this function contains an
656 // invoke, restore the old jmpbuf pointer to its input value.
658 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
659 ReturnInst *R = Returns[i];
661 // Before the return, insert a copy from the saved value to the new value.
662 Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
663 new StoreInst(OldBuf, JBListHead, true, R);
670 bool LowerInvoke::runOnFunction(Function &F) {
671 if (useExpensiveEHSupport)
672 return insertExpensiveEHSupport(F);
674 return insertCheapEHSupport(F);