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 const PassInfo *llvm::LowerInvokePassID = X.getPassInfo();
75 // Public Interface To the LowerInvoke pass.
76 FunctionPass *llvm::createLowerInvokePass() { return new LowerInvoke(); }
78 // doInitialization - Make sure that there is a prototype for abort in the
80 bool LowerInvoke::doInitialization(Module &M) {
81 const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
83 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);
92 { // 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();
102 const Type *PtrJBList = PointerType::get(JBLinkTy);
104 // Now that we've done that, insert the jmpbuf list head global, unless it
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);
111 SetJmpFn = M.getOrInsertFunction("llvm.setjmp", Type::IntTy,
112 PointerType::get(JmpBufTy), 0);
113 LongJmpFn = M.getOrInsertFunction("llvm.longjmp", Type::VoidTy,
114 PointerType::get(JmpBufTy),
117 // The abort message for expensive EH support tells the user that the
118 // program 'unwound' without an 'invoke' instruction.
120 ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
121 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
122 AbortMessageInit = Msg;
124 GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
125 if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
129 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
131 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
135 // The abort message for cheap EH support tells the user that EH is not
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
141 AbortMessageInit = Msg;
143 GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
144 if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
148 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
150 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
154 // We need the 'write' and 'abort' functions for both models.
155 AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
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'
159 // we will use their prototype. We _do not_ want to insert another instance
160 // 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())
171 WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
172 VoidPtrTy, Type::IntTy, 0);
177 void LowerInvoke::writeAbortMessage(Instruction *IB) {
180 GlobalVariable *MsgGV = new GlobalVariable(AbortMessageInit->getType(),
182 GlobalValue::InternalLinkage,
183 AbortMessageInit, "abort.msg",
184 WriteFn->getParent());
185 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
187 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
190 // 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));
196 // If the actual declaration of write disagrees, insert casts as
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));
205 new CallInst(WriteFn, Args, "", IB);
209 bool LowerInvoke::insertCheapEHSupport(Function &F) {
210 bool Changed = false;
211 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
212 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
213 // 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);
220 // Insert an unconditional branch to the normal destination.
221 new BranchInst(II->getNormalDest(), II);
223 // Remove any PHI node entries from the exception destination.
224 II->getUnwindDest()->removePredecessor(BB);
226 // Remove the invoke instruction now.
227 BB->getInstList().erase(II);
229 ++NumLowered; Changed = true;
230 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
231 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
232 writeAbortMessage(UI);
234 // Insert a call to abort()
235 new CallInst(AbortFn, std::vector<Value*>(), "", UI);
237 // Insert a return instruction. This really should be a "barrier", as it
239 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
240 Constant::getNullValue(F.getReturnType()), UI);
242 // Remove the unwind instruction now.
243 BB->getInstList().erase(UI);
245 ++NumLowered; Changed = true;
250 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
251 bool Changed = false;
253 // If a function uses invoke, we have an alloca for the jump buffer.
254 AllocaInst *JmpBuf = 0;
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
259 BasicBlock *UnwindBlock = 0, *TermBlock = 0;
260 std::vector<LoadInst*> JBPtrs;
262 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
263 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
265 JmpBuf = new AllocaInst(JBLinkTy, 0, "jblink", F.begin()->begin());
267 // On the entry to the invoke, we must install our JmpBuf as the top of
269 LoadInst *OldEntry = new LoadInst(JBListHead, "oldehlist", II);
271 // Store this old value as our 'next' field, and store our alloca as the
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);
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);
285 // Compare the return value to zero.
286 Value *IsNormal = BinaryOperator::create(Instruction::SetEQ, SJRet,
287 Constant::getNullValue(SJRet->getType()),
289 // Create the receiver block if there is a critical edge to the normal
291 SplitCriticalEdge(II, 0, this);
292 Instruction *InsertLoc = II->getNormalDest()->begin();
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,
300 II->replaceAllUsesWith(NewCall);
302 // If we got this far, then no exception was thrown and we can pop our
304 new StoreInst(OldEntry, JBListHead, InsertLoc);
306 // Now we change the invoke into a branch instruction.
307 new BranchInst(II->getNormalDest(), II->getUnwindDest(), IsNormal, II);
309 // Remove the InvokeInst now.
310 BB->getInstList().erase(II);
311 ++NumLowered; Changed = true;
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);
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);
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()),
333 new BranchInst(UnwindBlock, TermBlock, NotNull, UI);
335 // Remember the loaded value so we can insert the PHI node as needed.
336 JBPtrs.push_back(Ptr);
338 // Remove the UnwindInst now.
339 BB->getInstList().erase(UI);
340 ++NumLowered; Changed = true;
343 // If an unwind instruction was inserted, we need to set up the Unwind and
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();
351 if (JBPtrs.size() == 1)
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());
362 // Now that we have a pointer to the whole record, remove the entry from the
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);
371 // Now that we popped the top of the JBList, get a pointer to the jmpbuf and
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);
378 // Now we set up the terminate block.
379 RI = TermBlock->getTerminator();
381 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
382 writeAbortMessage(RI);
384 // Insert a call to abort()
385 new CallInst(AbortFn, std::vector<Value*>(), "", RI);
391 bool LowerInvoke::runOnFunction(Function &F) {
392 if (ExpensiveEHSupport)
393 return insertExpensiveEHSupport(F);
395 return insertCheapEHSupport(F);