blob: dc7ca2bd54b97ec663a3c1355252dccc1609716c [file] [log] [blame]
Bill Wendling12e5adb2012-03-13 20:04:21 +00001//===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
Jim Grosbach486be662009-08-17 16:41:22 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This transformation is designed for use by code generators which use SjLj
11// based exception handling.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "sjljehprepare"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Jim Grosbach486be662009-08-17 16:41:22 +000030#include "llvm/Pass.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000034#include "llvm/Target/TargetLowering.h"
35#include "llvm/Transforms/Scalar.h"
36#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Local.h"
Benjamin Kramer63abc842010-11-06 11:45:59 +000038#include <set>
Jim Grosbach486be662009-08-17 16:41:22 +000039using namespace llvm;
40
41STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach486be662009-08-17 16:41:22 +000042STATISTIC(NumSpilled, "Number of registers live across unwind edges");
43
44namespace {
Bill Wendling8faa30e2013-09-23 20:57:47 +000045class SjLjEHPrepare : public FunctionPass {
46 const TargetMachine *TM;
47 Type *FunctionContextTy;
48 Constant *RegisterFn;
49 Constant *UnregisterFn;
50 Constant *BuiltinSetjmpFn;
51 Constant *FrameAddrFn;
52 Constant *StackAddrFn;
53 Constant *StackRestoreFn;
54 Constant *LSDAAddrFn;
55 Value *PersonalityFn;
56 Constant *CallSiteFn;
57 Constant *FuncCtxFn;
58 AllocaInst *FuncCtx;
Jim Grosbach486be662009-08-17 16:41:22 +000059
Bill Wendling8faa30e2013-09-23 20:57:47 +000060public:
61 static char ID; // Pass identification, replacement for typeid
62 explicit SjLjEHPrepare(const TargetMachine *TM) : FunctionPass(ID), TM(TM) {}
Craig Topper4584cd52014-03-07 09:26:03 +000063 bool doInitialization(Module &M) override;
64 bool runOnFunction(Function &F) override;
Jim Grosbach486be662009-08-17 16:41:22 +000065
Craig Topper4584cd52014-03-07 09:26:03 +000066 void getAnalysisUsage(AnalysisUsage &AU) const override {}
67 const char *getPassName() const override {
Bill Wendling8faa30e2013-09-23 20:57:47 +000068 return "SJLJ Exception Handling preparation";
69 }
70
71private:
72 bool setupEntryBlockAndCallSites(Function &F);
73 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
74 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
75 void lowerIncomingArguments(Function &F);
76 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
77 void insertCallSiteStore(Instruction *I, int Number);
78};
Jim Grosbach486be662009-08-17 16:41:22 +000079} // end anonymous namespace
80
Bill Wendling12e5adb2012-03-13 20:04:21 +000081char SjLjEHPrepare::ID = 0;
Jim Grosbach486be662009-08-17 16:41:22 +000082
Bill Wendling12e5adb2012-03-13 20:04:21 +000083// Public Interface To the SjLjEHPrepare pass.
Bill Wendlingafc10362013-06-19 20:51:24 +000084FunctionPass *llvm::createSjLjEHPreparePass(const TargetMachine *TM) {
85 return new SjLjEHPrepare(TM);
Jim Grosbach486be662009-08-17 16:41:22 +000086}
Jim Grosbach1b0436b2009-08-23 18:13:48 +000087// doInitialization - Set up decalarations and types needed to process
88// exceptions.
Bill Wendling12e5adb2012-03-13 20:04:21 +000089bool SjLjEHPrepare::doInitialization(Module &M) {
Jim Grosbach486be662009-08-17 16:41:22 +000090 // Build the function context structure.
91 // builtin_setjmp uses a five word jbuf
Jay Foadb804a2b2011-07-12 14:06:48 +000092 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
93 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Bill Wendling8faa30e2013-09-23 20:57:47 +000094 FunctionContextTy = StructType::get(VoidPtrTy, // __prev
95 Int32Ty, // call_site
96 ArrayType::get(Int32Ty, 4), // __data
97 VoidPtrTy, // __personality
98 VoidPtrTy, // __lsda
99 ArrayType::get(VoidPtrTy, 5), // __jbuf
100 NULL);
101 RegisterFn = M.getOrInsertFunction(
102 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
103 PointerType::getUnqual(FunctionContextTy), (Type *)0);
104 UnregisterFn = M.getOrInsertFunction(
105 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
106 PointerType::getUnqual(FunctionContextTy), (Type *)0);
Jim Grosbach486be662009-08-17 16:41:22 +0000107 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbachfaa3abb2010-05-27 23:49:24 +0000108 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
Bob Wilson643e63c2011-11-16 07:12:00 +0000109 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach486be662009-08-17 16:41:22 +0000110 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
111 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Jim Grosbach54c05302010-01-28 01:45:32 +0000112 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Bill Wendling899da522011-09-28 21:56:53 +0000113 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Jim Grosbach1b0436b2009-08-23 18:13:48 +0000114 PersonalityFn = 0;
Jim Grosbach486be662009-08-17 16:41:22 +0000115
116 return true;
117}
118
Jim Grosbach1201f292010-03-04 22:07:46 +0000119/// insertCallSiteStore - Insert a store of the call-site value to the
120/// function context
Bill Wendling12e5adb2012-03-13 20:04:21 +0000121void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000122 IRBuilder<> Builder(I);
123
124 // Get a reference to the call_site field.
125 Type *Int32Ty = Type::getInt32Ty(I->getContext());
126 Value *Zero = ConstantInt::get(Int32Ty, 0);
127 Value *One = ConstantInt::get(Int32Ty, 1);
128 Value *Idxs[2] = { Zero, One };
129 Value *CallSite = Builder.CreateGEP(FuncCtx, Idxs, "call_site");
130
131 // Insert a store of the call-site number
Bill Wendling8faa30e2013-09-23 20:57:47 +0000132 ConstantInt *CallSiteNoC =
133 ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
134 Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
Jim Grosbach1201f292010-03-04 22:07:46 +0000135}
136
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000137/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
Jim Grosbach486be662009-08-17 16:41:22 +0000138/// we reach blocks we've already seen.
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000139static void MarkBlocksLiveIn(BasicBlock *BB,
Bill Wendling8faa30e2013-09-23 20:57:47 +0000140 SmallPtrSet<BasicBlock *, 64> &LiveBBs) {
141 if (!LiveBBs.insert(BB))
142 return; // already been here.
Jim Grosbach486be662009-08-17 16:41:22 +0000143
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000144 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
145 MarkBlocksLiveIn(*PI, LiveBBs);
Jim Grosbach486be662009-08-17 16:41:22 +0000146}
147
Bill Wendlingb108aae2011-12-14 22:45:33 +0000148/// substituteLPadValues - Substitute the values returned by the landingpad
149/// instruction with those returned by the personality function.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000150void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
151 Value *SelVal) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000152 SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
Bill Wendlingb108aae2011-12-14 22:45:33 +0000153 while (!UseWorkList.empty()) {
154 Value *Val = UseWorkList.pop_back_val();
155 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
Bill Wendling8faa30e2013-09-23 20:57:47 +0000156 if (!EVI)
157 continue;
158 if (EVI->getNumIndices() != 1)
159 continue;
Bill Wendlingb108aae2011-12-14 22:45:33 +0000160 if (*EVI->idx_begin() == 0)
161 EVI->replaceAllUsesWith(ExnVal);
162 else if (*EVI->idx_begin() == 1)
163 EVI->replaceAllUsesWith(SelVal);
164 if (EVI->getNumUses() == 0)
165 EVI->eraseFromParent();
166 }
167
Bill Wendling8faa30e2013-09-23 20:57:47 +0000168 if (LPI->getNumUses() == 0)
169 return;
Bill Wendlingb108aae2011-12-14 22:45:33 +0000170
171 // There are still some uses of LPI. Construct an aggregate with the exception
172 // values and replace the LPI with that aggregate.
173 Type *LPadType = LPI->getType();
174 Value *LPadVal = UndefValue::get(LPadType);
Bill Wendling8faa30e2013-09-23 20:57:47 +0000175 IRBuilder<> Builder(
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000176 std::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
Bill Wendlingb108aae2011-12-14 22:45:33 +0000177 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
178 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
179
180 LPI->replaceAllUsesWith(LPadVal);
181}
182
Bill Wendling2e76ca92011-09-28 03:14:05 +0000183/// setupFunctionContext - Allocate the function context on the stack and fill
184/// it with all of the data that we know at this point.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000185Value *SjLjEHPrepare::setupFunctionContext(Function &F,
186 ArrayRef<LandingPadInst *> LPads) {
Bill Wendling2e76ca92011-09-28 03:14:05 +0000187 BasicBlock *EntryBB = F.begin();
188
189 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
190 // that needs to be restored on all exits from the function. This is an alloca
191 // because the value needs to be added to the global context list.
Bill Wendlingafc10362013-06-19 20:51:24 +0000192 const TargetLowering *TLI = TM->getTargetLowering();
Bill Wendling2e76ca92011-09-28 03:14:05 +0000193 unsigned Align =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000194 TLI->getDataLayout()->getPrefTypeAlignment(FunctionContextTy);
195 FuncCtx = new AllocaInst(FunctionContextTy, 0, Align, "fn_context",
196 EntryBB->begin());
Bill Wendling2e76ca92011-09-28 03:14:05 +0000197
198 // Fill in the function context structure.
Bill Wendling2e76ca92011-09-28 03:14:05 +0000199 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
200 LandingPadInst *LPI = LPads[I];
201 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
202
Bill Wendling7717e9f2012-01-27 02:02:24 +0000203 // Reference the __data field.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000204 Value *FCData = Builder.CreateConstGEP2_32(FuncCtx, 0, 2, "__data");
Bill Wendling7717e9f2012-01-27 02:02:24 +0000205
206 // The exception values come back in context->__data[0].
Bill Wendling8faa30e2013-09-23 20:57:47 +0000207 Value *ExceptionAddr =
208 Builder.CreateConstGEP2_32(FCData, 0, 0, "exception_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000209 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000210 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
Bill Wendling7717e9f2012-01-27 02:02:24 +0000211
Bill Wendling8faa30e2013-09-23 20:57:47 +0000212 Value *SelectorAddr =
213 Builder.CreateConstGEP2_32(FCData, 0, 1, "exn_selector_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000214 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
215
Bill Wendlingb108aae2011-12-14 22:45:33 +0000216 substituteLPadValues(LPI, ExnVal, SelVal);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000217 }
218
219 // Personality function
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000220 IRBuilder<> Builder(EntryBB->getTerminator());
Bill Wendling2e76ca92011-09-28 03:14:05 +0000221 if (!PersonalityFn)
222 PersonalityFn = LPads[0]->getPersonalityFn();
Bill Wendling8faa30e2013-09-23 20:57:47 +0000223 Value *PersonalityFieldPtr =
224 Builder.CreateConstGEP2_32(FuncCtx, 0, 3, "pers_fn_gep");
225 Builder.CreateStore(
226 Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
227 PersonalityFieldPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000228
229 // LSDA address
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000230 Value *LSDA = Builder.CreateCall(LSDAAddrFn, "lsda_addr");
231 Value *LSDAFieldPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 4, "lsda_gep");
232 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000233
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000234 return FuncCtx;
Bill Wendling899da522011-09-28 21:56:53 +0000235}
236
Bill Wendlinge9574be2011-10-08 00:56:47 +0000237/// lowerIncomingArguments - To avoid having to handle incoming arguments
238/// specially, we lower each arg to a copy instruction in the entry block. This
239/// ensures that the argument value itself cannot be live out of the entry
240/// block.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000241void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000242 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
243 while (isa<AllocaInst>(AfterAllocaInsPt) &&
244 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
245 ++AfterAllocaInsPt;
246
Bill Wendling8faa30e2013-09-23 20:57:47 +0000247 for (Function::arg_iterator AI = F.arg_begin(), AE = F.arg_end(); AI != AE;
248 ++AI) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000249 Type *Ty = AI->getType();
250
251 // Aggregate types can't be cast, but are legal argument types, so we have
252 // to handle them differently. We use an extract/insert pair as a
253 // lightweight method to achieve the same goal.
Duncan P. N. Exon Smith50ed9af2014-01-21 22:46:46 +0000254 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000255 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
256 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
257 NI->insertAfter(EI);
258 AI->replaceAllUsesWith(NI);
259
260 // Set the operand of the instructions back to the AllocaInst.
261 EI->setOperand(0, AI);
262 NI->setOperand(0, AI);
263 } else {
264 // This is always a no-op cast because we're casting AI to AI->getType()
265 // so src and destination types are identical. BitCast is the only
266 // possibility.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000267 CastInst *NC = new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
268 AfterAllocaInsPt);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000269 AI->replaceAllUsesWith(NC);
270
271 // Set the operand of the cast instruction back to the AllocaInst.
272 // Normally it's forbidden to replace a CastInst's operand because it
273 // could cause the opcode to reflect an illegal conversion. However, we're
274 // replacing it here with the same value it was constructed with. We do
275 // this because the above replaceAllUsesWith() clobbered the operand, but
276 // we want this one to remain.
277 NC->setOperand(0, AI);
278 }
279 }
280}
281
282/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
283/// edge and spill them.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000284void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
Bill Wendling8faa30e2013-09-23 20:57:47 +0000285 ArrayRef<InvokeInst *> Invokes) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000286 // Finally, scan the code looking for instructions with bad live ranges.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000287 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
288 for (BasicBlock::iterator II = BB->begin(), IIE = BB->end(); II != IIE;
289 ++II) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000290 // Ignore obvious cases we don't have to handle. In particular, most
291 // instructions either have no uses or only have a single use inside the
292 // current block. Ignore them quickly.
293 Instruction *Inst = II;
Bill Wendling8faa30e2013-09-23 20:57:47 +0000294 if (Inst->use_empty())
295 continue;
Bill Wendlinge9574be2011-10-08 00:56:47 +0000296 if (Inst->hasOneUse() &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000297 cast<Instruction>(Inst->user_back())->getParent() == BB &&
298 !isa<PHINode>(Inst->user_back()))
Bill Wendling8faa30e2013-09-23 20:57:47 +0000299 continue;
Bill Wendlinge9574be2011-10-08 00:56:47 +0000300
301 // If this is an alloca in the entry block, it's not a real register
302 // value.
303 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
304 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
305 continue;
306
307 // Avoid iterator invalidation by copying users to a temporary vector.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000308 SmallVector<Instruction *, 16> Users;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000309 for (User *U : Inst->users()) {
310 Instruction *UI = cast<Instruction>(U);
311 if (UI->getParent() != BB || isa<PHINode>(UI))
312 Users.push_back(UI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000313 }
314
315 // Find all of the blocks that this value is live in.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000316 SmallPtrSet<BasicBlock *, 64> LiveBBs;
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000317 LiveBBs.insert(Inst->getParent());
Bill Wendlinge9574be2011-10-08 00:56:47 +0000318 while (!Users.empty()) {
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000319 Instruction *U = Users.back();
320 Users.pop_back();
Bill Wendlinge9574be2011-10-08 00:56:47 +0000321
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000322 if (!isa<PHINode>(U)) {
323 MarkBlocksLiveIn(U->getParent(), LiveBBs);
324 } else {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000325 // Uses for a PHI node occur in their predecessor block.
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000326 PHINode *PN = cast<PHINode>(U);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000327 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
328 if (PN->getIncomingValue(i) == Inst)
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000329 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000330 }
331 }
332
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000333 // Now that we know all of the blocks that this thing is live in, see if
334 // it includes any of the unwind locations.
335 bool NeedsSpill = false;
336 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
337 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
338 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
339 DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
Bill Wendling8faa30e2013-09-23 20:57:47 +0000340 << UnwindBlock->getName() << "\n");
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000341 NeedsSpill = true;
342 break;
Bill Wendlingd7c0aae2012-03-14 07:28:01 +0000343 }
Bill Wendling5ad91402012-03-12 20:19:41 +0000344 }
Bill Wendlingb1c43082011-10-21 22:08:56 +0000345
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000346 // If we decided we need a spill, do it.
347 // FIXME: Spilling this way is overkill, as it forces all uses of
348 // the value to be reloaded from the stack slot, even those that aren't
349 // in the unwind blocks. We should be more selective.
350 if (NeedsSpill) {
351 DemoteRegToStack(*Inst, true);
352 ++NumSpilled;
353 }
Bill Wendlingd7c0aae2012-03-14 07:28:01 +0000354 }
355 }
356
Bill Wendlingb1c43082011-10-21 22:08:56 +0000357 // Go through the landing pads and remove any PHIs there.
358 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
359 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
360 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
361
362 // Place PHIs into a set to avoid invalidating the iterator.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000363 SmallPtrSet<PHINode *, 8> PHIsToDemote;
364 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
Bill Wendlingb1c43082011-10-21 22:08:56 +0000365 PHIsToDemote.insert(cast<PHINode>(PN));
Bill Wendling8faa30e2013-09-23 20:57:47 +0000366 if (PHIsToDemote.empty())
367 continue;
Bill Wendlingb1c43082011-10-21 22:08:56 +0000368
369 // Demote the PHIs to the stack.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000370 for (SmallPtrSet<PHINode *, 8>::iterator I = PHIsToDemote.begin(),
371 E = PHIsToDemote.end();
372 I != E; ++I)
Bill Wendlingb1c43082011-10-21 22:08:56 +0000373 DemotePHIToStack(*I);
374
375 // Move the landingpad instruction back to the top of the landing pad block.
376 LPI->moveBefore(UnwindBlock->begin());
377 }
Bill Wendlinge9574be2011-10-08 00:56:47 +0000378}
379
Bill Wendling899da522011-09-28 21:56:53 +0000380/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
381/// the function context and marking the call sites with the appropriate
382/// values. These values are used by the DWARF EH emitter.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000383bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
Bill Wendling8faa30e2013-09-23 20:57:47 +0000384 SmallVector<ReturnInst *, 16> Returns;
385 SmallVector<InvokeInst *, 16> Invokes;
386 SmallSetVector<LandingPadInst *, 16> LPads;
Bill Wendling899da522011-09-28 21:56:53 +0000387
388 // Look through the terminators of the basic blocks to find invokes.
389 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
390 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Bill Wendling2d915e22013-03-08 02:21:08 +0000391 if (Function *Callee = II->getCalledFunction())
392 if (Callee->isIntrinsic() &&
393 Callee->getIntrinsicID() == Intrinsic::donothing) {
394 // Remove the NOP invoke.
395 BranchInst::Create(II->getNormalDest(), II);
396 II->eraseFromParent();
397 continue;
398 }
399
Bill Wendling899da522011-09-28 21:56:53 +0000400 Invokes.push_back(II);
Bob Wilsoncca9aa52011-11-16 07:57:21 +0000401 LPads.insert(II->getUnwindDest()->getLandingPadInst());
Bill Wendling899da522011-09-28 21:56:53 +0000402 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
403 Returns.push_back(RI);
404 }
405
Bill Wendling8faa30e2013-09-23 20:57:47 +0000406 if (Invokes.empty())
407 return false;
Bill Wendling899da522011-09-28 21:56:53 +0000408
Bill Wendling38f86c52011-10-24 17:12:36 +0000409 NumInvokes += Invokes.size();
410
Bill Wendlinge9574be2011-10-08 00:56:47 +0000411 lowerIncomingArguments(F);
412 lowerAcrossUnwindEdges(F, Invokes);
413
Bob Wilsoncca9aa52011-11-16 07:57:21 +0000414 Value *FuncCtx =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000415 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
Bill Wendling899da522011-09-28 21:56:53 +0000416 BasicBlock *EntryBB = F.begin();
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000417 IRBuilder<> Builder(EntryBB->getTerminator());
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000418
419 // Get a reference to the jump buffer.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000420 Value *JBufPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 5, "jbuf_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000421
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000422 // Save the frame pointer.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000423 Value *FramePtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 0, "jbuf_fp_gep");
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000424
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000425 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
426 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000427
428 // Save the stack pointer.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000429 Value *StackPtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 2, "jbuf_sp_gep");
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000430
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000431 Val = Builder.CreateCall(StackAddrFn, "sp");
432 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000433
434 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000435 Value *SetjmpArg = Builder.CreateBitCast(JBufPtr, Builder.getInt8PtrTy());
436 Builder.CreateCall(BuiltinSetjmpFn, SetjmpArg);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000437
Bill Wendling899da522011-09-28 21:56:53 +0000438 // Store a pointer to the function context so that the back-end will know
439 // where to look for it.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000440 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
441 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000442
443 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendlingdb163352011-10-05 22:04:08 +0000444 // their call_site values.
Bill Wendling2e76ca92011-09-28 03:14:05 +0000445 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000446 insertCallSiteStore(Invokes[I], I + 1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000447
448 ConstantInt *CallSiteNum =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000449 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000450
451 // Record the call site value for the back end so it stays associated with
452 // the invoke.
453 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
454 }
455
456 // Mark call instructions that aren't nounwind as no-action (call_site ==
457 // -1). Skip the entry block, as prior to then, no function context has been
458 // created for this function and any unexpected exceptions thrown will go
459 // directly to the caller's context, which is what we want anyway, so no need
460 // to do anything here.
Bill Wendlingac3fb4c2011-10-04 00:16:40 +0000461 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2e76ca92011-09-28 03:14:05 +0000462 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
463 if (CallInst *CI = dyn_cast<CallInst>(I)) {
464 if (!CI->doesNotThrow())
Bill Wendling7717e9f2012-01-27 02:02:24 +0000465 insertCallSiteStore(CI, -1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000466 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000467 insertCallSiteStore(RI, -1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000468 }
Bill Wendling2e76ca92011-09-28 03:14:05 +0000469
Bill Wendling899da522011-09-28 21:56:53 +0000470 // Register the function context and make sure it's known to not throw
Bill Wendling8faa30e2013-09-23 20:57:47 +0000471 CallInst *Register =
472 CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
Bill Wendling899da522011-09-28 21:56:53 +0000473 Register->setDoesNotThrow();
474
Bob Wilson643e63c2011-11-16 07:12:00 +0000475 // Following any allocas not in the entry block, update the saved SP in the
476 // jmpbuf to the new value.
477 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
478 if (BB == F.begin())
479 continue;
480 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
481 if (CallInst *CI = dyn_cast<CallInst>(I)) {
482 if (CI->getCalledFunction() != StackRestoreFn)
483 continue;
484 } else if (!isa<AllocaInst>(I)) {
485 continue;
486 }
487 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
488 StackAddr->insertAfter(I);
489 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
490 StoreStackAddr->insertAfter(StackAddr);
491 }
492 }
493
Bill Wendling899da522011-09-28 21:56:53 +0000494 // Finally, for any returns from this function, if this function contains an
495 // invoke, add a call to unregister the function context.
496 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000497 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendling899da522011-09-28 21:56:53 +0000498
Bill Wendling2e76ca92011-09-28 03:14:05 +0000499 return true;
500}
501
Bill Wendling12e5adb2012-03-13 20:04:21 +0000502bool SjLjEHPrepare::runOnFunction(Function &F) {
Bill Wendling38f86c52011-10-24 17:12:36 +0000503 bool Res = setupEntryBlockAndCallSites(F);
Jim Grosbach486be662009-08-17 16:41:22 +0000504 return Res;
505}