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