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