blob: 7039a4b7e1be8f85412dbfa4263e322acf6a8710 [file] [log] [blame]
Chris Lattner86e44452003-10-05 19:14:42 +00001//===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner86e44452003-10-05 19:14:42 +00009//
10// This transformation is designed for use by code generators which do not yet
Chris Lattner6d784572004-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
John Criswellfe3706a2005-05-02 14:47:42 +000021// support to the program at the cost of making the 'invoke' instruction
22// really expensive. It basically inserts setjmp/longjmp calls to emulate the
23// exception handling as necessary.
Chris Lattner6d784572004-02-08 19:53:56 +000024//
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 Lattner86e44452003-10-05 19:14:42 +000028//
Chris Lattner0e28eca2004-03-31 22:00:30 +000029// Note that after this pass runs the CFG is not entirely accurate (exceptional
30// control flow edges are not correct anymore) so only very simple things should
31// be done after the lowerinvoke pass has run (like generation of native code).
32// This should not be used as a general purpose "my LLVM-to-LLVM pass doesn't
33// support the invoke instruction yet" lowering pass.
34//
Chris Lattner86e44452003-10-05 19:14:42 +000035//===----------------------------------------------------------------------===//
36
37#include "llvm/Transforms/Scalar.h"
Chris Lattnere1c09302004-02-08 07:30:29 +000038#include "llvm/Constants.h"
39#include "llvm/DerivedTypes.h"
Chris Lattner6d784572004-02-08 19:53:56 +000040#include "llvm/Instructions.h"
Chris Lattnere1c09302004-02-08 07:30:29 +000041#include "llvm/Module.h"
Chris Lattner86e44452003-10-05 19:14:42 +000042#include "llvm/Pass.h"
Chris Lattner6d784572004-02-08 19:53:56 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +000044#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000045#include "llvm/ADT/Statistic.h"
46#include "llvm/Support/CommandLine.h"
Chris Lattner6d784572004-02-08 19:53:56 +000047#include <csetjmp>
Chris Lattnerdead9932003-12-10 20:22:42 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Chris Lattner86e44452003-10-05 19:14:42 +000050namespace {
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +000051 Statistic<> NumInvokes("lowerinvoke", "Number of invokes replaced");
52 Statistic<> NumUnwinds("lowerinvoke", "Number of unwinds replaced");
53 Statistic<> NumSpilled("lowerinvoke",
54 "Number of registers live across unwind edges");
Chris Lattner99cca7d2004-03-01 01:12:13 +000055 cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
Chris Lattner6d784572004-02-08 19:53:56 +000056 cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
Chris Lattner86e44452003-10-05 19:14:42 +000057
58 class LowerInvoke : public FunctionPass {
Chris Lattner6d784572004-02-08 19:53:56 +000059 // Used for both models.
Chris Lattnere1c09302004-02-08 07:30:29 +000060 Function *WriteFn;
Chris Lattner86e44452003-10-05 19:14:42 +000061 Function *AbortFn;
Chris Lattner6d784572004-02-08 19:53:56 +000062 Value *AbortMessage;
63 unsigned AbortMessageLength;
64
65 // Used for expensive EH support.
66 const Type *JBLinkTy;
67 GlobalVariable *JBListHead;
68 Function *SetJmpFn, *LongJmpFn;
Chris Lattner86e44452003-10-05 19:14:42 +000069 public:
70 bool doInitialization(Module &M);
71 bool runOnFunction(Function &F);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +000072
Chris Lattner6d784572004-02-08 19:53:56 +000073 private:
Chris Lattner0c3b3902004-11-13 19:07:32 +000074 void createAbortMessage();
Chris Lattner501825e2004-02-08 22:14:44 +000075 void writeAbortMessage(Instruction *IB);
Chris Lattner6d784572004-02-08 19:53:56 +000076 bool insertCheapEHSupport(Function &F);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +000077 void splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes);
78 void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
79 AllocaInst *InvokeNum, SwitchInst *CatchSwitch);
Chris Lattner6d784572004-02-08 19:53:56 +000080 bool insertExpensiveEHSupport(Function &F);
Chris Lattner86e44452003-10-05 19:14:42 +000081 };
82
83 RegisterOpt<LowerInvoke>
84 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
85}
86
Chris Lattnercefc18e2004-02-13 16:16:16 +000087const PassInfo *llvm::LowerInvokePassID = X.getPassInfo();
88
Brian Gaeked0fde302003-11-11 22:41:34 +000089// Public Interface To the LowerInvoke pass.
Chris Lattnerdead9932003-12-10 20:22:42 +000090FunctionPass *llvm::createLowerInvokePass() { return new LowerInvoke(); }
Chris Lattner86e44452003-10-05 19:14:42 +000091
92// doInitialization - Make sure that there is a prototype for abort in the
93// current module.
94bool LowerInvoke::doInitialization(Module &M) {
Chris Lattner6d784572004-02-08 19:53:56 +000095 const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
Chris Lattnerf1d0d352004-02-09 22:48:47 +000096 AbortMessage = 0;
Chris Lattner6d784572004-02-08 19:53:56 +000097 if (ExpensiveEHSupport) {
98 // Insert a type for the linked list of jump buffers. Unfortunately, we
99 // don't know the size of the target's setjmp buffer, so we make a guess.
100 // If this guess turns out to be too small, bad stuff could happen.
101 unsigned JmpBufSize = 200; // PPC has 192 words
102 assert(sizeof(jmp_buf) <= JmpBufSize*sizeof(void*) &&
103 "LowerInvoke doesn't know about targets with jmp_buf size > 200 words!");
104 const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JmpBufSize);
Chris Lattnere1c09302004-02-08 07:30:29 +0000105
Chris Lattner6d784572004-02-08 19:53:56 +0000106 { // The type is recursive, so use a type holder.
107 std::vector<const Type*> Elements;
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000108 Elements.push_back(JmpBufTy);
Chris Lattner6d784572004-02-08 19:53:56 +0000109 OpaqueType *OT = OpaqueType::get();
110 Elements.push_back(PointerType::get(OT));
Chris Lattner6d784572004-02-08 19:53:56 +0000111 PATypeHolder JBLType(StructType::get(Elements));
112 OT->refineAbstractTypeTo(JBLType.get()); // Complete the cycle.
113 JBLinkTy = JBLType.get();
Chris Lattner11b9be52004-05-28 05:02:13 +0000114 M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
Chris Lattner6d784572004-02-08 19:53:56 +0000115 }
116
117 const Type *PtrJBList = PointerType::get(JBLinkTy);
118
119 // Now that we've done that, insert the jmpbuf list head global, unless it
120 // already exists.
121 if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList)))
122 JBListHead = new GlobalVariable(PtrJBList, false,
123 GlobalValue::LinkOnceLinkage,
124 Constant::getNullValue(PtrJBList),
125 "llvm.sjljeh.jblist", &M);
Chris Lattner860a1612004-02-15 22:24:27 +0000126 SetJmpFn = M.getOrInsertFunction("llvm.setjmp", Type::IntTy,
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000127 PointerType::get(JmpBufTy), (Type *)0);
Chris Lattner860a1612004-02-15 22:24:27 +0000128 LongJmpFn = M.getOrInsertFunction("llvm.longjmp", Type::VoidTy,
Chris Lattner6d784572004-02-08 19:53:56 +0000129 PointerType::get(JmpBufTy),
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000130 Type::IntTy, (Type *)0);
Chris Lattner6d784572004-02-08 19:53:56 +0000131 }
132
133 // We need the 'write' and 'abort' functions for both models.
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000134 AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, (Type *)0);
Chris Lattner501825e2004-02-08 22:14:44 +0000135
136 // Unfortunately, 'write' can end up being prototyped in several different
137 // ways. If the user defines a three (or more) operand function named 'write'
Misha Brukmanb9806e02004-02-08 22:27:33 +0000138 // we will use their prototype. We _do not_ want to insert another instance
Chris Lattner501825e2004-02-08 22:14:44 +0000139 // of a write prototype, because we don't know that the funcresolve pass will
140 // run after us. If there is a definition of a write function, but it's not
141 // suitable for our uses, we just don't emit write calls. If there is no
142 // write prototype at all, we just add one.
143 if (Function *WF = M.getNamedFunction("write")) {
144 if (WF->getFunctionType()->getNumParams() > 3 ||
145 WF->getFunctionType()->isVarArg())
146 WriteFn = WF;
147 else
148 WriteFn = 0;
149 } else {
150 WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
Jeff Cohen66c5fd62005-10-23 04:37:20 +0000151 VoidPtrTy, Type::IntTy, (Type *)0);
Chris Lattner501825e2004-02-08 22:14:44 +0000152 }
Chris Lattner86e44452003-10-05 19:14:42 +0000153 return true;
154}
155
Chris Lattner0c3b3902004-11-13 19:07:32 +0000156void LowerInvoke::createAbortMessage() {
157 Module &M = *WriteFn->getParent();
158 if (ExpensiveEHSupport) {
159 // The abort message for expensive EH support tells the user that the
160 // program 'unwound' without an 'invoke' instruction.
161 Constant *Msg =
162 ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
163 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
Misha Brukmanfd939082005-04-21 23:48:37 +0000164
Chris Lattner0c3b3902004-11-13 19:07:32 +0000165 GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
166 GlobalValue::InternalLinkage,
167 Msg, "abortmsg", &M);
Chris Lattner1381dd82005-05-13 06:10:12 +0000168 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0c3b3902004-11-13 19:07:32 +0000169 AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, GEPIdx);
170 } else {
171 // The abort message for cheap EH support tells the user that EH is not
172 // enabled.
173 Constant *Msg =
174 ConstantArray::get("Exception handler needed, but not enabled. Recompile"
175 " program with -enable-correct-eh-support.\n");
176 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
177
178 GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
179 GlobalValue::InternalLinkage,
180 Msg, "abortmsg", &M);
Chris Lattner1381dd82005-05-13 06:10:12 +0000181 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0c3b3902004-11-13 19:07:32 +0000182 AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, GEPIdx);
183 }
184}
185
186
Chris Lattner501825e2004-02-08 22:14:44 +0000187void LowerInvoke::writeAbortMessage(Instruction *IB) {
188 if (WriteFn) {
Chris Lattner0c3b3902004-11-13 19:07:32 +0000189 if (AbortMessage == 0) createAbortMessage();
190
Chris Lattner501825e2004-02-08 22:14:44 +0000191 // These are the arguments we WANT...
192 std::vector<Value*> Args;
193 Args.push_back(ConstantInt::get(Type::IntTy, 2));
194 Args.push_back(AbortMessage);
195 Args.push_back(ConstantInt::get(Type::IntTy, AbortMessageLength));
196
197 // If the actual declaration of write disagrees, insert casts as
198 // appropriate.
199 const FunctionType *FT = WriteFn->getFunctionType();
200 unsigned NumArgs = FT->getNumParams();
201 for (unsigned i = 0; i != 3; ++i)
202 if (i < NumArgs && FT->getParamType(i) != Args[i]->getType())
Misha Brukmanfd939082005-04-21 23:48:37 +0000203 Args[i] = ConstantExpr::getCast(cast<Constant>(Args[i]),
Chris Lattner501825e2004-02-08 22:14:44 +0000204 FT->getParamType(i));
205
Chris Lattnera9e92112005-05-06 06:48:21 +0000206 (new CallInst(WriteFn, Args, "", IB))->setTailCall();
Chris Lattner501825e2004-02-08 22:14:44 +0000207 }
208}
209
Chris Lattner6d784572004-02-08 19:53:56 +0000210bool LowerInvoke::insertCheapEHSupport(Function &F) {
Chris Lattner86e44452003-10-05 19:14:42 +0000211 bool Changed = false;
Chris Lattnerdead9932003-12-10 20:22:42 +0000212 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
213 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Chris Lattner86e44452003-10-05 19:14:42 +0000214 // Insert a normal call instruction...
215 std::string Name = II->getName(); II->setName("");
Chris Lattnerefd91682005-05-13 06:27:02 +0000216 CallInst *NewCall = new CallInst(II->getCalledValue(),
217 std::vector<Value*>(II->op_begin()+3,
218 II->op_end()), Name, II);
219 NewCall->setCallingConv(II->getCallingConv());
Chris Lattner86e44452003-10-05 19:14:42 +0000220 II->replaceAllUsesWith(NewCall);
Misha Brukmanfd939082005-04-21 23:48:37 +0000221
Chris Lattnerdead9932003-12-10 20:22:42 +0000222 // Insert an unconditional branch to the normal destination.
Chris Lattner86e44452003-10-05 19:14:42 +0000223 new BranchInst(II->getNormalDest(), II);
224
Chris Lattnerdead9932003-12-10 20:22:42 +0000225 // Remove any PHI node entries from the exception destination.
Chris Lattneraeb2a1d2004-02-08 21:44:31 +0000226 II->getUnwindDest()->removePredecessor(BB);
Chris Lattnerdead9932003-12-10 20:22:42 +0000227
Chris Lattner86e44452003-10-05 19:14:42 +0000228 // Remove the invoke instruction now.
Chris Lattnerdead9932003-12-10 20:22:42 +0000229 BB->getInstList().erase(II);
Chris Lattner86e44452003-10-05 19:14:42 +0000230
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000231 ++NumInvokes; Changed = true;
Chris Lattnerdead9932003-12-10 20:22:42 +0000232 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattnere1c09302004-02-08 07:30:29 +0000233 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
Chris Lattner501825e2004-02-08 22:14:44 +0000234 writeAbortMessage(UI);
Chris Lattnere1c09302004-02-08 07:30:29 +0000235
Chris Lattner86e44452003-10-05 19:14:42 +0000236 // Insert a call to abort()
Chris Lattnera9e92112005-05-06 06:48:21 +0000237 (new CallInst(AbortFn, std::vector<Value*>(), "", UI))->setTailCall();
Chris Lattner86e44452003-10-05 19:14:42 +0000238
Chris Lattner6d784572004-02-08 19:53:56 +0000239 // Insert a return instruction. This really should be a "barrier", as it
240 // is unreachable.
Chris Lattner86e44452003-10-05 19:14:42 +0000241 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
242 Constant::getNullValue(F.getReturnType()), UI);
243
244 // Remove the unwind instruction now.
Chris Lattnerdead9932003-12-10 20:22:42 +0000245 BB->getInstList().erase(UI);
Chris Lattner86e44452003-10-05 19:14:42 +0000246
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000247 ++NumUnwinds; Changed = true;
Chris Lattner86e44452003-10-05 19:14:42 +0000248 }
249 return Changed;
250}
Chris Lattner6d784572004-02-08 19:53:56 +0000251
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000252/// rewriteExpensiveInvoke - Insert code and hack the function to replace the
253/// specified invoke instruction with a call.
254void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
255 AllocaInst *InvokeNum,
256 SwitchInst *CatchSwitch) {
257 ConstantUInt *InvokeNoC = ConstantUInt::get(Type::UIntTy, InvokeNo);
Chris Lattner6d784572004-02-08 19:53:56 +0000258
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000259 // Insert a store of the invoke num before the invoke and store zero into the
260 // location afterward.
261 new StoreInst(InvokeNoC, InvokeNum, true, II); // volatile
Chris Lattner93e50ce2005-09-29 17:44:20 +0000262
263 BasicBlock::iterator NI = II->getNormalDest()->begin();
264 while (isa<PHINode>(NI)) ++NI;
265 // nonvolatile.
266 new StoreInst(Constant::getNullValue(Type::UIntTy), InvokeNum, false, NI);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000267
268 // Add a switch case to our unwind block.
269 CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
270
271 // Insert a normal call instruction.
272 std::string Name = II->getName(); II->setName("");
273 CallInst *NewCall = new CallInst(II->getCalledValue(),
274 std::vector<Value*>(II->op_begin()+3,
275 II->op_end()), Name,
276 II);
277 NewCall->setCallingConv(II->getCallingConv());
278 II->replaceAllUsesWith(NewCall);
279
280 // Replace the invoke with an uncond branch.
281 new BranchInst(II->getNormalDest(), NewCall->getParent());
282 II->eraseFromParent();
283}
Chris Lattner6d784572004-02-08 19:53:56 +0000284
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000285/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
286/// we reach blocks we've already seen.
287static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
288 if (!LiveBBs.insert(BB).second) return; // already been here.
289
290 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
291 MarkBlocksLiveIn(*PI, LiveBBs);
292}
Chris Lattner6d784572004-02-08 19:53:56 +0000293
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000294// First thing we need to do is scan the whole function for values that are
295// live across unwind edges. Each value that is live across an unwind edge
296// we spill into a stack location, guaranteeing that there is nothing live
297// across the unwind edge. This process also splits all critical edges
298// coming out of invoke's.
299void LowerInvoke::
300splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes) {
301 // First step, split all critical edges from invoke instructions.
302 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
303 InvokeInst *II = Invokes[i];
304 SplitCriticalEdge(II, 0, this);
305 SplitCriticalEdge(II, 1, this);
306 assert(!isa<PHINode>(II->getNormalDest()) &&
307 !isa<PHINode>(II->getUnwindDest()) &&
308 "critical edge splitting left single entry phi nodes?");
Chris Lattner6d784572004-02-08 19:53:56 +0000309 }
310
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000311 Function *F = Invokes.back()->getParent()->getParent();
312
313 // To avoid having to handle incoming arguments specially, we lower each arg
314 // to a copy instruction in the entry block. This ensure that the argument
315 // value itself cannot be live across the entry block.
316 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
317 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
318 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
319 ++AfterAllocaInsertPt;
320 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
321 AI != E; ++AI) {
322 CastInst *NC = new CastInst(AI, AI->getType(), AI->getName()+".tmp",
323 AfterAllocaInsertPt);
324 AI->replaceAllUsesWith(NC);
325 NC->setOperand(0, AI);
326 }
327
328 // Finally, scan the code looking for instructions with bad live ranges.
329 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
330 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
331 // Ignore obvious cases we don't have to handle. In particular, most
332 // instructions either have no uses or only have a single use inside the
333 // current block. Ignore them quickly.
334 Instruction *Inst = II;
335 if (Inst->use_empty()) continue;
336 if (Inst->hasOneUse() &&
337 cast<Instruction>(Inst->use_back())->getParent() == BB &&
338 !isa<PHINode>(Inst->use_back())) continue;
339
Chris Lattner45313712005-09-27 21:33:12 +0000340 // If this is an alloca in the entry block, it's not a real register
341 // value.
342 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
343 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
344 continue;
345
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000346 // Avoid iterator invalidation by copying users to a temporary vector.
347 std::vector<Instruction*> Users;
348 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
349 UI != E; ++UI) {
350 Instruction *User = cast<Instruction>(*UI);
351 if (User->getParent() != BB || isa<PHINode>(User))
352 Users.push_back(User);
353 }
354
355 // Scan all of the uses and see if the live range is live across an unwind
356 // edge. If we find a use live across an invoke edge, create an alloca
357 // and spill the value.
358 AllocaInst *SpillLoc = 0;
359 std::set<InvokeInst*> InvokesWithStoreInserted;
360
361 // Find all of the blocks that this value is live in.
362 std::set<BasicBlock*> LiveBBs;
363 LiveBBs.insert(Inst->getParent());
364 while (!Users.empty()) {
365 Instruction *U = Users.back();
366 Users.pop_back();
367
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000368 if (!isa<PHINode>(U)) {
369 MarkBlocksLiveIn(U->getParent(), LiveBBs);
370 } else {
371 // Uses for a PHI node occur in their predecessor block.
372 PHINode *PN = cast<PHINode>(U);
373 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
374 if (PN->getIncomingValue(i) == Inst)
375 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
376 }
377 }
378
379 // Now that we know all of the blocks that this thing is live in, see if
380 // it includes any of the unwind locations.
381 bool NeedsSpill = false;
382 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
383 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
384 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
385 NeedsSpill = true;
386 }
387 }
388
389 // If we decided we need a spill, do it.
390 if (NeedsSpill) {
391 ++NumSpilled;
392 DemoteRegToStack(*Inst, true);
393 }
394 }
395}
396
397bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
398 std::vector<ReturnInst*> Returns;
399 std::vector<UnwindInst*> Unwinds;
400 std::vector<InvokeInst*> Invokes;
401
402 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
403 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
404 // Remember all return instructions in case we insert an invoke into this
405 // function.
406 Returns.push_back(RI);
407 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
408 Invokes.push_back(II);
409 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
410 Unwinds.push_back(UI);
411 }
412
413 if (Unwinds.empty() && Invokes.empty()) return false;
414
415 NumInvokes += Invokes.size();
416 NumUnwinds += Unwinds.size();
Chris Lattner5b3c7022005-09-27 22:44:59 +0000417
418 // TODO: This is not an optimal way to do this. In particular, this always
419 // inserts setjmp calls into the entries of functions with invoke instructions
420 // even though there are possibly paths through the function that do not
421 // execute any invokes. In particular, for functions with early exits, e.g.
422 // the 'addMove' method in hexxagon, it would be nice to not have to do the
423 // setjmp stuff on the early exit path. This requires a bit of dataflow, but
424 // would not be too hard to do.
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000425
426 // If we have an invoke instruction, insert a setjmp that dominates all
427 // invokes. After the setjmp, use a cond branch that goes to the original
428 // code path on zero, and to a designated 'catch' block of nonzero.
429 Value *OldJmpBufPtr = 0;
430 if (!Invokes.empty()) {
431 // First thing we need to do is scan the whole function for values that are
432 // live across unwind edges. Each value that is live across an unwind edge
433 // we spill into a stack location, guaranteeing that there is nothing live
434 // across the unwind edge. This process also splits all critical edges
435 // coming out of invoke's.
436 splitLiveRangesLiveAcrossInvokes(Invokes);
437
438 BasicBlock *EntryBB = F.begin();
439
440 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
441 // that needs to be restored on all exits from the function. This is an
442 // alloca because the value needs to be live across invokes.
443 AllocaInst *JmpBuf =
444 new AllocaInst(JBLinkTy, 0, "jblink", F.begin()->begin());
445
446 std::vector<Value*> Idx;
447 Idx.push_back(Constant::getNullValue(Type::IntTy));
448 Idx.push_back(ConstantUInt::get(Type::UIntTy, 1));
449 OldJmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "OldBuf",
450 EntryBB->getTerminator());
451
452 // Copy the JBListHead to the alloca.
453 Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
454 EntryBB->getTerminator());
455 new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
456
457 // Add the new jumpbuf to the list.
458 new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
459
460 // Create the catch block. The catch block is basically a big switch
461 // statement that goes to all of the invoke catch blocks.
462 BasicBlock *CatchBB = new BasicBlock("setjmp.catch", &F);
463
464 // Create an alloca which keeps track of which invoke is currently
465 // executing. For normal calls it contains zero.
466 AllocaInst *InvokeNum = new AllocaInst(Type::UIntTy, 0, "invokenum",
467 EntryBB->begin());
468 new StoreInst(ConstantInt::get(Type::UIntTy, 0), InvokeNum, true,
469 EntryBB->getTerminator());
470
471 // Insert a load in the Catch block, and a switch on its value. By default,
472 // we go to a block that just does an unwind (which is the correct action
473 // for a standard call).
474 BasicBlock *UnwindBB = new BasicBlock("unwindbb", &F);
475 Unwinds.push_back(new UnwindInst(UnwindBB));
476
477 Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
478 SwitchInst *CatchSwitch =
479 new SwitchInst(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
480
481 // Now that things are set up, insert the setjmp call itself.
482
483 // Split the entry block to insert the conditional branch for the setjmp.
484 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
485 "setjmp.cont");
486
487 Idx[1] = ConstantUInt::get(Type::UIntTy, 0);
488 Value *JmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "TheJmpBuf",
489 EntryBB->getTerminator());
490 Value *SJRet = new CallInst(SetJmpFn, JmpBufPtr, "sjret",
491 EntryBB->getTerminator());
492
493 // Compare the return value to zero.
494 Value *IsNormal = BinaryOperator::createSetEQ(SJRet,
495 Constant::getNullValue(SJRet->getType()),
496 "notunwind", EntryBB->getTerminator());
497 // Nuke the uncond branch.
498 EntryBB->getTerminator()->eraseFromParent();
499
500 // Put in a new condbranch in its place.
501 new BranchInst(ContBlock, CatchBB, IsNormal, EntryBB);
502
503 // At this point, we are all set up, rewrite each invoke instruction.
504 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
505 rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, CatchSwitch);
506 }
507
508 // We know that there is at least one unwind.
509
510 // Create three new blocks, the block to load the jmpbuf ptr and compare
511 // against null, the block to do the longjmp, and the error block for if it
512 // is null. Add them at the end of the function because they are not hot.
513 BasicBlock *UnwindHandler = new BasicBlock("dounwind", &F);
514 BasicBlock *UnwindBlock = new BasicBlock("unwind", &F);
515 BasicBlock *TermBlock = new BasicBlock("unwinderror", &F);
516
517 // If this function contains an invoke, restore the old jumpbuf ptr.
518 Value *BufPtr;
519 if (OldJmpBufPtr) {
520 // Before the return, insert a copy from the saved value to the new value.
521 BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
522 new StoreInst(BufPtr, JBListHead, UnwindHandler);
523 } else {
524 BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
525 }
526
527 // Load the JBList, if it's null, then there was no catch!
528 Value *NotNull = BinaryOperator::createSetNE(BufPtr,
529 Constant::getNullValue(BufPtr->getType()),
530 "notnull", UnwindHandler);
531 new BranchInst(UnwindBlock, TermBlock, NotNull, UnwindHandler);
532
533 // Create the block to do the longjmp.
534 // Get a pointer to the jmpbuf and longjmp.
535 std::vector<Value*> Idx;
536 Idx.push_back(Constant::getNullValue(Type::IntTy));
537 Idx.push_back(ConstantUInt::get(Type::UIntTy, 0));
538 Idx[0] = new GetElementPtrInst(BufPtr, Idx, "JmpBuf", UnwindBlock);
539 Idx[1] = ConstantInt::get(Type::IntTy, 1);
540 new CallInst(LongJmpFn, Idx, "", UnwindBlock);
541 new UnreachableInst(UnwindBlock);
542
543 // Set up the term block ("throw without a catch").
544 new UnreachableInst(TermBlock);
545
546 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
547 writeAbortMessage(TermBlock->getTerminator());
548
549 // Insert a call to abort()
550 (new CallInst(AbortFn, std::vector<Value*>(), "",
551 TermBlock->getTerminator()))->setTailCall();
552
553
554 // Replace all unwinds with a branch to the unwind handler.
555 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
556 new BranchInst(UnwindHandler, Unwinds[i]);
557 Unwinds[i]->eraseFromParent();
558 }
559
560 // Finally, for any returns from this function, if this function contains an
561 // invoke, restore the old jmpbuf pointer to its input value.
562 if (OldJmpBufPtr) {
563 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
564 ReturnInst *R = Returns[i];
565
566 // Before the return, insert a copy from the saved value to the new value.
567 Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
568 new StoreInst(OldBuf, JBListHead, true, R);
569 }
570 }
571
572 return true;
Chris Lattner6d784572004-02-08 19:53:56 +0000573}
574
575bool LowerInvoke::runOnFunction(Function &F) {
576 if (ExpensiveEHSupport)
577 return insertExpensiveEHSupport(F);
578 else
579 return insertCheapEHSupport(F);
580}