blob: 24033f4876aee67eafb19a5e98f0ab825b2b197a [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 Lattner5cf39332004-03-01 01:12:13 +000045 cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
Chris Lattner108cadc2004-02-08 19:53:56 +000046 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 Lattner37d46f42004-02-09 22:48:47 +000052 Constant *AbortMessageInit;
Chris Lattner108cadc2004-02-08 19:53:56 +000053 Value *AbortMessage;
54 unsigned AbortMessageLength;
55
56 // Used for expensive EH support.
57 const Type *JBLinkTy;
58 GlobalVariable *JBListHead;
59 Function *SetJmpFn, *LongJmpFn;
Chris Lattnera43b8f42003-10-05 19:14:42 +000060 public:
61 bool doInitialization(Module &M);
62 bool runOnFunction(Function &F);
Chris Lattner108cadc2004-02-08 19:53:56 +000063 private:
Chris Lattner3b7f6b22004-02-08 22:14:44 +000064 void writeAbortMessage(Instruction *IB);
Chris Lattner108cadc2004-02-08 19:53:56 +000065 bool insertCheapEHSupport(Function &F);
66 bool insertExpensiveEHSupport(Function &F);
Chris Lattnera43b8f42003-10-05 19:14:42 +000067 };
68
69 RegisterOpt<LowerInvoke>
70 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
71}
72
Chris Lattner7cbb22a2004-02-13 16:16:16 +000073const PassInfo *llvm::LowerInvokePassID = X.getPassInfo();
74
Brian Gaeke960707c2003-11-11 22:41:34 +000075// Public Interface To the LowerInvoke pass.
Chris Lattner7e5bd592003-12-10 20:22:42 +000076FunctionPass *llvm::createLowerInvokePass() { return new LowerInvoke(); }
Chris Lattnera43b8f42003-10-05 19:14:42 +000077
78// doInitialization - Make sure that there is a prototype for abort in the
79// current module.
80bool LowerInvoke::doInitialization(Module &M) {
Chris Lattner108cadc2004-02-08 19:53:56 +000081 const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
Chris Lattner37d46f42004-02-09 22:48:47 +000082 AbortMessage = 0;
Chris Lattner108cadc2004-02-08 19:53:56 +000083 if (ExpensiveEHSupport) {
84 // Insert a type for the linked list of jump buffers. Unfortunately, we
85 // don't know the size of the target's setjmp buffer, so we make a guess.
86 // If this guess turns out to be too small, bad stuff could happen.
87 unsigned JmpBufSize = 200; // PPC has 192 words
88 assert(sizeof(jmp_buf) <= JmpBufSize*sizeof(void*) &&
89 "LowerInvoke doesn't know about targets with jmp_buf size > 200 words!");
90 const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JmpBufSize);
Chris Lattner476488e2004-02-08 07:30:29 +000091
Chris Lattner108cadc2004-02-08 19:53:56 +000092 { // The type is recursive, so use a type holder.
93 std::vector<const Type*> Elements;
94 OpaqueType *OT = OpaqueType::get();
95 Elements.push_back(PointerType::get(OT));
96 Elements.push_back(JmpBufTy);
97 PATypeHolder JBLType(StructType::get(Elements));
98 OT->refineAbstractTypeTo(JBLType.get()); // Complete the cycle.
99 JBLinkTy = JBLType.get();
100 }
101
102 const Type *PtrJBList = PointerType::get(JBLinkTy);
103
104 // Now that we've done that, insert the jmpbuf list head global, unless it
105 // already exists.
106 if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList)))
107 JBListHead = new GlobalVariable(PtrJBList, false,
108 GlobalValue::LinkOnceLinkage,
109 Constant::getNullValue(PtrJBList),
110 "llvm.sjljeh.jblist", &M);
Chris Lattnerd85e0612004-02-15 22:24:27 +0000111 SetJmpFn = M.getOrInsertFunction("llvm.setjmp", Type::IntTy,
Chris Lattner108cadc2004-02-08 19:53:56 +0000112 PointerType::get(JmpBufTy), 0);
Chris Lattnerd85e0612004-02-15 22:24:27 +0000113 LongJmpFn = M.getOrInsertFunction("llvm.longjmp", Type::VoidTy,
Chris Lattner108cadc2004-02-08 19:53:56 +0000114 PointerType::get(JmpBufTy),
115 Type::IntTy, 0);
116
117 // The abort message for expensive EH support tells the user that the
118 // program 'unwound' without an 'invoke' instruction.
119 Constant *Msg =
120 ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
121 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
Chris Lattner37d46f42004-02-09 22:48:47 +0000122 AbortMessageInit = Msg;
Chris Lattner108cadc2004-02-08 19:53:56 +0000123
124 GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
125 if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
126 MsgGV = 0;
Chris Lattner37d46f42004-02-09 22:48:47 +0000127
128 if (MsgGV) {
129 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
130 AbortMessage =
131 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
132 }
Chris Lattner108cadc2004-02-08 19:53:56 +0000133
134 } else {
135 // The abort message for cheap EH support tells the user that EH is not
136 // enabled.
137 Constant *Msg =
138 ConstantArray::get("Exception handler needed, but not enabled. Recompile"
139 " program with -enable-correct-eh-support.\n");
140 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
Chris Lattner37d46f42004-02-09 22:48:47 +0000141 AbortMessageInit = Msg;
Chris Lattner108cadc2004-02-08 19:53:56 +0000142
143 GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
144 if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
145 MsgGV = 0;
146
Chris Lattner37d46f42004-02-09 22:48:47 +0000147 if (MsgGV) {
148 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
149 AbortMessage =
150 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
151 }
Chris Lattner108cadc2004-02-08 19:53:56 +0000152 }
153
154 // We need the 'write' and 'abort' functions for both models.
Chris Lattner108cadc2004-02-08 19:53:56 +0000155 AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000156
157 // Unfortunately, 'write' can end up being prototyped in several different
158 // ways. If the user defines a three (or more) operand function named 'write'
Misha Brukman3480e932004-02-08 22:27:33 +0000159 // we will use their prototype. We _do not_ want to insert another instance
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000160 // of a write prototype, because we don't know that the funcresolve pass will
161 // run after us. If there is a definition of a write function, but it's not
162 // suitable for our uses, we just don't emit write calls. If there is no
163 // write prototype at all, we just add one.
164 if (Function *WF = M.getNamedFunction("write")) {
165 if (WF->getFunctionType()->getNumParams() > 3 ||
166 WF->getFunctionType()->isVarArg())
167 WriteFn = WF;
168 else
169 WriteFn = 0;
170 } else {
171 WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
172 VoidPtrTy, Type::IntTy, 0);
173 }
Chris Lattnera43b8f42003-10-05 19:14:42 +0000174 return true;
175}
176
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000177void LowerInvoke::writeAbortMessage(Instruction *IB) {
178 if (WriteFn) {
Chris Lattner37d46f42004-02-09 22:48:47 +0000179 if (!AbortMessage) {
180 GlobalVariable *MsgGV = new GlobalVariable(AbortMessageInit->getType(),
181 true,
182 GlobalValue::InternalLinkage,
183 AbortMessageInit, "abort.msg",
184 WriteFn->getParent());
185 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
186 AbortMessage =
187 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
188 }
189
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000190 // These are the arguments we WANT...
191 std::vector<Value*> Args;
192 Args.push_back(ConstantInt::get(Type::IntTy, 2));
193 Args.push_back(AbortMessage);
194 Args.push_back(ConstantInt::get(Type::IntTy, AbortMessageLength));
195
196 // If the actual declaration of write disagrees, insert casts as
197 // appropriate.
198 const FunctionType *FT = WriteFn->getFunctionType();
199 unsigned NumArgs = FT->getNumParams();
200 for (unsigned i = 0; i != 3; ++i)
201 if (i < NumArgs && FT->getParamType(i) != Args[i]->getType())
202 Args[i] = ConstantExpr::getCast(cast<Constant>(Args[i]),
203 FT->getParamType(i));
204
205 new CallInst(WriteFn, Args, "", IB);
206 }
207}
208
Chris Lattner108cadc2004-02-08 19:53:56 +0000209bool LowerInvoke::insertCheapEHSupport(Function &F) {
Chris Lattnera43b8f42003-10-05 19:14:42 +0000210 bool Changed = false;
Chris Lattner7e5bd592003-12-10 20:22:42 +0000211 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
212 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Chris Lattnera43b8f42003-10-05 19:14:42 +0000213 // Insert a normal call instruction...
214 std::string Name = II->getName(); II->setName("");
215 Value *NewCall = new CallInst(II->getCalledValue(),
216 std::vector<Value*>(II->op_begin()+3,
217 II->op_end()), Name,II);
218 II->replaceAllUsesWith(NewCall);
219
Chris Lattner7e5bd592003-12-10 20:22:42 +0000220 // Insert an unconditional branch to the normal destination.
Chris Lattnera43b8f42003-10-05 19:14:42 +0000221 new BranchInst(II->getNormalDest(), II);
222
Chris Lattner7e5bd592003-12-10 20:22:42 +0000223 // Remove any PHI node entries from the exception destination.
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000224 II->getUnwindDest()->removePredecessor(BB);
Chris Lattner7e5bd592003-12-10 20:22:42 +0000225
Chris Lattnera43b8f42003-10-05 19:14:42 +0000226 // Remove the invoke instruction now.
Chris Lattner7e5bd592003-12-10 20:22:42 +0000227 BB->getInstList().erase(II);
Chris Lattnera43b8f42003-10-05 19:14:42 +0000228
229 ++NumLowered; Changed = true;
Chris Lattner7e5bd592003-12-10 20:22:42 +0000230 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattner476488e2004-02-08 07:30:29 +0000231 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000232 writeAbortMessage(UI);
Chris Lattner476488e2004-02-08 07:30:29 +0000233
Chris Lattnera43b8f42003-10-05 19:14:42 +0000234 // Insert a call to abort()
235 new CallInst(AbortFn, std::vector<Value*>(), "", UI);
236
Chris Lattner108cadc2004-02-08 19:53:56 +0000237 // Insert a return instruction. This really should be a "barrier", as it
238 // is unreachable.
Chris Lattnera43b8f42003-10-05 19:14:42 +0000239 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
240 Constant::getNullValue(F.getReturnType()), UI);
241
242 // Remove the unwind instruction now.
Chris Lattner7e5bd592003-12-10 20:22:42 +0000243 BB->getInstList().erase(UI);
Chris Lattnera43b8f42003-10-05 19:14:42 +0000244
245 ++NumLowered; Changed = true;
246 }
247 return Changed;
248}
Chris Lattner108cadc2004-02-08 19:53:56 +0000249
250bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
251 bool Changed = false;
252
253 // If a function uses invoke, we have an alloca for the jump buffer.
254 AllocaInst *JmpBuf = 0;
255
256 // If this function contains an unwind instruction, two blocks get added: one
257 // to actually perform the longjmp, and one to terminate the program if there
258 // is no handler.
259 BasicBlock *UnwindBlock = 0, *TermBlock = 0;
260 std::vector<LoadInst*> JBPtrs;
261
262 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
263 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
264 if (JmpBuf == 0)
265 JmpBuf = new AllocaInst(JBLinkTy, 0, "jblink", F.begin()->begin());
266
267 // On the entry to the invoke, we must install our JmpBuf as the top of
268 // the stack.
269 LoadInst *OldEntry = new LoadInst(JBListHead, "oldehlist", II);
270
271 // Store this old value as our 'next' field, and store our alloca as the
272 // current jblist.
273 std::vector<Value*> Idx;
274 Idx.push_back(Constant::getNullValue(Type::LongTy));
275 Idx.push_back(ConstantUInt::get(Type::UByteTy, 0));
276 Value *NextFieldPtr = new GetElementPtrInst(JmpBuf, Idx, "NextField", II);
277 new StoreInst(OldEntry, NextFieldPtr, II);
278 new StoreInst(JmpBuf, JBListHead, II);
279
280 // Call setjmp, passing in the address of the jmpbuffer.
281 Idx[1] = ConstantUInt::get(Type::UByteTy, 1);
282 Value *JmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "TheJmpBuf", II);
283 Value *SJRet = new CallInst(SetJmpFn, JmpBufPtr, "sjret", II);
284
285 // Compare the return value to zero.
286 Value *IsNormal = BinaryOperator::create(Instruction::SetEQ, SJRet,
287 Constant::getNullValue(SJRet->getType()),
288 "notunwind", II);
289 // Create the receiver block if there is a critical edge to the normal
290 // destination.
291 SplitCriticalEdge(II, 0, this);
292 Instruction *InsertLoc = II->getNormalDest()->begin();
293
294 // Insert a normal call instruction on the normal execution path.
295 std::string Name = II->getName(); II->setName("");
296 Value *NewCall = new CallInst(II->getCalledValue(),
297 std::vector<Value*>(II->op_begin()+3,
298 II->op_end()), Name,
299 InsertLoc);
300 II->replaceAllUsesWith(NewCall);
301
302 // If we got this far, then no exception was thrown and we can pop our
303 // jmpbuf entry off.
304 new StoreInst(OldEntry, JBListHead, InsertLoc);
305
306 // Now we change the invoke into a branch instruction.
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000307 new BranchInst(II->getNormalDest(), II->getUnwindDest(), IsNormal, II);
Chris Lattner108cadc2004-02-08 19:53:56 +0000308
309 // Remove the InvokeInst now.
310 BB->getInstList().erase(II);
311 ++NumLowered; Changed = true;
312
313 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
314 if (UnwindBlock == 0) {
315 // Create two new blocks, the unwind block and the terminate block. Add
316 // them at the end of the function because they are not hot.
317 UnwindBlock = new BasicBlock("unwind", &F);
318 TermBlock = new BasicBlock("unwinderror", &F);
319
320 // Insert return instructions. These really should be "barrier"s, as
321 // they are unreachable.
322 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
323 Constant::getNullValue(F.getReturnType()), UnwindBlock);
324 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
325 Constant::getNullValue(F.getReturnType()), TermBlock);
326 }
327
328 // Load the JBList, if it's null, then there was no catch!
329 LoadInst *Ptr = new LoadInst(JBListHead, "ehlist", UI);
330 Value *NotNull = BinaryOperator::create(Instruction::SetNE, Ptr,
331 Constant::getNullValue(Ptr->getType()),
332 "notnull", UI);
333 new BranchInst(UnwindBlock, TermBlock, NotNull, UI);
334
335 // Remember the loaded value so we can insert the PHI node as needed.
336 JBPtrs.push_back(Ptr);
337
338 // Remove the UnwindInst now.
339 BB->getInstList().erase(UI);
340 ++NumLowered; Changed = true;
341 }
342
343 // If an unwind instruction was inserted, we need to set up the Unwind and
344 // term blocks.
345 if (UnwindBlock) {
346 // In the unwind block, we know that the pointer coming in on the JBPtrs
347 // list are non-null.
348 Instruction *RI = UnwindBlock->getTerminator();
349
350 Value *RecPtr;
351 if (JBPtrs.size() == 1)
352 RecPtr = JBPtrs[0];
353 else {
354 // If there is more than one unwind in this function, make a PHI node to
355 // merge in all of the loaded values.
356 PHINode *PN = new PHINode(JBPtrs[0]->getType(), "jbptrs", RI);
357 for (unsigned i = 0, e = JBPtrs.size(); i != e; ++i)
358 PN->addIncoming(JBPtrs[i], JBPtrs[i]->getParent());
359 RecPtr = PN;
360 }
361
362 // Now that we have a pointer to the whole record, remove the entry from the
363 // JBList.
364 std::vector<Value*> Idx;
365 Idx.push_back(Constant::getNullValue(Type::LongTy));
366 Idx.push_back(ConstantUInt::get(Type::UByteTy, 0));
367 Value *NextFieldPtr = new GetElementPtrInst(RecPtr, Idx, "NextField", RI);
368 Value *NextRec = new LoadInst(NextFieldPtr, "NextRecord", RI);
369 new StoreInst(NextRec, JBListHead, RI);
370
371 // Now that we popped the top of the JBList, get a pointer to the jmpbuf and
372 // longjmp.
373 Idx[1] = ConstantUInt::get(Type::UByteTy, 1);
374 Idx[0] = new GetElementPtrInst(RecPtr, Idx, "JmpBuf", RI);
375 Idx[1] = ConstantInt::get(Type::IntTy, 1);
376 new CallInst(LongJmpFn, Idx, "", RI);
377
378 // Now we set up the terminate block.
379 RI = TermBlock->getTerminator();
380
381 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000382 writeAbortMessage(RI);
383
Chris Lattner108cadc2004-02-08 19:53:56 +0000384 // Insert a call to abort()
385 new CallInst(AbortFn, std::vector<Value*>(), "", RI);
386 }
387
388 return Changed;
389}
390
391bool LowerInvoke::runOnFunction(Function &F) {
392 if (ExpensiveEHSupport)
393 return insertExpensiveEHSupport(F);
394 else
395 return insertCheapEHSupport(F);
396}