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.
53 unsigned AbortMessageLength;
55 // Used for expensive EH support.
57 GlobalVariable *JBListHead;
58 Function *SetJmpFn, *LongJmpFn;
60 bool doInitialization(Module &M);
61 bool runOnFunction(Function &F);
63 bool insertCheapEHSupport(Function &F);
64 bool insertExpensiveEHSupport(Function &F);
67 RegisterOpt<LowerInvoke>
68 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
71 // Public Interface To the LowerInvoke pass.
72 FunctionPass *llvm::createLowerInvokePass() { return new LowerInvoke(); }
74 // doInitialization - Make sure that there is a prototype for abort in the
76 bool LowerInvoke::doInitialization(Module &M) {
77 const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
78 if (ExpensiveEHSupport) {
79 // Insert a type for the linked list of jump buffers. Unfortunately, we
80 // don't know the size of the target's setjmp buffer, so we make a guess.
81 // If this guess turns out to be too small, bad stuff could happen.
82 unsigned JmpBufSize = 200; // PPC has 192 words
83 assert(sizeof(jmp_buf) <= JmpBufSize*sizeof(void*) &&
84 "LowerInvoke doesn't know about targets with jmp_buf size > 200 words!");
85 const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JmpBufSize);
87 { // The type is recursive, so use a type holder.
88 std::vector<const Type*> Elements;
89 OpaqueType *OT = OpaqueType::get();
90 Elements.push_back(PointerType::get(OT));
91 Elements.push_back(JmpBufTy);
92 PATypeHolder JBLType(StructType::get(Elements));
93 OT->refineAbstractTypeTo(JBLType.get()); // Complete the cycle.
94 JBLinkTy = JBLType.get();
97 const Type *PtrJBList = PointerType::get(JBLinkTy);
99 // Now that we've done that, insert the jmpbuf list head global, unless it
101 if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList)))
102 JBListHead = new GlobalVariable(PtrJBList, false,
103 GlobalValue::LinkOnceLinkage,
104 Constant::getNullValue(PtrJBList),
105 "llvm.sjljeh.jblist", &M);
106 SetJmpFn = M.getOrInsertFunction("setjmp", Type::IntTy,
107 PointerType::get(JmpBufTy), 0);
108 LongJmpFn = M.getOrInsertFunction("longjmp", Type::VoidTy,
109 PointerType::get(JmpBufTy),
112 // The abort message for expensive EH support tells the user that the
113 // program 'unwound' without an 'invoke' instruction.
115 ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
116 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
118 GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
119 if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
122 MsgGV = new GlobalVariable(Msg->getType(), true,
123 GlobalValue::InternalLinkage,
124 Msg, "abort.msg", &M);
125 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
127 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
130 // The abort message for cheap EH support tells the user that EH is not
133 ConstantArray::get("Exception handler needed, but not enabled. Recompile"
134 " program with -enable-correct-eh-support.\n");
135 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
137 GlobalVariable *MsgGV = M.getGlobalVariable("abort.msg", Msg->getType());
138 if (MsgGV && (!MsgGV->hasInitializer() || MsgGV->getInitializer() != Msg))
142 MsgGV = new GlobalVariable(Msg->getType(), true,
143 GlobalValue::InternalLinkage,
144 Msg, "abort.msg", &M);
145 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::LongTy));
147 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(MsgGV), GEPIdx);
150 // We need the 'write' and 'abort' functions for both models.
151 WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
152 VoidPtrTy, Type::IntTy, 0);
153 AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
157 bool LowerInvoke::insertCheapEHSupport(Function &F) {
158 bool Changed = false;
159 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
160 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
161 // Insert a normal call instruction...
162 std::string Name = II->getName(); II->setName("");
163 Value *NewCall = new CallInst(II->getCalledValue(),
164 std::vector<Value*>(II->op_begin()+3,
165 II->op_end()), Name,II);
166 II->replaceAllUsesWith(NewCall);
168 // Insert an unconditional branch to the normal destination.
169 new BranchInst(II->getNormalDest(), II);
171 // Remove any PHI node entries from the exception destination.
172 II->getExceptionalDest()->removePredecessor(BB);
174 // Remove the invoke instruction now.
175 BB->getInstList().erase(II);
177 ++NumLowered; Changed = true;
178 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
179 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
180 std::vector<Value*> Args;
181 Args.push_back(ConstantInt::get(Type::IntTy, 2));
182 Args.push_back(AbortMessage);
183 Args.push_back(ConstantInt::get(Type::IntTy, AbortMessageLength));
184 new CallInst(WriteFn, Args, "", UI);
186 // Insert a call to abort()
187 new CallInst(AbortFn, std::vector<Value*>(), "", UI);
189 // Insert a return instruction. This really should be a "barrier", as it
191 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
192 Constant::getNullValue(F.getReturnType()), UI);
194 // Remove the unwind instruction now.
195 BB->getInstList().erase(UI);
197 ++NumLowered; Changed = true;
202 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
203 bool Changed = false;
205 // If a function uses invoke, we have an alloca for the jump buffer.
206 AllocaInst *JmpBuf = 0;
208 // If this function contains an unwind instruction, two blocks get added: one
209 // to actually perform the longjmp, and one to terminate the program if there
211 BasicBlock *UnwindBlock = 0, *TermBlock = 0;
212 std::vector<LoadInst*> JBPtrs;
214 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
215 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
217 JmpBuf = new AllocaInst(JBLinkTy, 0, "jblink", F.begin()->begin());
219 // On the entry to the invoke, we must install our JmpBuf as the top of
221 LoadInst *OldEntry = new LoadInst(JBListHead, "oldehlist", II);
223 // Store this old value as our 'next' field, and store our alloca as the
225 std::vector<Value*> Idx;
226 Idx.push_back(Constant::getNullValue(Type::LongTy));
227 Idx.push_back(ConstantUInt::get(Type::UByteTy, 0));
228 Value *NextFieldPtr = new GetElementPtrInst(JmpBuf, Idx, "NextField", II);
229 new StoreInst(OldEntry, NextFieldPtr, II);
230 new StoreInst(JmpBuf, JBListHead, II);
232 // Call setjmp, passing in the address of the jmpbuffer.
233 Idx[1] = ConstantUInt::get(Type::UByteTy, 1);
234 Value *JmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "TheJmpBuf", II);
235 Value *SJRet = new CallInst(SetJmpFn, JmpBufPtr, "sjret", II);
237 // Compare the return value to zero.
238 Value *IsNormal = BinaryOperator::create(Instruction::SetEQ, SJRet,
239 Constant::getNullValue(SJRet->getType()),
241 // Create the receiver block if there is a critical edge to the normal
243 SplitCriticalEdge(II, 0, this);
244 Instruction *InsertLoc = II->getNormalDest()->begin();
246 // Insert a normal call instruction on the normal execution path.
247 std::string Name = II->getName(); II->setName("");
248 Value *NewCall = new CallInst(II->getCalledValue(),
249 std::vector<Value*>(II->op_begin()+3,
252 II->replaceAllUsesWith(NewCall);
254 // If we got this far, then no exception was thrown and we can pop our
256 new StoreInst(OldEntry, JBListHead, InsertLoc);
258 // Now we change the invoke into a branch instruction.
259 new BranchInst(II->getNormalDest(), II->getExceptionalDest(), IsNormal, II);
261 // Remove the InvokeInst now.
262 BB->getInstList().erase(II);
263 ++NumLowered; Changed = true;
265 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
266 if (UnwindBlock == 0) {
267 // Create two new blocks, the unwind block and the terminate block. Add
268 // them at the end of the function because they are not hot.
269 UnwindBlock = new BasicBlock("unwind", &F);
270 TermBlock = new BasicBlock("unwinderror", &F);
272 // Insert return instructions. These really should be "barrier"s, as
273 // they are unreachable.
274 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
275 Constant::getNullValue(F.getReturnType()), UnwindBlock);
276 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
277 Constant::getNullValue(F.getReturnType()), TermBlock);
280 // Load the JBList, if it's null, then there was no catch!
281 LoadInst *Ptr = new LoadInst(JBListHead, "ehlist", UI);
282 Value *NotNull = BinaryOperator::create(Instruction::SetNE, Ptr,
283 Constant::getNullValue(Ptr->getType()),
285 new BranchInst(UnwindBlock, TermBlock, NotNull, UI);
287 // Remember the loaded value so we can insert the PHI node as needed.
288 JBPtrs.push_back(Ptr);
290 // Remove the UnwindInst now.
291 BB->getInstList().erase(UI);
292 ++NumLowered; Changed = true;
295 // If an unwind instruction was inserted, we need to set up the Unwind and
298 // In the unwind block, we know that the pointer coming in on the JBPtrs
299 // list are non-null.
300 Instruction *RI = UnwindBlock->getTerminator();
303 if (JBPtrs.size() == 1)
306 // If there is more than one unwind in this function, make a PHI node to
307 // merge in all of the loaded values.
308 PHINode *PN = new PHINode(JBPtrs[0]->getType(), "jbptrs", RI);
309 for (unsigned i = 0, e = JBPtrs.size(); i != e; ++i)
310 PN->addIncoming(JBPtrs[i], JBPtrs[i]->getParent());
314 // Now that we have a pointer to the whole record, remove the entry from the
316 std::vector<Value*> Idx;
317 Idx.push_back(Constant::getNullValue(Type::LongTy));
318 Idx.push_back(ConstantUInt::get(Type::UByteTy, 0));
319 Value *NextFieldPtr = new GetElementPtrInst(RecPtr, Idx, "NextField", RI);
320 Value *NextRec = new LoadInst(NextFieldPtr, "NextRecord", RI);
321 new StoreInst(NextRec, JBListHead, RI);
323 // Now that we popped the top of the JBList, get a pointer to the jmpbuf and
325 Idx[1] = ConstantUInt::get(Type::UByteTy, 1);
326 Idx[0] = new GetElementPtrInst(RecPtr, Idx, "JmpBuf", RI);
327 Idx[1] = ConstantInt::get(Type::IntTy, 1);
328 new CallInst(LongJmpFn, Idx, "", RI);
330 // Now we set up the terminate block.
331 RI = TermBlock->getTerminator();
333 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
334 Idx[0] = ConstantInt::get(Type::IntTy, 2);
335 Idx[1] = AbortMessage;
336 Idx.push_back(ConstantInt::get(Type::IntTy, AbortMessageLength));
337 new CallInst(WriteFn, Idx, "", RI);
339 // Insert a call to abort()
340 new CallInst(AbortFn, std::vector<Value*>(), "", RI);
346 bool LowerInvoke::runOnFunction(Function &F) {
347 if (ExpensiveEHSupport)
348 return insertExpensiveEHSupport(F);
350 return insertCheapEHSupport(F);