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