Only add the global variable with the abort message if an unwind actually
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 making the 'invoke' instruction really expensive.
22 // It basically inserts setjmp/longjmp calls to emulate the exception handling
23 // 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 //===----------------------------------------------------------------------===//
30
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Constants.h"
33 #include "llvm/DerivedTypes.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Module.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "Support/Statistic.h"
39 #include "Support/CommandLine.h"
40 #include <csetjmp>
41 using namespace llvm;
42
43 namespace {
44   Statistic<> NumLowered("lowerinvoke", "Number of invoke & unwinds replaced");
45   cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support", 
46  cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
47
48   class LowerInvoke : public FunctionPass {
49     // Used for both models.
50     Function *WriteFn;
51     Function *AbortFn;
52     Constant *AbortMessageInit;
53     Value *AbortMessage;
54     unsigned AbortMessageLength;
55
56     // Used for expensive EH support.
57     const Type *JBLinkTy;
58     GlobalVariable *JBListHead;
59     Function *SetJmpFn, *LongJmpFn;
60   public:
61     bool doInitialization(Module &M);
62     bool runOnFunction(Function &F);
63   private:
64     void writeAbortMessage(Instruction *IB);
65     bool insertCheapEHSupport(Function &F);
66     bool insertExpensiveEHSupport(Function &F);
67   };
68
69   RegisterOpt<LowerInvoke>
70   X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
71 }
72
73 // Public Interface To the LowerInvoke pass.
74 FunctionPass *llvm::createLowerInvokePass() { return new LowerInvoke(); }
75
76 // doInitialization - Make sure that there is a prototype for abort in the
77 // current module.
78 bool LowerInvoke::doInitialization(Module &M) {
79   const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
80   AbortMessage = 0;
81   if (ExpensiveEHSupport) {
82     // Insert a type for the linked list of jump buffers.  Unfortunately, we
83     // don't know the size of the target's setjmp buffer, so we make a guess.
84     // If this guess turns out to be too small, bad stuff could happen.
85     unsigned JmpBufSize = 200;  // PPC has 192 words
86     assert(sizeof(jmp_buf) <= JmpBufSize*sizeof(void*) &&
87        "LowerInvoke doesn't know about targets with jmp_buf size > 200 words!");
88     const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JmpBufSize);
89
90     { // The type is recursive, so use a type holder.
91       std::vector<const Type*> Elements;
92       OpaqueType *OT = OpaqueType::get();
93       Elements.push_back(PointerType::get(OT));
94       Elements.push_back(JmpBufTy);
95       PATypeHolder JBLType(StructType::get(Elements));
96       OT->refineAbstractTypeTo(JBLType.get());  // Complete the cycle.
97       JBLinkTy = JBLType.get();
98     }
99
100     const Type *PtrJBList = PointerType::get(JBLinkTy);
101
102     // Now that we've done that, insert the jmpbuf list head global, unless it
103     // already exists.
104     if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList)))
105       JBListHead = new GlobalVariable(PtrJBList, false,
106                                       GlobalValue::LinkOnceLinkage,
107                                       Constant::getNullValue(PtrJBList),
108                                       "llvm.sjljeh.jblist", &M);
109     SetJmpFn = M.getOrInsertFunction("setjmp", Type::IntTy,
110                                      PointerType::get(JmpBufTy), 0);
111     LongJmpFn = M.getOrInsertFunction("longjmp", Type::VoidTy,
112                                       PointerType::get(JmpBufTy),
113                                       Type::IntTy, 0);
114     
115     // The abort message for expensive EH support tells the user that the
116     // program 'unwound' without an 'invoke' instruction.
117     Constant *Msg =
118       ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
119     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
120     AbortMessageInit = Msg;
121   
122     GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
123     if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
124       MsgGV = 0;
125
126     if (MsgGV) {
127       std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
128       AbortMessage = 
129         ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
130     }
131
132   } else {
133     // The abort message for cheap EH support tells the user that EH is not
134     // enabled.
135     Constant *Msg =
136       ConstantArray::get("Exception handler needed, but not enabled.  Recompile"
137                          " program with -enable-correct-eh-support.\n");
138     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
139     AbortMessageInit = Msg;
140   
141     GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
142     if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
143       MsgGV = 0;
144
145     if (MsgGV) {
146       std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
147       AbortMessage =
148         ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
149     }
150   }
151
152   // We need the 'write' and 'abort' functions for both models.
153   AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
154
155   // Unfortunately, 'write' can end up being prototyped in several different
156   // ways.  If the user defines a three (or more) operand function named 'write'
157   // we will use their prototype.  We _do not_ want to insert another instance
158   // of a write prototype, because we don't know that the funcresolve pass will
159   // run after us.  If there is a definition of a write function, but it's not
160   // suitable for our uses, we just don't emit write calls.  If there is no
161   // write prototype at all, we just add one.
162   if (Function *WF = M.getNamedFunction("write")) {
163     if (WF->getFunctionType()->getNumParams() > 3 ||
164         WF->getFunctionType()->isVarArg())
165       WriteFn = WF;
166     else
167       WriteFn = 0;
168   } else {
169     WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
170                                     VoidPtrTy, Type::IntTy, 0);
171   }
172   return true;
173 }
174
175 void LowerInvoke::writeAbortMessage(Instruction *IB) {
176   if (WriteFn) {
177     if (!AbortMessage) {
178       GlobalVariable *MsgGV = new GlobalVariable(AbortMessageInit->getType(),
179                                                  true,
180                                                  GlobalValue::InternalLinkage,
181                                                  AbortMessageInit, "abort.msg",
182                                                  WriteFn->getParent());
183       std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
184       AbortMessage = 
185         ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
186     }
187
188     // These are the arguments we WANT...
189     std::vector<Value*> Args;
190     Args.push_back(ConstantInt::get(Type::IntTy, 2));
191     Args.push_back(AbortMessage);
192     Args.push_back(ConstantInt::get(Type::IntTy, AbortMessageLength));
193
194     // If the actual declaration of write disagrees, insert casts as
195     // appropriate.
196     const FunctionType *FT = WriteFn->getFunctionType();
197     unsigned NumArgs = FT->getNumParams();
198     for (unsigned i = 0; i != 3; ++i)
199       if (i < NumArgs && FT->getParamType(i) != Args[i]->getType())
200         Args[i] = ConstantExpr::getCast(cast<Constant>(Args[i]), 
201                                         FT->getParamType(i));
202
203     new CallInst(WriteFn, Args, "", IB);
204   }
205 }
206
207 bool LowerInvoke::insertCheapEHSupport(Function &F) {
208   bool Changed = false;
209   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
210     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
211       // Insert a normal call instruction...
212       std::string Name = II->getName(); II->setName("");
213       Value *NewCall = new CallInst(II->getCalledValue(),
214                                     std::vector<Value*>(II->op_begin()+3,
215                                                         II->op_end()), Name,II);
216       II->replaceAllUsesWith(NewCall);
217       
218       // Insert an unconditional branch to the normal destination.
219       new BranchInst(II->getNormalDest(), II);
220
221       // Remove any PHI node entries from the exception destination.
222       II->getUnwindDest()->removePredecessor(BB);
223
224       // Remove the invoke instruction now.
225       BB->getInstList().erase(II);
226
227       ++NumLowered; Changed = true;
228     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
229       // Insert a new call to write(2, AbortMessage, AbortMessageLength);
230       writeAbortMessage(UI);
231
232       // Insert a call to abort()
233       new CallInst(AbortFn, std::vector<Value*>(), "", UI);
234
235       // Insert a return instruction.  This really should be a "barrier", as it
236       // is unreachable.
237       new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
238                             Constant::getNullValue(F.getReturnType()), UI);
239
240       // Remove the unwind instruction now.
241       BB->getInstList().erase(UI);
242
243       ++NumLowered; Changed = true;
244     }
245   return Changed;
246 }
247
248 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
249   bool Changed = false;
250
251   // If a function uses invoke, we have an alloca for the jump buffer.
252   AllocaInst *JmpBuf = 0;
253
254   // If this function contains an unwind instruction, two blocks get added: one
255   // to actually perform the longjmp, and one to terminate the program if there
256   // is no handler.
257   BasicBlock *UnwindBlock = 0, *TermBlock = 0;
258   std::vector<LoadInst*> JBPtrs;
259
260   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
261     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
262       if (JmpBuf == 0)
263         JmpBuf = new AllocaInst(JBLinkTy, 0, "jblink", F.begin()->begin());
264
265       // On the entry to the invoke, we must install our JmpBuf as the top of
266       // the stack.
267       LoadInst *OldEntry = new LoadInst(JBListHead, "oldehlist", II);
268
269       // Store this old value as our 'next' field, and store our alloca as the
270       // current jblist.
271       std::vector<Value*> Idx;
272       Idx.push_back(Constant::getNullValue(Type::LongTy));
273       Idx.push_back(ConstantUInt::get(Type::UByteTy, 0));
274       Value *NextFieldPtr = new GetElementPtrInst(JmpBuf, Idx, "NextField", II);
275       new StoreInst(OldEntry, NextFieldPtr, II);
276       new StoreInst(JmpBuf, JBListHead, II);
277       
278       // Call setjmp, passing in the address of the jmpbuffer.
279       Idx[1] = ConstantUInt::get(Type::UByteTy, 1);
280       Value *JmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "TheJmpBuf", II);
281       Value *SJRet = new CallInst(SetJmpFn, JmpBufPtr, "sjret", II);
282
283       // Compare the return value to zero.
284       Value *IsNormal = BinaryOperator::create(Instruction::SetEQ, SJRet,
285                                        Constant::getNullValue(SJRet->getType()),
286                                                "notunwind", II);
287       // Create the receiver block if there is a critical edge to the normal
288       // destination.
289       SplitCriticalEdge(II, 0, this);
290       Instruction *InsertLoc = II->getNormalDest()->begin();
291       
292       // Insert a normal call instruction on the normal execution path.
293       std::string Name = II->getName(); II->setName("");
294       Value *NewCall = new CallInst(II->getCalledValue(),
295                                     std::vector<Value*>(II->op_begin()+3,
296                                                         II->op_end()), Name,
297                                     InsertLoc);
298       II->replaceAllUsesWith(NewCall);
299       
300       // If we got this far, then no exception was thrown and we can pop our
301       // jmpbuf entry off.
302       new StoreInst(OldEntry, JBListHead, InsertLoc);
303
304       // Now we change the invoke into a branch instruction.
305       new BranchInst(II->getNormalDest(), II->getUnwindDest(), IsNormal, II);
306
307       // Remove the InvokeInst now.
308       BB->getInstList().erase(II);
309       ++NumLowered; Changed = true;      
310       
311     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
312       if (UnwindBlock == 0) {
313         // Create two new blocks, the unwind block and the terminate block.  Add
314         // them at the end of the function because they are not hot.
315         UnwindBlock = new BasicBlock("unwind", &F);
316         TermBlock = new BasicBlock("unwinderror", &F);
317
318         // Insert return instructions.  These really should be "barrier"s, as
319         // they are unreachable.
320         new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
321                        Constant::getNullValue(F.getReturnType()), UnwindBlock);
322         new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
323                        Constant::getNullValue(F.getReturnType()), TermBlock);
324       }
325
326       // Load the JBList, if it's null, then there was no catch!
327       LoadInst *Ptr = new LoadInst(JBListHead, "ehlist", UI);
328       Value *NotNull = BinaryOperator::create(Instruction::SetNE, Ptr,
329                                         Constant::getNullValue(Ptr->getType()),
330                                               "notnull", UI);
331       new BranchInst(UnwindBlock, TermBlock, NotNull, UI);
332
333       // Remember the loaded value so we can insert the PHI node as needed.
334       JBPtrs.push_back(Ptr);
335
336       // Remove the UnwindInst now.
337       BB->getInstList().erase(UI);
338       ++NumLowered; Changed = true;      
339     }
340
341   // If an unwind instruction was inserted, we need to set up the Unwind and
342   // term blocks.
343   if (UnwindBlock) {
344     // In the unwind block, we know that the pointer coming in on the JBPtrs
345     // list are non-null.
346     Instruction *RI = UnwindBlock->getTerminator();
347
348     Value *RecPtr;
349     if (JBPtrs.size() == 1)
350       RecPtr = JBPtrs[0];
351     else {
352       // If there is more than one unwind in this function, make a PHI node to
353       // merge in all of the loaded values.
354       PHINode *PN = new PHINode(JBPtrs[0]->getType(), "jbptrs", RI);
355       for (unsigned i = 0, e = JBPtrs.size(); i != e; ++i)
356         PN->addIncoming(JBPtrs[i], JBPtrs[i]->getParent());
357       RecPtr = PN;
358     }
359
360     // Now that we have a pointer to the whole record, remove the entry from the
361     // JBList.
362     std::vector<Value*> Idx;
363     Idx.push_back(Constant::getNullValue(Type::LongTy));
364     Idx.push_back(ConstantUInt::get(Type::UByteTy, 0));
365     Value *NextFieldPtr = new GetElementPtrInst(RecPtr, Idx, "NextField", RI);
366     Value *NextRec = new LoadInst(NextFieldPtr, "NextRecord", RI);
367     new StoreInst(NextRec, JBListHead, RI);
368
369     // Now that we popped the top of the JBList, get a pointer to the jmpbuf and
370     // longjmp.
371     Idx[1] = ConstantUInt::get(Type::UByteTy, 1);
372     Idx[0] = new GetElementPtrInst(RecPtr, Idx, "JmpBuf", RI);
373     Idx[1] = ConstantInt::get(Type::IntTy, 1);
374     new CallInst(LongJmpFn, Idx, "", RI);
375
376     // Now we set up the terminate block.
377     RI = TermBlock->getTerminator();
378     
379     // Insert a new call to write(2, AbortMessage, AbortMessageLength);
380     writeAbortMessage(RI);
381
382     // Insert a call to abort()
383     new CallInst(AbortFn, std::vector<Value*>(), "", RI);
384   }
385
386   return Changed;
387 }
388
389 bool LowerInvoke::runOnFunction(Function &F) {
390   if (ExpensiveEHSupport)
391     return insertExpensiveEHSupport(F);
392   else
393     return insertCheapEHSupport(F);
394 }