1 //===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
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.
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
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
29 //===----------------------------------------------------------------------===//
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"
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"));
48 class LowerInvoke : public FunctionPass {
49 // Used for both models.
52 Constant *AbortMessageInit;
54 unsigned AbortMessageLength;
56 // Used for expensive EH support.
58 GlobalVariable *JBListHead;
59 Function *SetJmpFn, *LongJmpFn;
61 bool doInitialization(Module &M);
62 bool runOnFunction(Function &F);
64 void writeAbortMessage(Instruction *IB);
65 bool insertCheapEHSupport(Function &F);
66 bool insertExpensiveEHSupport(Function &F);
69 RegisterOpt<LowerInvoke>
70 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
73 // Public Interface To the LowerInvoke pass.
74 FunctionPass *llvm::createLowerInvokePass() { return new LowerInvoke(); }
76 // doInitialization - Make sure that there is a prototype for abort in the
78 bool LowerInvoke::doInitialization(Module &M) {
79 const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
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);
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();
100 const Type *PtrJBList = PointerType::get(JBLinkTy);
102 // Now that we've done that, insert the jmpbuf list head global, unless it
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),
115 // The abort message for expensive EH support tells the user that the
116 // program 'unwound' without an 'invoke' instruction.
118 ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
119 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
120 AbortMessageInit = Msg;
122 GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
123 if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
127 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
129 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
133 // The abort message for cheap EH support tells the user that EH is not
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;
141 GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
142 if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
146 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
148 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
152 // We need the 'write' and 'abort' functions for both models.
153 AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
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())
169 WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
170 VoidPtrTy, Type::IntTy, 0);
175 void LowerInvoke::writeAbortMessage(Instruction *IB) {
178 GlobalVariable *MsgGV = new GlobalVariable(AbortMessageInit->getType(),
180 GlobalValue::InternalLinkage,
181 AbortMessageInit, "abort.msg",
182 WriteFn->getParent());
183 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
185 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
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));
194 // If the actual declaration of write disagrees, insert casts as
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));
203 new CallInst(WriteFn, Args, "", IB);
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);
218 // Insert an unconditional branch to the normal destination.
219 new BranchInst(II->getNormalDest(), II);
221 // Remove any PHI node entries from the exception destination.
222 II->getUnwindDest()->removePredecessor(BB);
224 // Remove the invoke instruction now.
225 BB->getInstList().erase(II);
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);
232 // Insert a call to abort()
233 new CallInst(AbortFn, std::vector<Value*>(), "", UI);
235 // Insert a return instruction. This really should be a "barrier", as it
237 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
238 Constant::getNullValue(F.getReturnType()), UI);
240 // Remove the unwind instruction now.
241 BB->getInstList().erase(UI);
243 ++NumLowered; Changed = true;
248 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
249 bool Changed = false;
251 // If a function uses invoke, we have an alloca for the jump buffer.
252 AllocaInst *JmpBuf = 0;
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
257 BasicBlock *UnwindBlock = 0, *TermBlock = 0;
258 std::vector<LoadInst*> JBPtrs;
260 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
261 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
263 JmpBuf = new AllocaInst(JBLinkTy, 0, "jblink", F.begin()->begin());
265 // On the entry to the invoke, we must install our JmpBuf as the top of
267 LoadInst *OldEntry = new LoadInst(JBListHead, "oldehlist", II);
269 // Store this old value as our 'next' field, and store our alloca as the
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);
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);
283 // Compare the return value to zero.
284 Value *IsNormal = BinaryOperator::create(Instruction::SetEQ, SJRet,
285 Constant::getNullValue(SJRet->getType()),
287 // Create the receiver block if there is a critical edge to the normal
289 SplitCriticalEdge(II, 0, this);
290 Instruction *InsertLoc = II->getNormalDest()->begin();
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,
298 II->replaceAllUsesWith(NewCall);
300 // If we got this far, then no exception was thrown and we can pop our
302 new StoreInst(OldEntry, JBListHead, InsertLoc);
304 // Now we change the invoke into a branch instruction.
305 new BranchInst(II->getNormalDest(), II->getUnwindDest(), IsNormal, II);
307 // Remove the InvokeInst now.
308 BB->getInstList().erase(II);
309 ++NumLowered; Changed = true;
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);
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);
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()),
331 new BranchInst(UnwindBlock, TermBlock, NotNull, UI);
333 // Remember the loaded value so we can insert the PHI node as needed.
334 JBPtrs.push_back(Ptr);
336 // Remove the UnwindInst now.
337 BB->getInstList().erase(UI);
338 ++NumLowered; Changed = true;
341 // If an unwind instruction was inserted, we need to set up the Unwind and
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();
349 if (JBPtrs.size() == 1)
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());
360 // Now that we have a pointer to the whole record, remove the entry from the
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);
369 // Now that we popped the top of the JBList, get a pointer to the jmpbuf and
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);
376 // Now we set up the terminate block.
377 RI = TermBlock->getTerminator();
379 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
380 writeAbortMessage(RI);
382 // Insert a call to abort()
383 new CallInst(AbortFn, std::vector<Value*>(), "", RI);
389 bool LowerInvoke::runOnFunction(Function &F) {
390 if (ExpensiveEHSupport)
391 return insertExpensiveEHSupport(F);
393 return insertCheapEHSupport(F);