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