blob: a027743bda715bdce5b981d954f613b0c883feeb [file] [log] [blame]
Chris Lattnera43b8f42003-10-05 19:14:42 +00001//===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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
John Criswellf42ed7b2005-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 Lattner108cadc2004-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 Lattnera43b8f42003-10-05 19:14:42 +000028//
Chris Lattner61fab142004-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 Lattnera43b8f42003-10-05 19:14:42 +000035//===----------------------------------------------------------------------===//
36
Chris Lattner45f966d2006-12-19 22:17:40 +000037#define DEBUG_TYPE "lowerinvoke"
Chris Lattnera43b8f42003-10-05 19:14:42 +000038#include "llvm/Transforms/Scalar.h"
Chris Lattner476488e2004-02-08 07:30:29 +000039#include "llvm/Constants.h"
40#include "llvm/DerivedTypes.h"
Chris Lattner108cadc2004-02-08 19:53:56 +000041#include "llvm/Instructions.h"
Chris Lattner476488e2004-02-08 07:30:29 +000042#include "llvm/Module.h"
Chris Lattnera43b8f42003-10-05 19:14:42 +000043#include "llvm/Pass.h"
Chris Lattner108cadc2004-02-08 19:53:56 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner87eb2492005-09-27 21:18:17 +000045#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000046#include "llvm/ADT/Statistic.h"
47#include "llvm/Support/CommandLine.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000048#include "llvm/Support/Compiler.h"
Duraid Madinacf6749e2006-09-04 06:21:35 +000049#include "llvm/Target/TargetLowering.h"
Chris Lattner108cadc2004-02-08 19:53:56 +000050#include <csetjmp>
Chris Lattner7e5bd592003-12-10 20:22:42 +000051using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000052
Chris Lattner45f966d2006-12-19 22:17:40 +000053STATISTIC(NumInvokes, "Number of invokes replaced");
54STATISTIC(NumUnwinds, "Number of unwinds replaced");
55STATISTIC(NumSpilled, "Number of registers live across unwind edges");
56
57static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
Chris Lattner108cadc2004-02-08 19:53:56 +000058 cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
Chris Lattnera43b8f42003-10-05 19:14:42 +000059
Chris Lattner45f966d2006-12-19 22:17:40 +000060namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000061 class VISIBILITY_HIDDEN LowerInvoke : public FunctionPass {
Chris Lattner108cadc2004-02-08 19:53:56 +000062 // Used for both models.
Chris Lattner34acba42007-01-07 08:12:01 +000063 Constant *WriteFn;
64 Constant *AbortFn;
Chris Lattner108cadc2004-02-08 19:53:56 +000065 Value *AbortMessage;
66 unsigned AbortMessageLength;
67
68 // Used for expensive EH support.
69 const Type *JBLinkTy;
70 GlobalVariable *JBListHead;
Chris Lattner34acba42007-01-07 08:12:01 +000071 Constant *SetJmpFn, *LongJmpFn;
Duraid Madinacf6749e2006-09-04 06:21:35 +000072
73 // We peek in TLI to grab the target's jmp_buf size and alignment
74 const TargetLowering *TLI;
75
Chris Lattnera43b8f42003-10-05 19:14:42 +000076 public:
Duraid Madinacf6749e2006-09-04 06:21:35 +000077 LowerInvoke(const TargetLowering *tli = NULL) : TLI(tli) { }
Chris Lattnera43b8f42003-10-05 19:14:42 +000078 bool doInitialization(Module &M);
79 bool runOnFunction(Function &F);
Chris Lattnere4cb4762006-05-17 21:05:27 +000080
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82 // This is a cluster of orthogonal Transforms
83 AU.addPreservedID(PromoteMemoryToRegisterID);
84 AU.addPreservedID(LowerSelectID);
85 AU.addPreservedID(LowerSwitchID);
86 AU.addPreservedID(LowerAllocationsID);
87 }
88
Chris Lattner108cadc2004-02-08 19:53:56 +000089 private:
Chris Lattner34acba42007-01-07 08:12:01 +000090 void createAbortMessage(Module *M);
Chris Lattner3b7f6b22004-02-08 22:14:44 +000091 void writeAbortMessage(Instruction *IB);
Chris Lattner108cadc2004-02-08 19:53:56 +000092 bool insertCheapEHSupport(Function &F);
Chris Lattner87eb2492005-09-27 21:18:17 +000093 void splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes);
94 void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
95 AllocaInst *InvokeNum, SwitchInst *CatchSwitch);
Chris Lattner108cadc2004-02-08 19:53:56 +000096 bool insertExpensiveEHSupport(Function &F);
Chris Lattnera43b8f42003-10-05 19:14:42 +000097 };
98
Chris Lattnerc2d3d312006-08-27 22:42:52 +000099 RegisterPass<LowerInvoke>
Chris Lattnera43b8f42003-10-05 19:14:42 +0000100 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
101}
102
Chris Lattner7cbb22a2004-02-13 16:16:16 +0000103const PassInfo *llvm::LowerInvokePassID = X.getPassInfo();
104
Brian Gaeke960707c2003-11-11 22:41:34 +0000105// Public Interface To the LowerInvoke pass.
Duraid Madinacf6749e2006-09-04 06:21:35 +0000106FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI) {
107 return new LowerInvoke(TLI);
Nate Begeman848622f2005-11-05 09:21:28 +0000108}
Chris Lattnera43b8f42003-10-05 19:14:42 +0000109
110// doInitialization - Make sure that there is a prototype for abort in the
111// current module.
112bool LowerInvoke::doInitialization(Module &M) {
Reid Spencerc635f472006-12-31 05:48:39 +0000113 const Type *VoidPtrTy = PointerType::get(Type::Int8Ty);
Chris Lattner37d46f42004-02-09 22:48:47 +0000114 AbortMessage = 0;
Chris Lattner108cadc2004-02-08 19:53:56 +0000115 if (ExpensiveEHSupport) {
Nate Begeman848622f2005-11-05 09:21:28 +0000116 // Insert a type for the linked list of jump buffers.
Chris Lattner845b2232006-09-05 17:48:07 +0000117 unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
118 JBSize = JBSize ? JBSize : 200;
119 const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
Chris Lattner476488e2004-02-08 07:30:29 +0000120
Chris Lattner108cadc2004-02-08 19:53:56 +0000121 { // The type is recursive, so use a type holder.
122 std::vector<const Type*> Elements;
Chris Lattner87eb2492005-09-27 21:18:17 +0000123 Elements.push_back(JmpBufTy);
Chris Lattner108cadc2004-02-08 19:53:56 +0000124 OpaqueType *OT = OpaqueType::get();
125 Elements.push_back(PointerType::get(OT));
Chris Lattner108cadc2004-02-08 19:53:56 +0000126 PATypeHolder JBLType(StructType::get(Elements));
127 OT->refineAbstractTypeTo(JBLType.get()); // Complete the cycle.
128 JBLinkTy = JBLType.get();
Chris Lattner523d3e62004-05-28 05:02:13 +0000129 M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
Chris Lattner108cadc2004-02-08 19:53:56 +0000130 }
131
132 const Type *PtrJBList = PointerType::get(JBLinkTy);
133
134 // Now that we've done that, insert the jmpbuf list head global, unless it
135 // already exists.
Chris Lattner845b2232006-09-05 17:48:07 +0000136 if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) {
Chris Lattner108cadc2004-02-08 19:53:56 +0000137 JBListHead = new GlobalVariable(PtrJBList, false,
138 GlobalValue::LinkOnceLinkage,
139 Constant::getNullValue(PtrJBList),
140 "llvm.sjljeh.jblist", &M);
Chris Lattner845b2232006-09-05 17:48:07 +0000141 }
Reid Spencerc635f472006-12-31 05:48:39 +0000142 SetJmpFn = M.getOrInsertFunction("llvm.setjmp", Type::Int32Ty,
Jeff Cohen11e26b52005-10-23 04:37:20 +0000143 PointerType::get(JmpBufTy), (Type *)0);
Chris Lattnerd85e0612004-02-15 22:24:27 +0000144 LongJmpFn = M.getOrInsertFunction("llvm.longjmp", Type::VoidTy,
Chris Lattner108cadc2004-02-08 19:53:56 +0000145 PointerType::get(JmpBufTy),
Reid Spencerc635f472006-12-31 05:48:39 +0000146 Type::Int32Ty, (Type *)0);
Chris Lattner108cadc2004-02-08 19:53:56 +0000147 }
148
149 // We need the 'write' and 'abort' functions for both models.
Jeff Cohen11e26b52005-10-23 04:37:20 +0000150 AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, (Type *)0);
Chris Lattner34acba42007-01-07 08:12:01 +0000151 WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::Int32Ty,
152 VoidPtrTy, Type::Int32Ty, (Type *)0);
Chris Lattnera43b8f42003-10-05 19:14:42 +0000153 return true;
154}
155
Chris Lattner34acba42007-01-07 08:12:01 +0000156void LowerInvoke::createAbortMessage(Module *M) {
Chris Lattner2858e172004-11-13 19:07:32 +0000157 if (ExpensiveEHSupport) {
158 // The abort message for expensive EH support tells the user that the
159 // program 'unwound' without an 'invoke' instruction.
160 Constant *Msg =
161 ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
162 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
Misha Brukmanb1c93172005-04-21 23:48:37 +0000163
Chris Lattner2858e172004-11-13 19:07:32 +0000164 GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
165 GlobalValue::InternalLinkage,
Chris Lattner34acba42007-01-07 08:12:01 +0000166 Msg, "abortmsg", M);
Reid Spencerc635f472006-12-31 05:48:39 +0000167 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner2858e172004-11-13 19:07:32 +0000168 AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, GEPIdx);
169 } else {
170 // The abort message for cheap EH support tells the user that EH is not
171 // enabled.
172 Constant *Msg =
173 ConstantArray::get("Exception handler needed, but not enabled. Recompile"
174 " program with -enable-correct-eh-support.\n");
175 AbortMessageLength = Msg->getNumOperands()-1; // don't include \0
176
177 GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
178 GlobalValue::InternalLinkage,
Chris Lattner34acba42007-01-07 08:12:01 +0000179 Msg, "abortmsg", M);
Reid Spencerc635f472006-12-31 05:48:39 +0000180 std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner2858e172004-11-13 19:07:32 +0000181 AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, GEPIdx);
182 }
183}
184
185
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000186void LowerInvoke::writeAbortMessage(Instruction *IB) {
Chris Lattner34acba42007-01-07 08:12:01 +0000187 if (AbortMessage == 0)
188 createAbortMessage(IB->getParent()->getParent()->getParent());
Chris Lattner2858e172004-11-13 19:07:32 +0000189
Chris Lattner34acba42007-01-07 08:12:01 +0000190 // These are the arguments we WANT...
191 std::vector<Value*> Args;
192 Args.push_back(ConstantInt::get(Type::Int32Ty, 2));
193 Args.push_back(AbortMessage);
194 Args.push_back(ConstantInt::get(Type::Int32Ty, AbortMessageLength));
195 (new CallInst(WriteFn, Args, "", IB))->setTailCall();
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000196}
197
Chris Lattner108cadc2004-02-08 19:53:56 +0000198bool LowerInvoke::insertCheapEHSupport(Function &F) {
Chris Lattnera43b8f42003-10-05 19:14:42 +0000199 bool Changed = false;
Chris Lattner7e5bd592003-12-10 20:22:42 +0000200 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
201 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Chris Lattnera43b8f42003-10-05 19:14:42 +0000202 // Insert a normal call instruction...
203 std::string Name = II->getName(); II->setName("");
Chris Lattnerca968392005-05-13 06:27:02 +0000204 CallInst *NewCall = new CallInst(II->getCalledValue(),
205 std::vector<Value*>(II->op_begin()+3,
206 II->op_end()), Name, II);
207 NewCall->setCallingConv(II->getCallingConv());
Chris Lattnera43b8f42003-10-05 19:14:42 +0000208 II->replaceAllUsesWith(NewCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000209
Chris Lattner7e5bd592003-12-10 20:22:42 +0000210 // Insert an unconditional branch to the normal destination.
Chris Lattnera43b8f42003-10-05 19:14:42 +0000211 new BranchInst(II->getNormalDest(), II);
212
Chris Lattner7e5bd592003-12-10 20:22:42 +0000213 // Remove any PHI node entries from the exception destination.
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000214 II->getUnwindDest()->removePredecessor(BB);
Chris Lattner7e5bd592003-12-10 20:22:42 +0000215
Chris Lattnera43b8f42003-10-05 19:14:42 +0000216 // Remove the invoke instruction now.
Chris Lattner7e5bd592003-12-10 20:22:42 +0000217 BB->getInstList().erase(II);
Chris Lattnera43b8f42003-10-05 19:14:42 +0000218
Chris Lattner87eb2492005-09-27 21:18:17 +0000219 ++NumInvokes; Changed = true;
Chris Lattner7e5bd592003-12-10 20:22:42 +0000220 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattner476488e2004-02-08 07:30:29 +0000221 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
Chris Lattner3b7f6b22004-02-08 22:14:44 +0000222 writeAbortMessage(UI);
Chris Lattner476488e2004-02-08 07:30:29 +0000223
Chris Lattnera43b8f42003-10-05 19:14:42 +0000224 // Insert a call to abort()
Chris Lattner6aacb0f2005-05-06 06:48:21 +0000225 (new CallInst(AbortFn, std::vector<Value*>(), "", UI))->setTailCall();
Chris Lattnera43b8f42003-10-05 19:14:42 +0000226
Chris Lattner108cadc2004-02-08 19:53:56 +0000227 // Insert a return instruction. This really should be a "barrier", as it
228 // is unreachable.
Chris Lattnera43b8f42003-10-05 19:14:42 +0000229 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
230 Constant::getNullValue(F.getReturnType()), UI);
231
232 // Remove the unwind instruction now.
Chris Lattner7e5bd592003-12-10 20:22:42 +0000233 BB->getInstList().erase(UI);
Chris Lattnera43b8f42003-10-05 19:14:42 +0000234
Chris Lattner87eb2492005-09-27 21:18:17 +0000235 ++NumUnwinds; Changed = true;
Chris Lattnera43b8f42003-10-05 19:14:42 +0000236 }
237 return Changed;
238}
Chris Lattner108cadc2004-02-08 19:53:56 +0000239
Chris Lattner87eb2492005-09-27 21:18:17 +0000240/// rewriteExpensiveInvoke - Insert code and hack the function to replace the
241/// specified invoke instruction with a call.
242void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
243 AllocaInst *InvokeNum,
244 SwitchInst *CatchSwitch) {
Reid Spencerc635f472006-12-31 05:48:39 +0000245 ConstantInt *InvokeNoC = ConstantInt::get(Type::Int32Ty, InvokeNo);
Chris Lattner108cadc2004-02-08 19:53:56 +0000246
Chris Lattner87eb2492005-09-27 21:18:17 +0000247 // Insert a store of the invoke num before the invoke and store zero into the
248 // location afterward.
249 new StoreInst(InvokeNoC, InvokeNum, true, II); // volatile
Chris Lattnera554c942005-09-29 17:44:20 +0000250
251 BasicBlock::iterator NI = II->getNormalDest()->begin();
252 while (isa<PHINode>(NI)) ++NI;
253 // nonvolatile.
Reid Spencerc635f472006-12-31 05:48:39 +0000254 new StoreInst(Constant::getNullValue(Type::Int32Ty), InvokeNum, false, NI);
Chris Lattner87eb2492005-09-27 21:18:17 +0000255
256 // Add a switch case to our unwind block.
257 CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
258
259 // Insert a normal call instruction.
260 std::string Name = II->getName(); II->setName("");
261 CallInst *NewCall = new CallInst(II->getCalledValue(),
262 std::vector<Value*>(II->op_begin()+3,
263 II->op_end()), Name,
264 II);
265 NewCall->setCallingConv(II->getCallingConv());
266 II->replaceAllUsesWith(NewCall);
267
268 // Replace the invoke with an uncond branch.
269 new BranchInst(II->getNormalDest(), NewCall->getParent());
270 II->eraseFromParent();
271}
Chris Lattner108cadc2004-02-08 19:53:56 +0000272
Chris Lattner87eb2492005-09-27 21:18:17 +0000273/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
274/// we reach blocks we've already seen.
275static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
276 if (!LiveBBs.insert(BB).second) return; // already been here.
277
278 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
279 MarkBlocksLiveIn(*PI, LiveBBs);
280}
Chris Lattner108cadc2004-02-08 19:53:56 +0000281
Chris Lattner87eb2492005-09-27 21:18:17 +0000282// First thing we need to do is scan the whole function for values that are
283// live across unwind edges. Each value that is live across an unwind edge
284// we spill into a stack location, guaranteeing that there is nothing live
285// across the unwind edge. This process also splits all critical edges
286// coming out of invoke's.
287void LowerInvoke::
288splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes) {
289 // First step, split all critical edges from invoke instructions.
290 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
291 InvokeInst *II = Invokes[i];
292 SplitCriticalEdge(II, 0, this);
293 SplitCriticalEdge(II, 1, this);
294 assert(!isa<PHINode>(II->getNormalDest()) &&
295 !isa<PHINode>(II->getUnwindDest()) &&
296 "critical edge splitting left single entry phi nodes?");
Chris Lattner108cadc2004-02-08 19:53:56 +0000297 }
298
Chris Lattner87eb2492005-09-27 21:18:17 +0000299 Function *F = Invokes.back()->getParent()->getParent();
300
301 // To avoid having to handle incoming arguments specially, we lower each arg
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000302 // to a copy instruction in the entry block. This ensures that the argument
Chris Lattner87eb2492005-09-27 21:18:17 +0000303 // value itself cannot be live across the entry block.
304 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
305 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
306 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
307 ++AfterAllocaInsertPt;
308 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
309 AI != E; ++AI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000310 // This is always a no-op cast because we're casting AI to AI->getType() so
311 // src and destination types are identical. BitCast is the only possibility.
312 CastInst *NC = new BitCastInst(
313 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
Chris Lattner87eb2492005-09-27 21:18:17 +0000314 AI->replaceAllUsesWith(NC);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000315 // Normally its is forbidden to replace a CastInst's operand because it
316 // could cause the opcode to reflect an illegal conversion. However, we're
317 // replacing it here with the same value it was constructed with to simply
318 // make NC its user.
319 NC->setOperand(0, AI);
Chris Lattner87eb2492005-09-27 21:18:17 +0000320 }
321
322 // Finally, scan the code looking for instructions with bad live ranges.
323 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
324 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
325 // Ignore obvious cases we don't have to handle. In particular, most
326 // instructions either have no uses or only have a single use inside the
327 // current block. Ignore them quickly.
328 Instruction *Inst = II;
329 if (Inst->use_empty()) continue;
330 if (Inst->hasOneUse() &&
331 cast<Instruction>(Inst->use_back())->getParent() == BB &&
332 !isa<PHINode>(Inst->use_back())) continue;
333
Chris Lattnere285f5e2005-09-27 21:33:12 +0000334 // If this is an alloca in the entry block, it's not a real register
335 // value.
336 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
337 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
338 continue;
339
Chris Lattner87eb2492005-09-27 21:18:17 +0000340 // Avoid iterator invalidation by copying users to a temporary vector.
341 std::vector<Instruction*> Users;
342 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
343 UI != E; ++UI) {
344 Instruction *User = cast<Instruction>(*UI);
345 if (User->getParent() != BB || isa<PHINode>(User))
346 Users.push_back(User);
347 }
348
349 // Scan all of the uses and see if the live range is live across an unwind
350 // edge. If we find a use live across an invoke edge, create an alloca
351 // and spill the value.
Chris Lattner87eb2492005-09-27 21:18:17 +0000352 std::set<InvokeInst*> InvokesWithStoreInserted;
353
354 // Find all of the blocks that this value is live in.
355 std::set<BasicBlock*> LiveBBs;
356 LiveBBs.insert(Inst->getParent());
357 while (!Users.empty()) {
358 Instruction *U = Users.back();
359 Users.pop_back();
360
Chris Lattner87eb2492005-09-27 21:18:17 +0000361 if (!isa<PHINode>(U)) {
362 MarkBlocksLiveIn(U->getParent(), LiveBBs);
363 } else {
364 // Uses for a PHI node occur in their predecessor block.
365 PHINode *PN = cast<PHINode>(U);
366 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
367 if (PN->getIncomingValue(i) == Inst)
368 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
369 }
370 }
371
372 // Now that we know all of the blocks that this thing is live in, see if
373 // it includes any of the unwind locations.
374 bool NeedsSpill = false;
375 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
376 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
377 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
378 NeedsSpill = true;
379 }
380 }
381
382 // If we decided we need a spill, do it.
383 if (NeedsSpill) {
384 ++NumSpilled;
385 DemoteRegToStack(*Inst, true);
386 }
387 }
388}
389
390bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
391 std::vector<ReturnInst*> Returns;
392 std::vector<UnwindInst*> Unwinds;
393 std::vector<InvokeInst*> Invokes;
394
395 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
396 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
397 // Remember all return instructions in case we insert an invoke into this
398 // function.
399 Returns.push_back(RI);
400 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
401 Invokes.push_back(II);
402 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
403 Unwinds.push_back(UI);
404 }
405
406 if (Unwinds.empty() && Invokes.empty()) return false;
407
408 NumInvokes += Invokes.size();
409 NumUnwinds += Unwinds.size();
Chris Lattner3b63bb32005-09-27 22:44:59 +0000410
411 // TODO: This is not an optimal way to do this. In particular, this always
412 // inserts setjmp calls into the entries of functions with invoke instructions
413 // even though there are possibly paths through the function that do not
414 // execute any invokes. In particular, for functions with early exits, e.g.
415 // the 'addMove' method in hexxagon, it would be nice to not have to do the
416 // setjmp stuff on the early exit path. This requires a bit of dataflow, but
417 // would not be too hard to do.
Chris Lattner87eb2492005-09-27 21:18:17 +0000418
419 // If we have an invoke instruction, insert a setjmp that dominates all
420 // invokes. After the setjmp, use a cond branch that goes to the original
421 // code path on zero, and to a designated 'catch' block of nonzero.
422 Value *OldJmpBufPtr = 0;
423 if (!Invokes.empty()) {
424 // First thing we need to do is scan the whole function for values that are
425 // live across unwind edges. Each value that is live across an unwind edge
426 // we spill into a stack location, guaranteeing that there is nothing live
427 // across the unwind edge. This process also splits all critical edges
428 // coming out of invoke's.
429 splitLiveRangesLiveAcrossInvokes(Invokes);
430
431 BasicBlock *EntryBB = F.begin();
432
433 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
434 // that needs to be restored on all exits from the function. This is an
435 // alloca because the value needs to be live across invokes.
Chris Lattner845b2232006-09-05 17:48:07 +0000436 unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0;
Chris Lattner87eb2492005-09-27 21:18:17 +0000437 AllocaInst *JmpBuf =
Chris Lattner845b2232006-09-05 17:48:07 +0000438 new AllocaInst(JBLinkTy, 0, Align, "jblink", F.begin()->begin());
Chris Lattner87eb2492005-09-27 21:18:17 +0000439
440 std::vector<Value*> Idx;
Reid Spencerc635f472006-12-31 05:48:39 +0000441 Idx.push_back(Constant::getNullValue(Type::Int32Ty));
442 Idx.push_back(ConstantInt::get(Type::Int32Ty, 1));
Chris Lattner87eb2492005-09-27 21:18:17 +0000443 OldJmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "OldBuf",
444 EntryBB->getTerminator());
445
446 // Copy the JBListHead to the alloca.
447 Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
448 EntryBB->getTerminator());
449 new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
450
451 // Add the new jumpbuf to the list.
452 new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
453
454 // Create the catch block. The catch block is basically a big switch
455 // statement that goes to all of the invoke catch blocks.
456 BasicBlock *CatchBB = new BasicBlock("setjmp.catch", &F);
457
458 // Create an alloca which keeps track of which invoke is currently
459 // executing. For normal calls it contains zero.
Reid Spencerc635f472006-12-31 05:48:39 +0000460 AllocaInst *InvokeNum = new AllocaInst(Type::Int32Ty, 0, "invokenum",
Chris Lattner87eb2492005-09-27 21:18:17 +0000461 EntryBB->begin());
Reid Spencerc635f472006-12-31 05:48:39 +0000462 new StoreInst(ConstantInt::get(Type::Int32Ty, 0), InvokeNum, true,
Chris Lattner87eb2492005-09-27 21:18:17 +0000463 EntryBB->getTerminator());
464
465 // Insert a load in the Catch block, and a switch on its value. By default,
466 // we go to a block that just does an unwind (which is the correct action
467 // for a standard call).
468 BasicBlock *UnwindBB = new BasicBlock("unwindbb", &F);
469 Unwinds.push_back(new UnwindInst(UnwindBB));
470
471 Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
472 SwitchInst *CatchSwitch =
473 new SwitchInst(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
474
475 // Now that things are set up, insert the setjmp call itself.
476
477 // Split the entry block to insert the conditional branch for the setjmp.
478 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
479 "setjmp.cont");
480
Reid Spencerc635f472006-12-31 05:48:39 +0000481 Idx[1] = ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner87eb2492005-09-27 21:18:17 +0000482 Value *JmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "TheJmpBuf",
483 EntryBB->getTerminator());
484 Value *SJRet = new CallInst(SetJmpFn, JmpBufPtr, "sjret",
485 EntryBB->getTerminator());
486
487 // Compare the return value to zero.
Reid Spencer266e42b2006-12-23 06:05:41 +0000488 Value *IsNormal = new ICmpInst(ICmpInst::ICMP_EQ, SJRet,
489 Constant::getNullValue(SJRet->getType()),
490 "notunwind", EntryBB->getTerminator());
Chris Lattner87eb2492005-09-27 21:18:17 +0000491 // Nuke the uncond branch.
492 EntryBB->getTerminator()->eraseFromParent();
493
494 // Put in a new condbranch in its place.
495 new BranchInst(ContBlock, CatchBB, IsNormal, EntryBB);
496
497 // At this point, we are all set up, rewrite each invoke instruction.
498 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
499 rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, CatchSwitch);
500 }
501
502 // We know that there is at least one unwind.
503
504 // Create three new blocks, the block to load the jmpbuf ptr and compare
505 // against null, the block to do the longjmp, and the error block for if it
506 // is null. Add them at the end of the function because they are not hot.
507 BasicBlock *UnwindHandler = new BasicBlock("dounwind", &F);
508 BasicBlock *UnwindBlock = new BasicBlock("unwind", &F);
509 BasicBlock *TermBlock = new BasicBlock("unwinderror", &F);
510
511 // If this function contains an invoke, restore the old jumpbuf ptr.
512 Value *BufPtr;
513 if (OldJmpBufPtr) {
514 // Before the return, insert a copy from the saved value to the new value.
515 BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
516 new StoreInst(BufPtr, JBListHead, UnwindHandler);
517 } else {
518 BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
519 }
520
521 // Load the JBList, if it's null, then there was no catch!
Reid Spencer266e42b2006-12-23 06:05:41 +0000522 Value *NotNull = new ICmpInst(ICmpInst::ICMP_NE, BufPtr,
523 Constant::getNullValue(BufPtr->getType()),
524 "notnull", UnwindHandler);
Chris Lattner87eb2492005-09-27 21:18:17 +0000525 new BranchInst(UnwindBlock, TermBlock, NotNull, UnwindHandler);
526
527 // Create the block to do the longjmp.
528 // Get a pointer to the jmpbuf and longjmp.
529 std::vector<Value*> Idx;
Reid Spencerc635f472006-12-31 05:48:39 +0000530 Idx.push_back(Constant::getNullValue(Type::Int32Ty));
531 Idx.push_back(ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner87eb2492005-09-27 21:18:17 +0000532 Idx[0] = new GetElementPtrInst(BufPtr, Idx, "JmpBuf", UnwindBlock);
Reid Spencerc635f472006-12-31 05:48:39 +0000533 Idx[1] = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattner87eb2492005-09-27 21:18:17 +0000534 new CallInst(LongJmpFn, Idx, "", UnwindBlock);
535 new UnreachableInst(UnwindBlock);
536
537 // Set up the term block ("throw without a catch").
538 new UnreachableInst(TermBlock);
539
540 // Insert a new call to write(2, AbortMessage, AbortMessageLength);
541 writeAbortMessage(TermBlock->getTerminator());
542
543 // Insert a call to abort()
544 (new CallInst(AbortFn, std::vector<Value*>(), "",
545 TermBlock->getTerminator()))->setTailCall();
546
547
548 // Replace all unwinds with a branch to the unwind handler.
549 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
550 new BranchInst(UnwindHandler, Unwinds[i]);
551 Unwinds[i]->eraseFromParent();
552 }
553
554 // Finally, for any returns from this function, if this function contains an
555 // invoke, restore the old jmpbuf pointer to its input value.
556 if (OldJmpBufPtr) {
557 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
558 ReturnInst *R = Returns[i];
559
560 // Before the return, insert a copy from the saved value to the new value.
561 Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
562 new StoreInst(OldBuf, JBListHead, true, R);
563 }
564 }
565
566 return true;
Chris Lattner108cadc2004-02-08 19:53:56 +0000567}
568
569bool LowerInvoke::runOnFunction(Function &F) {
570 if (ExpensiveEHSupport)
571 return insertExpensiveEHSupport(F);
572 else
573 return insertCheapEHSupport(F);
574}