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