Get rid of pop_macro warnings on MSVC.
[oota-llvm.git] / lib / Transforms / Utils / LowerInvoke.cpp
1 //===- LowerInvoke.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 do not yet
11 // support stack unwinding.  This pass supports two models of exception handling
12 // lowering, the 'cheap' support and the 'expensive' support.
13 //
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.
19 //
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.
24 //
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
27 // option.
28 //
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.
34 //
35 //===----------------------------------------------------------------------===//
36
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"
52 #include <csetjmp>
53 #include <set>
54 using namespace llvm;
55
56 STATISTIC(NumInvokes, "Number of invokes replaced");
57 STATISTIC(NumUnwinds, "Number of unwinds replaced");
58 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
59
60 static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
61  cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
62
63 namespace {
64   class LowerInvoke : public FunctionPass {
65     // Used for both models.
66     Constant *AbortFn;
67
68     // Used for expensive EH support.
69     const Type *JBLinkTy;
70     GlobalVariable *JBListHead;
71     Constant *SetJmpFn, *LongJmpFn, *StackSaveFn, *StackRestoreFn;
72     bool useExpensiveEHSupport;
73
74     // We peek in TLI to grab the target's jmp_buf size and alignment
75     const TargetLowering *TLI;
76
77   public:
78     static char ID; // Pass identification, replacement for typeid
79     explicit LowerInvoke(const TargetLowering *tli = NULL,
80                          bool useExpensiveEHSupport = ExpensiveEHSupport)
81       : FunctionPass(ID), useExpensiveEHSupport(useExpensiveEHSupport),
82         TLI(tli) { }
83     bool doInitialization(Module &M);
84     bool runOnFunction(Function &F);
85
86     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87       // This is a cluster of orthogonal Transforms
88       AU.addPreserved("mem2reg");
89       AU.addPreservedID(LowerSwitchID);
90     }
91
92   private:
93     bool insertCheapEHSupport(Function &F);
94     void splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*>&Invokes);
95     void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
96                                 AllocaInst *InvokeNum, AllocaInst *StackPtr,
97                                 SwitchInst *CatchSwitch);
98     bool insertExpensiveEHSupport(Function &F);
99   };
100 }
101
102 char LowerInvoke::ID = 0;
103 INITIALIZE_PASS(LowerInvoke, "lowerinvoke",
104                 "Lower invoke and unwind, for unwindless code generators",
105                 false, false);
106
107 char &llvm::LowerInvokePassID = LowerInvoke::ID;
108
109 // Public Interface To the LowerInvoke pass.
110 FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI) {
111   return new LowerInvoke(TLI, ExpensiveEHSupport);
112 }
113 FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI,
114                                           bool useExpensiveEHSupport) {
115   return new LowerInvoke(TLI, useExpensiveEHSupport);
116 }
117
118 // doInitialization - Make sure that there is a prototype for abort in the
119 // current module.
120 bool LowerInvoke::doInitialization(Module &M) {
121   const Type *VoidPtrTy =
122           Type::getInt8PtrTy(M.getContext());
123   if (useExpensiveEHSupport) {
124     // Insert a type for the linked list of jump buffers.
125     unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
126     JBSize = JBSize ? JBSize : 200;
127     const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
128
129     { // The type is recursive, so use a type holder.
130       std::vector<const Type*> Elements;
131       Elements.push_back(JmpBufTy);
132       OpaqueType *OT = OpaqueType::get(M.getContext());
133       Elements.push_back(PointerType::getUnqual(OT));
134       PATypeHolder JBLType(StructType::get(M.getContext(), Elements));
135       OT->refineAbstractTypeTo(JBLType.get());  // Complete the cycle.
136       JBLinkTy = JBLType.get();
137       M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
138     }
139
140     const Type *PtrJBList = PointerType::getUnqual(JBLinkTy);
141
142     // Now that we've done that, insert the jmpbuf list head global, unless it
143     // already exists.
144     if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) {
145       JBListHead = new GlobalVariable(M, PtrJBList, false,
146                                       GlobalValue::LinkOnceAnyLinkage,
147                                       Constant::getNullValue(PtrJBList),
148                                       "llvm.sjljeh.jblist");
149     }
150
151 // VisualStudio defines setjmp as _setjmp
152 #if defined(_MSC_VER) && defined(setjmp) && \
153                          !defined(setjmp_undefined_for_msvc)
154 #  pragma push_macro("setjmp")
155 #  undef setjmp
156 #  define setjmp_undefined_for_msvc
157 #endif
158
159     SetJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::setjmp);
160
161 #if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
162    // let's return it to _setjmp state
163 #  pragma pop_macro("setjmp")
164 #  undef setjmp_undefined_for_msvc
165 #endif
166
167     LongJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::longjmp);
168     StackSaveFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
169     StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
170   }
171
172   // We need the 'write' and 'abort' functions for both models.
173   AbortFn = M.getOrInsertFunction("abort", Type::getVoidTy(M.getContext()),
174                                   (Type *)0);
175   return true;
176 }
177
178 bool LowerInvoke::insertCheapEHSupport(Function &F) {
179   bool Changed = false;
180   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
181     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
182       SmallVector<Value*,16> CallArgs(II->op_begin(), II->op_end() - 3);
183       // Insert a normal call instruction...
184       CallInst *NewCall = CallInst::Create(II->getCalledValue(),
185                                            CallArgs.begin(), CallArgs.end(),
186                                            "",II);
187       NewCall->takeName(II);
188       NewCall->setCallingConv(II->getCallingConv());
189       NewCall->setAttributes(II->getAttributes());
190       II->replaceAllUsesWith(NewCall);
191
192       // Insert an unconditional branch to the normal destination.
193       BranchInst::Create(II->getNormalDest(), II);
194
195       // Remove any PHI node entries from the exception destination.
196       II->getUnwindDest()->removePredecessor(BB);
197
198       // Remove the invoke instruction now.
199       BB->getInstList().erase(II);
200
201       ++NumInvokes; Changed = true;
202     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
203       // Insert a call to abort()
204       CallInst::Create(AbortFn, "", UI)->setTailCall();
205
206       // Insert a return instruction.  This really should be a "barrier", as it
207       // is unreachable.
208       ReturnInst::Create(F.getContext(),
209                          F.getReturnType()->isVoidTy() ?
210                           0 : Constant::getNullValue(F.getReturnType()), UI);
211
212       // Remove the unwind instruction now.
213       BB->getInstList().erase(UI);
214
215       ++NumUnwinds; Changed = true;
216     }
217   return Changed;
218 }
219
220 /// rewriteExpensiveInvoke - Insert code and hack the function to replace the
221 /// specified invoke instruction with a call.
222 void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
223                                          AllocaInst *InvokeNum,
224                                          AllocaInst *StackPtr,
225                                          SwitchInst *CatchSwitch) {
226   ConstantInt *InvokeNoC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
227                                             InvokeNo);
228
229   // If the unwind edge has phi nodes, split the edge.
230   if (isa<PHINode>(II->getUnwindDest()->begin())) {
231     SplitCriticalEdge(II, 1, this);
232
233     // If there are any phi nodes left, they must have a single predecessor.
234     while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
235       PN->replaceAllUsesWith(PN->getIncomingValue(0));
236       PN->eraseFromParent();
237     }
238   }
239
240   // Insert a store of the invoke num before the invoke and store zero into the
241   // location afterward.
242   new StoreInst(InvokeNoC, InvokeNum, true, II);  // volatile
243   
244   // Insert a store of the stack ptr before the invoke, so we can restore it
245   // later in the exception case.
246   CallInst* StackSaveRet = CallInst::Create(StackSaveFn, "ssret", II);
247   new StoreInst(StackSaveRet, StackPtr, true, II); // volatile
248
249   BasicBlock::iterator NI = II->getNormalDest()->getFirstNonPHI();
250   // nonvolatile.
251   new StoreInst(Constant::getNullValue(Type::getInt32Ty(II->getContext())), 
252                 InvokeNum, false, NI);
253
254   Instruction* StackPtrLoad = new LoadInst(StackPtr, "stackptr.restore", true,
255                                            II->getUnwindDest()->getFirstNonPHI()
256                                            );
257   CallInst::Create(StackRestoreFn, StackPtrLoad, "")->insertAfter(StackPtrLoad);
258     
259   // Add a switch case to our unwind block.
260   CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
261
262   // Insert a normal call instruction.
263   SmallVector<Value*,16> CallArgs(II->op_begin(), II->op_end() - 3);
264   CallInst *NewCall = CallInst::Create(II->getCalledValue(),
265                                        CallArgs.begin(), CallArgs.end(), "",
266                                        II);
267   NewCall->takeName(II);
268   NewCall->setCallingConv(II->getCallingConv());
269   NewCall->setAttributes(II->getAttributes());
270   II->replaceAllUsesWith(NewCall);
271
272   // Replace the invoke with an uncond branch.
273   BranchInst::Create(II->getNormalDest(), NewCall->getParent());
274   II->eraseFromParent();
275 }
276
277 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
278 /// we reach blocks we've already seen.
279 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
280   if (!LiveBBs.insert(BB).second) return; // already been here.
281
282   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
283     MarkBlocksLiveIn(*PI, LiveBBs);
284 }
285
286 // First thing we need to do is scan the whole function for values that are
287 // live across unwind edges.  Each value that is live across an unwind edge
288 // we spill into a stack location, guaranteeing that there is nothing live
289 // across the unwind edge.  This process also splits all critical edges
290 // coming out of invoke's.
291 void LowerInvoke::
292 splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*> &Invokes) {
293   // First step, split all critical edges from invoke instructions.
294   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
295     InvokeInst *II = Invokes[i];
296     SplitCriticalEdge(II, 0, this);
297     SplitCriticalEdge(II, 1, this);
298     assert(!isa<PHINode>(II->getNormalDest()) &&
299            !isa<PHINode>(II->getUnwindDest()) &&
300            "critical edge splitting left single entry phi nodes?");
301   }
302
303   Function *F = Invokes.back()->getParent()->getParent();
304
305   // To avoid having to handle incoming arguments specially, we lower each arg
306   // to a copy instruction in the entry block.  This ensures that the argument
307   // value itself cannot be live across the entry block.
308   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
309   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
310         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
311     ++AfterAllocaInsertPt;
312   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
313        AI != E; ++AI) {
314     const Type *Ty = AI->getType();
315     // Aggregate types can't be cast, but are legal argument types, so we have
316     // to handle them differently. We use an extract/insert pair as a
317     // lightweight method to achieve the same goal.
318     if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
319       Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
320       Instruction *NI = InsertValueInst::Create(AI, EI, 0);
321       NI->insertAfter(EI);
322       AI->replaceAllUsesWith(NI);
323       // Set the operand of the instructions back to the AllocaInst.
324       EI->setOperand(0, AI);
325       NI->setOperand(0, AI);
326     } else {
327       // This is always a no-op cast because we're casting AI to AI->getType()
328       // so src and destination types are identical. BitCast is the only
329       // possibility.
330       CastInst *NC = new BitCastInst(
331         AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
332       AI->replaceAllUsesWith(NC);
333       // Set the operand of the cast instruction back to the AllocaInst.
334       // Normally it's forbidden to replace a CastInst's operand because it
335       // could cause the opcode to reflect an illegal conversion. However,
336       // we're replacing it here with the same value it was constructed with.
337       // We do this because the above replaceAllUsesWith() clobbered the
338       // operand, but we want this one to remain.
339       NC->setOperand(0, AI);
340     }
341   }
342
343   // Finally, scan the code looking for instructions with bad live ranges.
344   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
345     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
346       // Ignore obvious cases we don't have to handle.  In particular, most
347       // instructions either have no uses or only have a single use inside the
348       // current block.  Ignore them quickly.
349       Instruction *Inst = II;
350       if (Inst->use_empty()) continue;
351       if (Inst->hasOneUse() &&
352           cast<Instruction>(Inst->use_back())->getParent() == BB &&
353           !isa<PHINode>(Inst->use_back())) continue;
354
355       // If this is an alloca in the entry block, it's not a real register
356       // value.
357       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
358         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
359           continue;
360
361       // Avoid iterator invalidation by copying users to a temporary vector.
362       SmallVector<Instruction*,16> Users;
363       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
364            UI != E; ++UI) {
365         Instruction *User = cast<Instruction>(*UI);
366         if (User->getParent() != BB || isa<PHINode>(User))
367           Users.push_back(User);
368       }
369
370       // Scan all of the uses and see if the live range is live across an unwind
371       // edge.  If we find a use live across an invoke edge, create an alloca
372       // and spill the value.
373       std::set<InvokeInst*> InvokesWithStoreInserted;
374
375       // Find all of the blocks that this value is live in.
376       std::set<BasicBlock*> LiveBBs;
377       LiveBBs.insert(Inst->getParent());
378       while (!Users.empty()) {
379         Instruction *U = Users.back();
380         Users.pop_back();
381
382         if (!isa<PHINode>(U)) {
383           MarkBlocksLiveIn(U->getParent(), LiveBBs);
384         } else {
385           // Uses for a PHI node occur in their predecessor block.
386           PHINode *PN = cast<PHINode>(U);
387           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
388             if (PN->getIncomingValue(i) == Inst)
389               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
390         }
391       }
392
393       // Now that we know all of the blocks that this thing is live in, see if
394       // it includes any of the unwind locations.
395       bool NeedsSpill = false;
396       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
397         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
398         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
399           NeedsSpill = true;
400         }
401       }
402
403       // If we decided we need a spill, do it.
404       if (NeedsSpill) {
405         ++NumSpilled;
406         DemoteRegToStack(*Inst, true);
407       }
408     }
409 }
410
411 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
412   SmallVector<ReturnInst*,16> Returns;
413   SmallVector<UnwindInst*,16> Unwinds;
414   SmallVector<InvokeInst*,16> Invokes;
415
416   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
417     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
418       // Remember all return instructions in case we insert an invoke into this
419       // function.
420       Returns.push_back(RI);
421     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
422       Invokes.push_back(II);
423     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
424       Unwinds.push_back(UI);
425     }
426
427   if (Unwinds.empty() && Invokes.empty()) return false;
428
429   NumInvokes += Invokes.size();
430   NumUnwinds += Unwinds.size();
431
432   // TODO: This is not an optimal way to do this.  In particular, this always
433   // inserts setjmp calls into the entries of functions with invoke instructions
434   // even though there are possibly paths through the function that do not
435   // execute any invokes.  In particular, for functions with early exits, e.g.
436   // the 'addMove' method in hexxagon, it would be nice to not have to do the
437   // setjmp stuff on the early exit path.  This requires a bit of dataflow, but
438   // would not be too hard to do.
439
440   // If we have an invoke instruction, insert a setjmp that dominates all
441   // invokes.  After the setjmp, use a cond branch that goes to the original
442   // code path on zero, and to a designated 'catch' block of nonzero.
443   Value *OldJmpBufPtr = 0;
444   if (!Invokes.empty()) {
445     // First thing we need to do is scan the whole function for values that are
446     // live across unwind edges.  Each value that is live across an unwind edge
447     // we spill into a stack location, guaranteeing that there is nothing live
448     // across the unwind edge.  This process also splits all critical edges
449     // coming out of invoke's.
450     splitLiveRangesLiveAcrossInvokes(Invokes);
451
452     BasicBlock *EntryBB = F.begin();
453
454     // Create an alloca for the incoming jump buffer ptr and the new jump buffer
455     // that needs to be restored on all exits from the function.  This is an
456     // alloca because the value needs to be live across invokes.
457     unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0;
458     AllocaInst *JmpBuf =
459       new AllocaInst(JBLinkTy, 0, Align,
460                      "jblink", F.begin()->begin());
461
462     Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())),
463                      ConstantInt::get(Type::getInt32Ty(F.getContext()), 1) };
464     OldJmpBufPtr = GetElementPtrInst::Create(JmpBuf, &Idx[0], &Idx[2],
465                                              "OldBuf",
466                                              EntryBB->getTerminator());
467
468     // Copy the JBListHead to the alloca.
469     Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
470                                  EntryBB->getTerminator());
471     new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
472
473     // Add the new jumpbuf to the list.
474     new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
475
476     // Create the catch block.  The catch block is basically a big switch
477     // statement that goes to all of the invoke catch blocks.
478     BasicBlock *CatchBB =
479             BasicBlock::Create(F.getContext(), "setjmp.catch", &F);
480
481     // Create an alloca which keeps track of the stack pointer before every
482     // invoke, this allows us to properly restore the stack pointer after
483     // long jumping.
484     AllocaInst *StackPtr = new AllocaInst(Type::getInt8PtrTy(F.getContext()), 0,
485                                           "stackptr", EntryBB->begin());
486
487     // Create an alloca which keeps track of which invoke is currently
488     // executing.  For normal calls it contains zero.
489     AllocaInst *InvokeNum = new AllocaInst(Type::getInt32Ty(F.getContext()), 0,
490                                            "invokenum",EntryBB->begin());
491     new StoreInst(ConstantInt::get(Type::getInt32Ty(F.getContext()), 0), 
492                   InvokeNum, true, EntryBB->getTerminator());
493
494     // Insert a load in the Catch block, and a switch on its value.  By default,
495     // we go to a block that just does an unwind (which is the correct action
496     // for a standard call).
497     BasicBlock *UnwindBB = BasicBlock::Create(F.getContext(), "unwindbb", &F);
498     Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBB));
499
500     Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
501     SwitchInst *CatchSwitch =
502       SwitchInst::Create(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
503
504     // Now that things are set up, insert the setjmp call itself.
505
506     // Split the entry block to insert the conditional branch for the setjmp.
507     BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
508                                                      "setjmp.cont");
509
510     Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 0);
511     Value *JmpBufPtr = GetElementPtrInst::Create(JmpBuf, &Idx[0], &Idx[2],
512                                                  "TheJmpBuf",
513                                                  EntryBB->getTerminator());
514     JmpBufPtr = new BitCastInst(JmpBufPtr,
515                         Type::getInt8PtrTy(F.getContext()),
516                                 "tmp", EntryBB->getTerminator());
517     Value *SJRet = CallInst::Create(SetJmpFn, JmpBufPtr, "sjret",
518                                     EntryBB->getTerminator());
519
520     // Compare the return value to zero.
521     Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
522                                    ICmpInst::ICMP_EQ, SJRet,
523                                    Constant::getNullValue(SJRet->getType()),
524                                    "notunwind");
525     // Nuke the uncond branch.
526     EntryBB->getTerminator()->eraseFromParent();
527
528     // Put in a new condbranch in its place.
529     BranchInst::Create(ContBlock, CatchBB, IsNormal, EntryBB);
530
531     // At this point, we are all set up, rewrite each invoke instruction.
532     for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
533       rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, StackPtr, CatchSwitch);
534   }
535
536   // We know that there is at least one unwind.
537
538   // Create three new blocks, the block to load the jmpbuf ptr and compare
539   // against null, the block to do the longjmp, and the error block for if it
540   // is null.  Add them at the end of the function because they are not hot.
541   BasicBlock *UnwindHandler = BasicBlock::Create(F.getContext(),
542                                                 "dounwind", &F);
543   BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwind", &F);
544   BasicBlock *TermBlock = BasicBlock::Create(F.getContext(), "unwinderror", &F);
545
546   // If this function contains an invoke, restore the old jumpbuf ptr.
547   Value *BufPtr;
548   if (OldJmpBufPtr) {
549     // Before the return, insert a copy from the saved value to the new value.
550     BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
551     new StoreInst(BufPtr, JBListHead, UnwindHandler);
552   } else {
553     BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
554   }
555
556   // Load the JBList, if it's null, then there was no catch!
557   Value *NotNull = new ICmpInst(*UnwindHandler, ICmpInst::ICMP_NE, BufPtr,
558                                 Constant::getNullValue(BufPtr->getType()),
559                                 "notnull");
560   BranchInst::Create(UnwindBlock, TermBlock, NotNull, UnwindHandler);
561
562   // Create the block to do the longjmp.
563   // Get a pointer to the jmpbuf and longjmp.
564   Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())),
565                    ConstantInt::get(Type::getInt32Ty(F.getContext()), 0) };
566   Idx[0] = GetElementPtrInst::Create(BufPtr, &Idx[0], &Idx[2], "JmpBuf",
567                                      UnwindBlock);
568   Idx[0] = new BitCastInst(Idx[0],
569              Type::getInt8PtrTy(F.getContext()),
570                            "tmp", UnwindBlock);
571   Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 1);
572   CallInst::Create(LongJmpFn, &Idx[0], &Idx[2], "", UnwindBlock);
573   new UnreachableInst(F.getContext(), UnwindBlock);
574
575   // Set up the term block ("throw without a catch").
576   new UnreachableInst(F.getContext(), TermBlock);
577
578   // Insert a call to abort()
579   CallInst::Create(AbortFn, "",
580                    TermBlock->getTerminator())->setTailCall();
581
582
583   // Replace all unwinds with a branch to the unwind handler.
584   for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
585     BranchInst::Create(UnwindHandler, Unwinds[i]);
586     Unwinds[i]->eraseFromParent();
587   }
588
589   // Finally, for any returns from this function, if this function contains an
590   // invoke, restore the old jmpbuf pointer to its input value.
591   if (OldJmpBufPtr) {
592     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
593       ReturnInst *R = Returns[i];
594
595       // Before the return, insert a copy from the saved value to the new value.
596       Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
597       new StoreInst(OldBuf, JBListHead, true, R);
598     }
599   }
600
601   return true;
602 }
603
604 bool LowerInvoke::runOnFunction(Function &F) {
605   if (useExpensiveEHSupport)
606     return insertExpensiveEHSupport(F);
607   else
608     return insertCheapEHSupport(F);
609 }