blob: 3450316721c76b3f2d782b3568cbde8664146c50 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Chris Lattnerd216e8b2006-12-19 22:17:40 +000037#define DEBUG_TYPE "lowerinvoke"
Chris Lattner86e44452003-10-05 19:14:42 +000038#include "llvm/Transforms/Scalar.h"
Chris Lattnere1c09302004-02-08 07:30:29 +000039#include "llvm/Constants.h"
40#include "llvm/DerivedTypes.h"
Chris Lattner6d784572004-02-08 19:53:56 +000041#include "llvm/Instructions.h"
Duncan Sandsa1220432008-04-07 13:41:19 +000042#include "llvm/Intrinsics.h"
Owen Anderson0a205a42009-07-05 22:41:43 +000043#include "llvm/LLVMContext.h"
Chris Lattnere1c09302004-02-08 07:30:29 +000044#include "llvm/Module.h"
Chris Lattner86e44452003-10-05 19:14:42 +000045#include "llvm/Pass.h"
Chris Lattner6d784572004-02-08 19:53:56 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +000047#include "llvm/Transforms/Utils/Local.h"
Jim Grosbach601f9d62010-06-01 17:56:41 +000048#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000049#include "llvm/ADT/Statistic.h"
50#include "llvm/Support/CommandLine.h"
Duraid Madina2a0013f2006-09-04 06:21:35 +000051#include "llvm/Target/TargetLowering.h"
Chris Lattner6d784572004-02-08 19:53:56 +000052#include <csetjmp>
Reid Spencer6734b572007-02-04 00:40:42 +000053#include <set>
Chris Lattnerdead9932003-12-10 20:22:42 +000054using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000055
Chris Lattnerd216e8b2006-12-19 22:17:40 +000056STATISTIC(NumInvokes, "Number of invokes replaced");
57STATISTIC(NumUnwinds, "Number of unwinds replaced");
58STATISTIC(NumSpilled, "Number of registers live across unwind edges");
59
60static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
Chris Lattner6d784572004-02-08 19:53:56 +000061 cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
Chris Lattner86e44452003-10-05 19:14:42 +000062
Chris Lattnerd216e8b2006-12-19 22:17:40 +000063namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000064 class LowerInvoke : public FunctionPass {
Chris Lattner6d784572004-02-08 19:53:56 +000065 // Used for both models.
Chris Lattnerb76efb72007-01-07 08:12:01 +000066 Constant *AbortFn;
Chris Lattner6d784572004-02-08 19:53:56 +000067
68 // Used for expensive EH support.
Chris Lattner1afcace2011-07-09 17:41:24 +000069 StructType *JBLinkTy;
Chris Lattner6d784572004-02-08 19:53:56 +000070 GlobalVariable *JBListHead;
Chris Lattnerc6f0aad2010-04-26 23:49:32 +000071 Constant *SetJmpFn, *LongJmpFn, *StackSaveFn, *StackRestoreFn;
72 bool useExpensiveEHSupport;
Jim Grosbach46445382009-04-17 23:30:55 +000073
Duraid Madina2a0013f2006-09-04 06:21:35 +000074 // We peek in TLI to grab the target's jmp_buf size and alignment
75 const TargetLowering *TLI;
Jim Grosbach46445382009-04-17 23:30:55 +000076
Chris Lattner86e44452003-10-05 19:14:42 +000077 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000078 static char ID; // Pass identification, replacement for typeid
Chris Lattnerc6f0aad2010-04-26 23:49:32 +000079 explicit LowerInvoke(const TargetLowering *tli = NULL,
80 bool useExpensiveEHSupport = ExpensiveEHSupport)
Owen Anderson90c579d2010-08-06 18:33:48 +000081 : FunctionPass(ID), useExpensiveEHSupport(useExpensiveEHSupport),
Owen Anderson081c34b2010-10-19 17:21:58 +000082 TLI(tli) {
83 initializeLowerInvokePass(*PassRegistry::getPassRegistry());
84 }
Chris Lattner86e44452003-10-05 19:14:42 +000085 bool doInitialization(Module &M);
86 bool runOnFunction(Function &F);
Jim Grosbach46445382009-04-17 23:30:55 +000087
Chris Lattnered96fe82006-05-17 21:05:27 +000088 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Anton Korobeynikovbed29462007-04-16 18:10:23 +000089 // This is a cluster of orthogonal Transforms
Dan Gohman60493c32010-08-06 21:48:06 +000090 AU.addPreserved("mem2reg");
Chris Lattnered96fe82006-05-17 21:05:27 +000091 AU.addPreservedID(LowerSwitchID);
Chris Lattnered96fe82006-05-17 21:05:27 +000092 }
Jim Grosbach46445382009-04-17 23:30:55 +000093
Chris Lattner6d784572004-02-08 19:53:56 +000094 private:
95 bool insertCheapEHSupport(Function &F);
Jim Grosbachaeafb372010-06-01 21:06:46 +000096 void splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*>&Invokes);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +000097 void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
Chris Lattnerc6f0aad2010-04-26 23:49:32 +000098 AllocaInst *InvokeNum, AllocaInst *StackPtr,
99 SwitchInst *CatchSwitch);
Chris Lattner6d784572004-02-08 19:53:56 +0000100 bool insertExpensiveEHSupport(Function &F);
Chris Lattner86e44452003-10-05 19:14:42 +0000101 };
Chris Lattner86e44452003-10-05 19:14:42 +0000102}
103
Dan Gohman844731a2008-05-13 00:00:25 +0000104char LowerInvoke::ID = 0;
Owen Anderson02dd53e2010-08-23 17:52:01 +0000105INITIALIZE_PASS(LowerInvoke, "lowerinvoke",
106 "Lower invoke and unwind, for unwindless code generators",
Owen Andersonce665bd2010-10-07 22:25:06 +0000107 false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000108
Owen Anderson90c579d2010-08-06 18:33:48 +0000109char &llvm::LowerInvokePassID = LowerInvoke::ID;
Chris Lattnercefc18e2004-02-13 16:16:16 +0000110
Brian Gaeked0fde302003-11-11 22:41:34 +0000111// Public Interface To the LowerInvoke pass.
Jim Grosbach46445382009-04-17 23:30:55 +0000112FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI) {
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000113 return new LowerInvoke(TLI, ExpensiveEHSupport);
114}
115FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI,
116 bool useExpensiveEHSupport) {
117 return new LowerInvoke(TLI, useExpensiveEHSupport);
Nate Begeman14b05292005-11-05 09:21:28 +0000118}
Chris Lattner86e44452003-10-05 19:14:42 +0000119
120// doInitialization - Make sure that there is a prototype for abort in the
121// current module.
122bool LowerInvoke::doInitialization(Module &M) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000123 const Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000124 if (useExpensiveEHSupport) {
Jim Laskey7d485382007-02-22 16:21:18 +0000125 // Insert a type for the linked list of jump buffers.
126 unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
127 JBSize = JBSize ? JBSize : 200;
Chris Lattner1afcace2011-07-09 17:41:24 +0000128 Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
Chris Lattnere1c09302004-02-08 07:30:29 +0000129
Chris Lattner1afcace2011-07-09 17:41:24 +0000130 JBLinkTy = StructType::createNamed(M.getContext(), "llvm.sjljeh.jmpbufty");
131 Type *Elts[] = { JmpBufTy, PointerType::getUnqual(JBLinkTy) };
132 JBLinkTy->setBody(Elts);
Chris Lattner6d784572004-02-08 19:53:56 +0000133
Owen Andersondebcb012009-07-29 22:17:13 +0000134 const Type *PtrJBList = PointerType::getUnqual(JBLinkTy);
Jim Laskey7d485382007-02-22 16:21:18 +0000135
136 // Now that we've done that, insert the jmpbuf list head global, unless it
137 // already exists.
138 if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) {
Owen Andersone9b11b42009-07-08 19:03:57 +0000139 JBListHead = new GlobalVariable(M, PtrJBList, false,
Duncan Sands667d4b82009-03-07 15:45:40 +0000140 GlobalValue::LinkOnceAnyLinkage,
Owen Andersona7235ea2009-07-31 20:28:14 +0000141 Constant::getNullValue(PtrJBList),
Owen Andersone9b11b42009-07-08 19:03:57 +0000142 "llvm.sjljeh.jblist");
Jim Laskey7d485382007-02-22 16:21:18 +0000143 }
Chuck Rose IIIcc51c312008-04-15 21:27:11 +0000144
Michael J. Spencer1f409602010-09-24 19:48:47 +0000145// VisualStudio defines setjmp as _setjmp
146#if defined(_MSC_VER) && defined(setjmp) && \
147 !defined(setjmp_undefined_for_msvc)
148# pragma push_macro("setjmp")
149# undef setjmp
150# define setjmp_undefined_for_msvc
Chuck Rose IIIcc51c312008-04-15 21:27:11 +0000151#endif
152
Duncan Sandsa1220432008-04-07 13:41:19 +0000153 SetJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::setjmp);
Chuck Rose IIIcc51c312008-04-15 21:27:11 +0000154
Michael J. Spencer1f409602010-09-24 19:48:47 +0000155#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
156 // let's return it to _setjmp state
157# pragma pop_macro("setjmp")
158# undef setjmp_undefined_for_msvc
Chuck Rose IIIcc51c312008-04-15 21:27:11 +0000159#endif
160
Duncan Sandsa1220432008-04-07 13:41:19 +0000161 LongJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::longjmp);
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000162 StackSaveFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
163 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Chris Lattner6d784572004-02-08 19:53:56 +0000164 }
Jim Laskey7d485382007-02-22 16:21:18 +0000165
166 // We need the 'write' and 'abort' functions for both models.
Owen Anderson1d0be152009-08-13 21:58:54 +0000167 AbortFn = M.getOrInsertFunction("abort", Type::getVoidTy(M.getContext()),
168 (Type *)0);
Chris Lattner86e44452003-10-05 19:14:42 +0000169 return true;
170}
171
Chris Lattner6d784572004-02-08 19:53:56 +0000172bool LowerInvoke::insertCheapEHSupport(Function &F) {
Chris Lattner86e44452003-10-05 19:14:42 +0000173 bool Changed = false;
Chris Lattnerdead9932003-12-10 20:22:42 +0000174 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
175 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Jim Grosbach601f9d62010-06-01 17:56:41 +0000176 SmallVector<Value*,16> CallArgs(II->op_begin(), II->op_end() - 3);
Chris Lattner86e44452003-10-05 19:14:42 +0000177 // Insert a normal call instruction...
Gabor Greif051a9502008-04-06 20:25:17 +0000178 CallInst *NewCall = CallInst::Create(II->getCalledValue(),
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000179 CallArgs.begin(), CallArgs.end(),
180 "",II);
Chris Lattner86cc4232007-02-11 01:37:51 +0000181 NewCall->takeName(II);
Chris Lattnerefd91682005-05-13 06:27:02 +0000182 NewCall->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000183 NewCall->setAttributes(II->getAttributes());
Devang Patel3bcb3a62010-10-18 18:53:44 +0000184 NewCall->setDebugLoc(II->getDebugLoc());
Chris Lattner86e44452003-10-05 19:14:42 +0000185 II->replaceAllUsesWith(NewCall);
Misha Brukmanfd939082005-04-21 23:48:37 +0000186
Chris Lattnerdead9932003-12-10 20:22:42 +0000187 // Insert an unconditional branch to the normal destination.
Gabor Greif051a9502008-04-06 20:25:17 +0000188 BranchInst::Create(II->getNormalDest(), II);
Chris Lattner86e44452003-10-05 19:14:42 +0000189
Chris Lattnerdead9932003-12-10 20:22:42 +0000190 // Remove any PHI node entries from the exception destination.
Chris Lattneraeb2a1d2004-02-08 21:44:31 +0000191 II->getUnwindDest()->removePredecessor(BB);
Chris Lattnerdead9932003-12-10 20:22:42 +0000192
Chris Lattner86e44452003-10-05 19:14:42 +0000193 // Remove the invoke instruction now.
Chris Lattnerdead9932003-12-10 20:22:42 +0000194 BB->getInstList().erase(II);
Chris Lattner86e44452003-10-05 19:14:42 +0000195
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000196 ++NumInvokes; Changed = true;
Chris Lattnerdead9932003-12-10 20:22:42 +0000197 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattner86e44452003-10-05 19:14:42 +0000198 // Insert a call to abort()
Gabor Greif051a9502008-04-06 20:25:17 +0000199 CallInst::Create(AbortFn, "", UI)->setTailCall();
Chris Lattner86e44452003-10-05 19:14:42 +0000200
Chris Lattner6d784572004-02-08 19:53:56 +0000201 // Insert a return instruction. This really should be a "barrier", as it
202 // is unreachable.
Owen Anderson1d0be152009-08-13 21:58:54 +0000203 ReturnInst::Create(F.getContext(),
Benjamin Kramerf0127052010-01-05 13:12:22 +0000204 F.getReturnType()->isVoidTy() ?
Owen Anderson1d0be152009-08-13 21:58:54 +0000205 0 : Constant::getNullValue(F.getReturnType()), UI);
Chris Lattner86e44452003-10-05 19:14:42 +0000206
207 // Remove the unwind instruction now.
Chris Lattnerdead9932003-12-10 20:22:42 +0000208 BB->getInstList().erase(UI);
Chris Lattner86e44452003-10-05 19:14:42 +0000209
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000210 ++NumUnwinds; Changed = true;
Chris Lattner86e44452003-10-05 19:14:42 +0000211 }
212 return Changed;
213}
Chris Lattner6d784572004-02-08 19:53:56 +0000214
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000215/// rewriteExpensiveInvoke - Insert code and hack the function to replace the
216/// specified invoke instruction with a call.
217void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
218 AllocaInst *InvokeNum,
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000219 AllocaInst *StackPtr,
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000220 SwitchInst *CatchSwitch) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000221 ConstantInt *InvokeNoC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
222 InvokeNo);
Chris Lattner6d784572004-02-08 19:53:56 +0000223
Chris Lattner8c5c22f2008-02-14 19:18:13 +0000224 // If the unwind edge has phi nodes, split the edge.
225 if (isa<PHINode>(II->getUnwindDest()->begin())) {
226 SplitCriticalEdge(II, 1, this);
Jim Grosbach46445382009-04-17 23:30:55 +0000227
Chris Lattner8c5c22f2008-02-14 19:18:13 +0000228 // If there are any phi nodes left, they must have a single predecessor.
229 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
230 PN->replaceAllUsesWith(PN->getIncomingValue(0));
231 PN->eraseFromParent();
232 }
233 }
Jim Grosbach46445382009-04-17 23:30:55 +0000234
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000235 // Insert a store of the invoke num before the invoke and store zero into the
236 // location afterward.
237 new StoreInst(InvokeNoC, InvokeNum, true, II); // volatile
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000238
239 // Insert a store of the stack ptr before the invoke, so we can restore it
240 // later in the exception case.
241 CallInst* StackSaveRet = CallInst::Create(StackSaveFn, "ssret", II);
242 new StoreInst(StackSaveRet, StackPtr, true, II); // volatile
Jim Grosbach46445382009-04-17 23:30:55 +0000243
Dan Gohman02dea8b2008-05-23 21:05:58 +0000244 BasicBlock::iterator NI = II->getNormalDest()->getFirstNonPHI();
Chris Lattner93e50ce2005-09-29 17:44:20 +0000245 // nonvolatile.
Owen Anderson1d0be152009-08-13 21:58:54 +0000246 new StoreInst(Constant::getNullValue(Type::getInt32Ty(II->getContext())),
247 InvokeNum, false, NI);
Jim Grosbach46445382009-04-17 23:30:55 +0000248
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000249 Instruction* StackPtrLoad = new LoadInst(StackPtr, "stackptr.restore", true,
250 II->getUnwindDest()->getFirstNonPHI()
251 );
252 CallInst::Create(StackRestoreFn, StackPtrLoad, "")->insertAfter(StackPtrLoad);
253
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000254 // Add a switch case to our unwind block.
255 CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
Jim Grosbach46445382009-04-17 23:30:55 +0000256
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000257 // Insert a normal call instruction.
Jim Grosbach601f9d62010-06-01 17:56:41 +0000258 SmallVector<Value*,16> CallArgs(II->op_begin(), II->op_end() - 3);
Gabor Greif051a9502008-04-06 20:25:17 +0000259 CallInst *NewCall = CallInst::Create(II->getCalledValue(),
260 CallArgs.begin(), CallArgs.end(), "",
261 II);
Chris Lattner86cc4232007-02-11 01:37:51 +0000262 NewCall->takeName(II);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000263 NewCall->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000264 NewCall->setAttributes(II->getAttributes());
Devang Patel3bcb3a62010-10-18 18:53:44 +0000265 NewCall->setDebugLoc(II->getDebugLoc());
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000266 II->replaceAllUsesWith(NewCall);
Jim Grosbach46445382009-04-17 23:30:55 +0000267
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000268 // Replace the invoke with an uncond branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000269 BranchInst::Create(II->getNormalDest(), NewCall->getParent());
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000270 II->eraseFromParent();
271}
Chris Lattner6d784572004-02-08 19:53:56 +0000272
Chris Lattnerf4e6c3a2005-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.
Jim Grosbach46445382009-04-17 23:30:55 +0000277
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000278 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Jim Grosbach46445382009-04-17 23:30:55 +0000279 MarkBlocksLiveIn(*PI, LiveBBs);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000280}
Chris Lattner6d784572004-02-08 19:53:56 +0000281
Chris Lattnerf4e6c3a2005-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::
Jim Grosbachaeafb372010-06-01 21:06:46 +0000288splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*> &Invokes) {
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000289 // 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 Lattner6d784572004-02-08 19:53:56 +0000297 }
298
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000299 Function *F = Invokes.back()->getParent()->getParent();
Jim Grosbach46445382009-04-17 23:30:55 +0000300
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000301 // To avoid having to handle incoming arguments specially, we lower each arg
Reid Spencer3da59db2006-11-27 01:05:10 +0000302 // to a copy instruction in the entry block. This ensures that the argument
Chris Lattnerf4e6c3a2005-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) {
Jim Grosbach0fd8b622010-06-01 18:04:56 +0000310 const Type *Ty = AI->getType();
Jim Grosbach7fa1bba2010-06-30 22:22:59 +0000311 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbach0fd8b622010-06-01 18:04:56 +0000312 // to handle them differently. We use an extract/insert pair as a
313 // lightweight method to achieve the same goal.
Jim Grosbach7fa1bba2010-06-30 22:22:59 +0000314 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
315 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbach0fd8b622010-06-01 18:04:56 +0000316 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
317 NI->insertAfter(EI);
318 AI->replaceAllUsesWith(NI);
Jim Grosbach7fa1bba2010-06-30 22:22:59 +0000319 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbach0fd8b622010-06-01 18:04:56 +0000320 EI->setOperand(0, AI);
321 NI->setOperand(0, AI);
322 } else {
323 // This is always a no-op cast because we're casting AI to AI->getType()
324 // so src and destination types are identical. BitCast is the only
325 // possibility.
326 CastInst *NC = new BitCastInst(
327 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
328 AI->replaceAllUsesWith(NC);
329 // Set the operand of the cast instruction back to the AllocaInst.
330 // Normally it's forbidden to replace a CastInst's operand because it
331 // could cause the opcode to reflect an illegal conversion. However,
332 // we're replacing it here with the same value it was constructed with.
333 // We do this because the above replaceAllUsesWith() clobbered the
334 // operand, but we want this one to remain.
335 NC->setOperand(0, AI);
336 }
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000337 }
Jim Grosbach46445382009-04-17 23:30:55 +0000338
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000339 // Finally, scan the code looking for instructions with bad live ranges.
340 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
341 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
342 // Ignore obvious cases we don't have to handle. In particular, most
343 // instructions either have no uses or only have a single use inside the
344 // current block. Ignore them quickly.
345 Instruction *Inst = II;
346 if (Inst->use_empty()) continue;
347 if (Inst->hasOneUse() &&
348 cast<Instruction>(Inst->use_back())->getParent() == BB &&
349 !isa<PHINode>(Inst->use_back())) continue;
Jim Grosbach46445382009-04-17 23:30:55 +0000350
Chris Lattner45313712005-09-27 21:33:12 +0000351 // If this is an alloca in the entry block, it's not a real register
352 // value.
353 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
354 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
355 continue;
Jim Grosbach46445382009-04-17 23:30:55 +0000356
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000357 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach601f9d62010-06-01 17:56:41 +0000358 SmallVector<Instruction*,16> Users;
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000359 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
360 UI != E; ++UI) {
361 Instruction *User = cast<Instruction>(*UI);
362 if (User->getParent() != BB || isa<PHINode>(User))
363 Users.push_back(User);
364 }
365
366 // Scan all of the uses and see if the live range is live across an unwind
367 // edge. If we find a use live across an invoke edge, create an alloca
368 // and spill the value.
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000369 std::set<InvokeInst*> InvokesWithStoreInserted;
370
371 // Find all of the blocks that this value is live in.
372 std::set<BasicBlock*> LiveBBs;
373 LiveBBs.insert(Inst->getParent());
374 while (!Users.empty()) {
375 Instruction *U = Users.back();
376 Users.pop_back();
Jim Grosbach46445382009-04-17 23:30:55 +0000377
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000378 if (!isa<PHINode>(U)) {
379 MarkBlocksLiveIn(U->getParent(), LiveBBs);
380 } else {
381 // Uses for a PHI node occur in their predecessor block.
382 PHINode *PN = cast<PHINode>(U);
383 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
384 if (PN->getIncomingValue(i) == Inst)
385 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
386 }
387 }
Jim Grosbach46445382009-04-17 23:30:55 +0000388
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000389 // Now that we know all of the blocks that this thing is live in, see if
390 // it includes any of the unwind locations.
391 bool NeedsSpill = false;
392 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
393 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
394 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
395 NeedsSpill = true;
396 }
397 }
398
399 // If we decided we need a spill, do it.
400 if (NeedsSpill) {
401 ++NumSpilled;
Owen Anderson50dead02009-07-15 23:53:25 +0000402 DemoteRegToStack(*Inst, true);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000403 }
404 }
405}
406
407bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
Jim Grosbach601f9d62010-06-01 17:56:41 +0000408 SmallVector<ReturnInst*,16> Returns;
409 SmallVector<UnwindInst*,16> Unwinds;
410 SmallVector<InvokeInst*,16> Invokes;
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000411
412 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
413 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
414 // Remember all return instructions in case we insert an invoke into this
415 // function.
416 Returns.push_back(RI);
417 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
418 Invokes.push_back(II);
419 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
420 Unwinds.push_back(UI);
421 }
422
423 if (Unwinds.empty() && Invokes.empty()) return false;
424
425 NumInvokes += Invokes.size();
426 NumUnwinds += Unwinds.size();
Jim Grosbach46445382009-04-17 23:30:55 +0000427
Chris Lattner5b3c7022005-09-27 22:44:59 +0000428 // TODO: This is not an optimal way to do this. In particular, this always
429 // inserts setjmp calls into the entries of functions with invoke instructions
430 // even though there are possibly paths through the function that do not
431 // execute any invokes. In particular, for functions with early exits, e.g.
432 // the 'addMove' method in hexxagon, it would be nice to not have to do the
433 // setjmp stuff on the early exit path. This requires a bit of dataflow, but
434 // would not be too hard to do.
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000435
436 // If we have an invoke instruction, insert a setjmp that dominates all
437 // invokes. After the setjmp, use a cond branch that goes to the original
438 // code path on zero, and to a designated 'catch' block of nonzero.
439 Value *OldJmpBufPtr = 0;
440 if (!Invokes.empty()) {
441 // First thing we need to do is scan the whole function for values that are
442 // live across unwind edges. Each value that is live across an unwind edge
443 // we spill into a stack location, guaranteeing that there is nothing live
444 // across the unwind edge. This process also splits all critical edges
445 // coming out of invoke's.
Jim Grosbach46445382009-04-17 23:30:55 +0000446 splitLiveRangesLiveAcrossInvokes(Invokes);
447
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000448 BasicBlock *EntryBB = F.begin();
Jim Grosbach46445382009-04-17 23:30:55 +0000449
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000450 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
451 // that needs to be restored on all exits from the function. This is an
452 // alloca because the value needs to be live across invokes.
Chris Lattner97d2dbd2006-09-05 17:48:07 +0000453 unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0;
Jim Grosbach46445382009-04-17 23:30:55 +0000454 AllocaInst *JmpBuf =
Owen Anderson50dead02009-07-15 23:53:25 +0000455 new AllocaInst(JBLinkTy, 0, Align,
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000456 "jblink", F.begin()->begin());
Jim Grosbach46445382009-04-17 23:30:55 +0000457
Jim Grosbachaeafb372010-06-01 21:06:46 +0000458 Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())),
459 ConstantInt::get(Type::getInt32Ty(F.getContext()), 1) };
460 OldJmpBufPtr = GetElementPtrInst::Create(JmpBuf, &Idx[0], &Idx[2],
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000461 "OldBuf",
Jim Grosbachaeafb372010-06-01 21:06:46 +0000462 EntryBB->getTerminator());
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000463
464 // Copy the JBListHead to the alloca.
465 Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
466 EntryBB->getTerminator());
467 new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
Jim Grosbach46445382009-04-17 23:30:55 +0000468
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000469 // Add the new jumpbuf to the list.
470 new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
471
472 // Create the catch block. The catch block is basically a big switch
473 // statement that goes to all of the invoke catch blocks.
Owen Anderson1d0be152009-08-13 21:58:54 +0000474 BasicBlock *CatchBB =
475 BasicBlock::Create(F.getContext(), "setjmp.catch", &F);
Jim Grosbach46445382009-04-17 23:30:55 +0000476
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000477 // Create an alloca which keeps track of the stack pointer before every
478 // invoke, this allows us to properly restore the stack pointer after
479 // long jumping.
480 AllocaInst *StackPtr = new AllocaInst(Type::getInt8PtrTy(F.getContext()), 0,
481 "stackptr", EntryBB->begin());
482
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000483 // Create an alloca which keeps track of which invoke is currently
484 // executing. For normal calls it contains zero.
Owen Anderson1d0be152009-08-13 21:58:54 +0000485 AllocaInst *InvokeNum = new AllocaInst(Type::getInt32Ty(F.getContext()), 0,
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000486 "invokenum",EntryBB->begin());
Owen Anderson1d0be152009-08-13 21:58:54 +0000487 new StoreInst(ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
488 InvokeNum, true, EntryBB->getTerminator());
Jim Grosbach46445382009-04-17 23:30:55 +0000489
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000490 // Insert a load in the Catch block, and a switch on its value. By default,
491 // we go to a block that just does an unwind (which is the correct action
492 // for a standard call).
Owen Anderson1d0be152009-08-13 21:58:54 +0000493 BasicBlock *UnwindBB = BasicBlock::Create(F.getContext(), "unwindbb", &F);
494 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBB));
Jim Grosbach46445382009-04-17 23:30:55 +0000495
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000496 Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
Gabor Greif051a9502008-04-06 20:25:17 +0000497 SwitchInst *CatchSwitch =
498 SwitchInst::Create(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000499
500 // Now that things are set up, insert the setjmp call itself.
Jim Grosbach46445382009-04-17 23:30:55 +0000501
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000502 // Split the entry block to insert the conditional branch for the setjmp.
503 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
504 "setjmp.cont");
505
Owen Anderson1d0be152009-08-13 21:58:54 +0000506 Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 0);
Jim Grosbachaeafb372010-06-01 21:06:46 +0000507 Value *JmpBufPtr = GetElementPtrInst::Create(JmpBuf, &Idx[0], &Idx[2],
Gabor Greif051a9502008-04-06 20:25:17 +0000508 "TheJmpBuf",
509 EntryBB->getTerminator());
Owen Anderson1d0be152009-08-13 21:58:54 +0000510 JmpBufPtr = new BitCastInst(JmpBufPtr,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000511 Type::getInt8PtrTy(F.getContext()),
Duncan Sandsa1220432008-04-07 13:41:19 +0000512 "tmp", EntryBB->getTerminator());
Gabor Greif051a9502008-04-06 20:25:17 +0000513 Value *SJRet = CallInst::Create(SetJmpFn, JmpBufPtr, "sjret",
514 EntryBB->getTerminator());
Duncan Sandsa1220432008-04-07 13:41:19 +0000515
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000516 // Compare the return value to zero.
Owen Anderson333c4002009-07-09 23:48:35 +0000517 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
518 ICmpInst::ICMP_EQ, SJRet,
Owen Andersona7235ea2009-07-31 20:28:14 +0000519 Constant::getNullValue(SJRet->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +0000520 "notunwind");
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000521 // Nuke the uncond branch.
522 EntryBB->getTerminator()->eraseFromParent();
Jim Grosbach46445382009-04-17 23:30:55 +0000523
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000524 // Put in a new condbranch in its place.
Gabor Greif051a9502008-04-06 20:25:17 +0000525 BranchInst::Create(ContBlock, CatchBB, IsNormal, EntryBB);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000526
527 // At this point, we are all set up, rewrite each invoke instruction.
528 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000529 rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, StackPtr, CatchSwitch);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000530 }
531
532 // We know that there is at least one unwind.
Jim Grosbach46445382009-04-17 23:30:55 +0000533
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000534 // Create three new blocks, the block to load the jmpbuf ptr and compare
535 // against null, the block to do the longjmp, and the error block for if it
536 // is null. Add them at the end of the function because they are not hot.
Owen Anderson1d0be152009-08-13 21:58:54 +0000537 BasicBlock *UnwindHandler = BasicBlock::Create(F.getContext(),
538 "dounwind", &F);
539 BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwind", &F);
540 BasicBlock *TermBlock = BasicBlock::Create(F.getContext(), "unwinderror", &F);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000541
542 // If this function contains an invoke, restore the old jumpbuf ptr.
543 Value *BufPtr;
544 if (OldJmpBufPtr) {
545 // Before the return, insert a copy from the saved value to the new value.
546 BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
547 new StoreInst(BufPtr, JBListHead, UnwindHandler);
548 } else {
549 BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
550 }
Jim Grosbach46445382009-04-17 23:30:55 +0000551
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000552 // Load the JBList, if it's null, then there was no catch!
Owen Anderson333c4002009-07-09 23:48:35 +0000553 Value *NotNull = new ICmpInst(*UnwindHandler, ICmpInst::ICMP_NE, BufPtr,
Owen Andersona7235ea2009-07-31 20:28:14 +0000554 Constant::getNullValue(BufPtr->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +0000555 "notnull");
Gabor Greif051a9502008-04-06 20:25:17 +0000556 BranchInst::Create(UnwindBlock, TermBlock, NotNull, UnwindHandler);
Jim Grosbach46445382009-04-17 23:30:55 +0000557
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000558 // Create the block to do the longjmp.
559 // Get a pointer to the jmpbuf and longjmp.
Jim Grosbachaeafb372010-06-01 21:06:46 +0000560 Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())),
561 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0) };
562 Idx[0] = GetElementPtrInst::Create(BufPtr, &Idx[0], &Idx[2], "JmpBuf",
Gabor Greif051a9502008-04-06 20:25:17 +0000563 UnwindBlock);
Owen Anderson1d0be152009-08-13 21:58:54 +0000564 Idx[0] = new BitCastInst(Idx[0],
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000565 Type::getInt8PtrTy(F.getContext()),
Duncan Sandsa1220432008-04-07 13:41:19 +0000566 "tmp", UnwindBlock);
Owen Anderson1d0be152009-08-13 21:58:54 +0000567 Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 1);
Jim Grosbachaeafb372010-06-01 21:06:46 +0000568 CallInst::Create(LongJmpFn, &Idx[0], &Idx[2], "", UnwindBlock);
Owen Anderson1d0be152009-08-13 21:58:54 +0000569 new UnreachableInst(F.getContext(), UnwindBlock);
Jim Grosbach46445382009-04-17 23:30:55 +0000570
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000571 // Set up the term block ("throw without a catch").
Owen Anderson1d0be152009-08-13 21:58:54 +0000572 new UnreachableInst(F.getContext(), TermBlock);
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000573
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000574 // Insert a call to abort()
Gabor Greif051a9502008-04-06 20:25:17 +0000575 CallInst::Create(AbortFn, "",
576 TermBlock->getTerminator())->setTailCall();
Jim Grosbach46445382009-04-17 23:30:55 +0000577
578
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000579 // Replace all unwinds with a branch to the unwind handler.
580 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
Gabor Greif051a9502008-04-06 20:25:17 +0000581 BranchInst::Create(UnwindHandler, Unwinds[i]);
Jim Grosbach46445382009-04-17 23:30:55 +0000582 Unwinds[i]->eraseFromParent();
583 }
584
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000585 // Finally, for any returns from this function, if this function contains an
586 // invoke, restore the old jmpbuf pointer to its input value.
587 if (OldJmpBufPtr) {
588 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
589 ReturnInst *R = Returns[i];
Jim Grosbach46445382009-04-17 23:30:55 +0000590
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000591 // Before the return, insert a copy from the saved value to the new value.
592 Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
593 new StoreInst(OldBuf, JBListHead, true, R);
594 }
595 }
Jim Grosbach46445382009-04-17 23:30:55 +0000596
Chris Lattnerf4e6c3a2005-09-27 21:18:17 +0000597 return true;
Chris Lattner6d784572004-02-08 19:53:56 +0000598}
599
600bool LowerInvoke::runOnFunction(Function &F) {
Chris Lattnerc6f0aad2010-04-26 23:49:32 +0000601 if (useExpensiveEHSupport)
Chris Lattner6d784572004-02-08 19:53:56 +0000602 return insertExpensiveEHSupport(F);
603 else
604 return insertCheapEHSupport(F);
605}