blob: 2335a888794c872f2614697f500cfddc4fb54b6b [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/CodeGen/Passes.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Module.h"
Jim Grosbach486be662009-08-17 16:41:22 +000029#include "llvm/Pass.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000033#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000035#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
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "sjljehprepare"
42
Jim Grosbach486be662009-08-17 16:41:22 +000043STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach486be662009-08-17 16:41:22 +000044STATISTIC(NumSpilled, "Number of registers live across unwind edges");
45
46namespace {
Bill Wendling8faa30e2013-09-23 20:57:47 +000047class SjLjEHPrepare : public FunctionPass {
48 const TargetMachine *TM;
49 Type *FunctionContextTy;
50 Constant *RegisterFn;
51 Constant *UnregisterFn;
52 Constant *BuiltinSetjmpFn;
53 Constant *FrameAddrFn;
54 Constant *StackAddrFn;
55 Constant *StackRestoreFn;
56 Constant *LSDAAddrFn;
57 Value *PersonalityFn;
58 Constant *CallSiteFn;
59 Constant *FuncCtxFn;
60 AllocaInst *FuncCtx;
Jim Grosbach486be662009-08-17 16:41:22 +000061
Bill Wendling8faa30e2013-09-23 20:57:47 +000062public:
63 static char ID; // Pass identification, replacement for typeid
64 explicit SjLjEHPrepare(const TargetMachine *TM) : FunctionPass(ID), TM(TM) {}
Craig Topper4584cd52014-03-07 09:26:03 +000065 bool doInitialization(Module &M) override;
66 bool runOnFunction(Function &F) override;
Jim Grosbach486be662009-08-17 16:41:22 +000067
Craig Topper4584cd52014-03-07 09:26:03 +000068 void getAnalysisUsage(AnalysisUsage &AU) const override {}
69 const char *getPassName() const override {
Bill Wendling8faa30e2013-09-23 20:57:47 +000070 return "SJLJ Exception Handling preparation";
71 }
72
73private:
74 bool setupEntryBlockAndCallSites(Function &F);
75 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
76 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
77 void lowerIncomingArguments(Function &F);
78 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
79 void insertCallSiteStore(Instruction *I, int Number);
80};
Jim Grosbach486be662009-08-17 16:41:22 +000081} // end anonymous namespace
82
Bill Wendling12e5adb2012-03-13 20:04:21 +000083char SjLjEHPrepare::ID = 0;
Jim Grosbach486be662009-08-17 16:41:22 +000084
Bill Wendling12e5adb2012-03-13 20:04:21 +000085// Public Interface To the SjLjEHPrepare pass.
Bill Wendlingafc10362013-06-19 20:51:24 +000086FunctionPass *llvm::createSjLjEHPreparePass(const TargetMachine *TM) {
87 return new SjLjEHPrepare(TM);
Jim Grosbach486be662009-08-17 16:41:22 +000088}
Jim Grosbach1b0436b2009-08-23 18:13:48 +000089// doInitialization - Set up decalarations and types needed to process
90// exceptions.
Bill Wendling12e5adb2012-03-13 20:04:21 +000091bool SjLjEHPrepare::doInitialization(Module &M) {
Jim Grosbach486be662009-08-17 16:41:22 +000092 // Build the function context structure.
93 // builtin_setjmp uses a five word jbuf
Jay Foadb804a2b2011-07-12 14:06:48 +000094 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
95 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Bill Wendling8faa30e2013-09-23 20:57:47 +000096 FunctionContextTy = StructType::get(VoidPtrTy, // __prev
97 Int32Ty, // call_site
98 ArrayType::get(Int32Ty, 4), // __data
99 VoidPtrTy, // __personality
100 VoidPtrTy, // __lsda
101 ArrayType::get(VoidPtrTy, 5), // __jbuf
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000102 nullptr);
Bill Wendling8faa30e2013-09-23 20:57:47 +0000103 RegisterFn = M.getOrInsertFunction(
104 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
Craig Topperc0196b12014-04-14 00:51:57 +0000105 PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
Bill Wendling8faa30e2013-09-23 20:57:47 +0000106 UnregisterFn = M.getOrInsertFunction(
107 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
Craig Topperc0196b12014-04-14 00:51:57 +0000108 PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
Jim Grosbach486be662009-08-17 16:41:22 +0000109 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbachfaa3abb2010-05-27 23:49:24 +0000110 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
Bob Wilson643e63c2011-11-16 07:12:00 +0000111 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach486be662009-08-17 16:41:22 +0000112 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
113 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Jim Grosbach54c05302010-01-28 01:45:32 +0000114 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Bill Wendling899da522011-09-28 21:56:53 +0000115 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Craig Topperc0196b12014-04-14 00:51:57 +0000116 PersonalityFn = nullptr;
Jim Grosbach486be662009-08-17 16:41:22 +0000117
118 return true;
119}
120
Jim Grosbach1201f292010-03-04 22:07:46 +0000121/// insertCallSiteStore - Insert a store of the call-site value to the
122/// function context
Bill Wendling12e5adb2012-03-13 20:04:21 +0000123void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000124 IRBuilder<> Builder(I);
125
126 // Get a reference to the call_site field.
127 Type *Int32Ty = Type::getInt32Ty(I->getContext());
128 Value *Zero = ConstantInt::get(Int32Ty, 0);
129 Value *One = ConstantInt::get(Int32Ty, 1);
130 Value *Idxs[2] = { Zero, One };
David Blaikie68d535c2015-03-24 22:38:16 +0000131 Value *CallSite =
132 Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
Bill Wendling7717e9f2012-01-27 02:02:24 +0000133
134 // Insert a store of the call-site number
Bill Wendling8faa30e2013-09-23 20:57:47 +0000135 ConstantInt *CallSiteNoC =
136 ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
137 Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
Jim Grosbach1201f292010-03-04 22:07:46 +0000138}
139
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000140/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
Jim Grosbach486be662009-08-17 16:41:22 +0000141/// we reach blocks we've already seen.
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000142static void MarkBlocksLiveIn(BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000143 SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
David Blaikie70573dc2014-11-19 07:49:26 +0000144 if (!LiveBBs.insert(BB).second)
Bill Wendling8faa30e2013-09-23 20:57:47 +0000145 return; // already been here.
Jim Grosbach486be662009-08-17 16:41:22 +0000146
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000147 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
148 MarkBlocksLiveIn(*PI, LiveBBs);
Jim Grosbach486be662009-08-17 16:41:22 +0000149}
150
Bill Wendlingb108aae2011-12-14 22:45:33 +0000151/// substituteLPadValues - Substitute the values returned by the landingpad
152/// instruction with those returned by the personality function.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000153void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
154 Value *SelVal) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000155 SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
Bill Wendlingb108aae2011-12-14 22:45:33 +0000156 while (!UseWorkList.empty()) {
157 Value *Val = UseWorkList.pop_back_val();
158 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
Bill Wendling8faa30e2013-09-23 20:57:47 +0000159 if (!EVI)
160 continue;
161 if (EVI->getNumIndices() != 1)
162 continue;
Bill Wendlingb108aae2011-12-14 22:45:33 +0000163 if (*EVI->idx_begin() == 0)
164 EVI->replaceAllUsesWith(ExnVal);
165 else if (*EVI->idx_begin() == 1)
166 EVI->replaceAllUsesWith(SelVal);
167 if (EVI->getNumUses() == 0)
168 EVI->eraseFromParent();
169 }
170
Bill Wendling8faa30e2013-09-23 20:57:47 +0000171 if (LPI->getNumUses() == 0)
172 return;
Bill Wendlingb108aae2011-12-14 22:45:33 +0000173
174 // There are still some uses of LPI. Construct an aggregate with the exception
175 // values and replace the LPI with that aggregate.
176 Type *LPadType = LPI->getType();
177 Value *LPadVal = UndefValue::get(LPadType);
Bill Wendling8faa30e2013-09-23 20:57:47 +0000178 IRBuilder<> Builder(
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000179 std::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
Bill Wendlingb108aae2011-12-14 22:45:33 +0000180 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
181 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
182
183 LPI->replaceAllUsesWith(LPadVal);
184}
185
Bill Wendling2e76ca92011-09-28 03:14:05 +0000186/// setupFunctionContext - Allocate the function context on the stack and fill
187/// it with all of the data that we know at this point.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000188Value *SjLjEHPrepare::setupFunctionContext(Function &F,
189 ArrayRef<LandingPadInst *> LPads) {
Bill Wendling2e76ca92011-09-28 03:14:05 +0000190 BasicBlock *EntryBB = F.begin();
191
192 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
193 // that needs to be restored on all exits from the function. This is an alloca
194 // because the value needs to be added to the global context list.
Eric Christopher33726202015-01-27 08:48:42 +0000195 const TargetLowering *TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Bill Wendling2e76ca92011-09-28 03:14:05 +0000196 unsigned Align =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000197 TLI->getDataLayout()->getPrefTypeAlignment(FunctionContextTy);
Craig Topperc0196b12014-04-14 00:51:57 +0000198 FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
Bill Wendling8faa30e2013-09-23 20:57:47 +0000199 EntryBB->begin());
Bill Wendling2e76ca92011-09-28 03:14:05 +0000200
201 // Fill in the function context structure.
Bill Wendling2e76ca92011-09-28 03:14:05 +0000202 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
203 LandingPadInst *LPI = LPads[I];
204 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
205
Bill Wendling7717e9f2012-01-27 02:02:24 +0000206 // Reference the __data field.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000207 Value *FCData = Builder.CreateConstGEP2_32(FuncCtx, 0, 2, "__data");
Bill Wendling7717e9f2012-01-27 02:02:24 +0000208
209 // The exception values come back in context->__data[0].
Bill Wendling8faa30e2013-09-23 20:57:47 +0000210 Value *ExceptionAddr =
211 Builder.CreateConstGEP2_32(FCData, 0, 0, "exception_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000212 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000213 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
Bill Wendling7717e9f2012-01-27 02:02:24 +0000214
Bill Wendling8faa30e2013-09-23 20:57:47 +0000215 Value *SelectorAddr =
216 Builder.CreateConstGEP2_32(FCData, 0, 1, "exn_selector_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000217 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
218
Bill Wendlingb108aae2011-12-14 22:45:33 +0000219 substituteLPadValues(LPI, ExnVal, SelVal);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000220 }
221
222 // Personality function
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000223 IRBuilder<> Builder(EntryBB->getTerminator());
Bill Wendling2e76ca92011-09-28 03:14:05 +0000224 if (!PersonalityFn)
225 PersonalityFn = LPads[0]->getPersonalityFn();
Bill Wendling8faa30e2013-09-23 20:57:47 +0000226 Value *PersonalityFieldPtr =
227 Builder.CreateConstGEP2_32(FuncCtx, 0, 3, "pers_fn_gep");
228 Builder.CreateStore(
229 Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
230 PersonalityFieldPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000231
232 // LSDA address
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000233 Value *LSDA = Builder.CreateCall(LSDAAddrFn, "lsda_addr");
234 Value *LSDAFieldPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 4, "lsda_gep");
235 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000236
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000237 return FuncCtx;
Bill Wendling899da522011-09-28 21:56:53 +0000238}
239
Bill Wendlinge9574be2011-10-08 00:56:47 +0000240/// lowerIncomingArguments - To avoid having to handle incoming arguments
241/// specially, we lower each arg to a copy instruction in the entry block. This
242/// ensures that the argument value itself cannot be live out of the entry
243/// block.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000244void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000245 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
246 while (isa<AllocaInst>(AfterAllocaInsPt) &&
247 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
248 ++AfterAllocaInsPt;
249
Bill Wendling8faa30e2013-09-23 20:57:47 +0000250 for (Function::arg_iterator AI = F.arg_begin(), AE = F.arg_end(); AI != AE;
251 ++AI) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000252 Type *Ty = AI->getType();
253
Bill Wendlingc80b6c92014-07-14 18:21:11 +0000254 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
255 Value *TrueValue = ConstantInt::getTrue(F.getContext());
256 Value *UndefValue = UndefValue::get(Ty);
257 Instruction *SI = SelectInst::Create(TrueValue, AI, UndefValue,
258 AI->getName() + ".tmp",
259 AfterAllocaInsPt);
260 AI->replaceAllUsesWith(SI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000261
Bill Wendlingc80b6c92014-07-14 18:21:11 +0000262 // Reset the operand, because it was clobbered by the RAUW above.
263 SI->setOperand(1, AI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000264 }
265}
266
267/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
268/// edge and spill them.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000269void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
Bill Wendling8faa30e2013-09-23 20:57:47 +0000270 ArrayRef<InvokeInst *> Invokes) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000271 // Finally, scan the code looking for instructions with bad live ranges.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000272 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
273 for (BasicBlock::iterator II = BB->begin(), IIE = BB->end(); II != IIE;
274 ++II) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000275 // Ignore obvious cases we don't have to handle. In particular, most
276 // instructions either have no uses or only have a single use inside the
277 // current block. Ignore them quickly.
278 Instruction *Inst = II;
Bill Wendling8faa30e2013-09-23 20:57:47 +0000279 if (Inst->use_empty())
280 continue;
Bill Wendlinge9574be2011-10-08 00:56:47 +0000281 if (Inst->hasOneUse() &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000282 cast<Instruction>(Inst->user_back())->getParent() == BB &&
283 !isa<PHINode>(Inst->user_back()))
Bill Wendling8faa30e2013-09-23 20:57:47 +0000284 continue;
Bill Wendlinge9574be2011-10-08 00:56:47 +0000285
286 // If this is an alloca in the entry block, it's not a real register
287 // value.
288 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
289 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
290 continue;
291
292 // Avoid iterator invalidation by copying users to a temporary vector.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000293 SmallVector<Instruction *, 16> Users;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000294 for (User *U : Inst->users()) {
295 Instruction *UI = cast<Instruction>(U);
296 if (UI->getParent() != BB || isa<PHINode>(UI))
297 Users.push_back(UI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000298 }
299
300 // Find all of the blocks that this value is live in.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000301 SmallPtrSet<BasicBlock *, 64> LiveBBs;
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000302 LiveBBs.insert(Inst->getParent());
Bill Wendlinge9574be2011-10-08 00:56:47 +0000303 while (!Users.empty()) {
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000304 Instruction *U = Users.back();
305 Users.pop_back();
Bill Wendlinge9574be2011-10-08 00:56:47 +0000306
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000307 if (!isa<PHINode>(U)) {
308 MarkBlocksLiveIn(U->getParent(), LiveBBs);
309 } else {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000310 // Uses for a PHI node occur in their predecessor block.
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000311 PHINode *PN = cast<PHINode>(U);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000312 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
313 if (PN->getIncomingValue(i) == Inst)
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000314 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000315 }
316 }
317
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000318 // Now that we know all of the blocks that this thing is live in, see if
319 // it includes any of the unwind locations.
320 bool NeedsSpill = false;
321 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
322 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
323 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
324 DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
Bill Wendling8faa30e2013-09-23 20:57:47 +0000325 << UnwindBlock->getName() << "\n");
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000326 NeedsSpill = true;
327 break;
Bill Wendlingd7c0aae2012-03-14 07:28:01 +0000328 }
Bill Wendling5ad91402012-03-12 20:19:41 +0000329 }
Bill Wendlingb1c43082011-10-21 22:08:56 +0000330
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000331 // If we decided we need a spill, do it.
332 // FIXME: Spilling this way is overkill, as it forces all uses of
333 // the value to be reloaded from the stack slot, even those that aren't
334 // in the unwind blocks. We should be more selective.
335 if (NeedsSpill) {
336 DemoteRegToStack(*Inst, true);
337 ++NumSpilled;
338 }
Bill Wendlingd7c0aae2012-03-14 07:28:01 +0000339 }
340 }
341
Bill Wendlingb1c43082011-10-21 22:08:56 +0000342 // Go through the landing pads and remove any PHIs there.
343 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
344 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
345 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
346
347 // Place PHIs into a set to avoid invalidating the iterator.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000348 SmallPtrSet<PHINode *, 8> PHIsToDemote;
349 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
Bill Wendlingb1c43082011-10-21 22:08:56 +0000350 PHIsToDemote.insert(cast<PHINode>(PN));
Bill Wendling8faa30e2013-09-23 20:57:47 +0000351 if (PHIsToDemote.empty())
352 continue;
Bill Wendlingb1c43082011-10-21 22:08:56 +0000353
354 // Demote the PHIs to the stack.
Craig Topper46276792014-08-24 23:23:06 +0000355 for (PHINode *PN : PHIsToDemote)
356 DemotePHIToStack(PN);
Bill Wendlingb1c43082011-10-21 22:08:56 +0000357
358 // Move the landingpad instruction back to the top of the landing pad block.
359 LPI->moveBefore(UnwindBlock->begin());
360 }
Bill Wendlinge9574be2011-10-08 00:56:47 +0000361}
362
Bill Wendling899da522011-09-28 21:56:53 +0000363/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
364/// the function context and marking the call sites with the appropriate
365/// values. These values are used by the DWARF EH emitter.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000366bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
Bill Wendling8faa30e2013-09-23 20:57:47 +0000367 SmallVector<ReturnInst *, 16> Returns;
368 SmallVector<InvokeInst *, 16> Invokes;
369 SmallSetVector<LandingPadInst *, 16> LPads;
Bill Wendling899da522011-09-28 21:56:53 +0000370
371 // Look through the terminators of the basic blocks to find invokes.
372 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
373 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Bill Wendling2d915e22013-03-08 02:21:08 +0000374 if (Function *Callee = II->getCalledFunction())
375 if (Callee->isIntrinsic() &&
376 Callee->getIntrinsicID() == Intrinsic::donothing) {
377 // Remove the NOP invoke.
378 BranchInst::Create(II->getNormalDest(), II);
379 II->eraseFromParent();
380 continue;
381 }
382
Bill Wendling899da522011-09-28 21:56:53 +0000383 Invokes.push_back(II);
Bob Wilsoncca9aa52011-11-16 07:57:21 +0000384 LPads.insert(II->getUnwindDest()->getLandingPadInst());
Bill Wendling899da522011-09-28 21:56:53 +0000385 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
386 Returns.push_back(RI);
387 }
388
Bill Wendling8faa30e2013-09-23 20:57:47 +0000389 if (Invokes.empty())
390 return false;
Bill Wendling899da522011-09-28 21:56:53 +0000391
Bill Wendling38f86c52011-10-24 17:12:36 +0000392 NumInvokes += Invokes.size();
393
Bill Wendlinge9574be2011-10-08 00:56:47 +0000394 lowerIncomingArguments(F);
395 lowerAcrossUnwindEdges(F, Invokes);
396
Bob Wilsoncca9aa52011-11-16 07:57:21 +0000397 Value *FuncCtx =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000398 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
Bill Wendling899da522011-09-28 21:56:53 +0000399 BasicBlock *EntryBB = F.begin();
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000400 IRBuilder<> Builder(EntryBB->getTerminator());
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000401
402 // Get a reference to the jump buffer.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000403 Value *JBufPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 5, "jbuf_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000404
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000405 // Save the frame pointer.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000406 Value *FramePtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 0, "jbuf_fp_gep");
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000407
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000408 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
409 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000410
411 // Save the stack pointer.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000412 Value *StackPtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 2, "jbuf_sp_gep");
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000413
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000414 Val = Builder.CreateCall(StackAddrFn, "sp");
415 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000416
417 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000418 Value *SetjmpArg = Builder.CreateBitCast(JBufPtr, Builder.getInt8PtrTy());
419 Builder.CreateCall(BuiltinSetjmpFn, SetjmpArg);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000420
Bill Wendling899da522011-09-28 21:56:53 +0000421 // Store a pointer to the function context so that the back-end will know
422 // where to look for it.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000423 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
424 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000425
426 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendlingdb163352011-10-05 22:04:08 +0000427 // their call_site values.
Bill Wendling2e76ca92011-09-28 03:14:05 +0000428 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000429 insertCallSiteStore(Invokes[I], I + 1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000430
431 ConstantInt *CallSiteNum =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000432 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000433
434 // Record the call site value for the back end so it stays associated with
435 // the invoke.
436 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
437 }
438
439 // Mark call instructions that aren't nounwind as no-action (call_site ==
440 // -1). Skip the entry block, as prior to then, no function context has been
441 // created for this function and any unexpected exceptions thrown will go
442 // directly to the caller's context, which is what we want anyway, so no need
443 // to do anything here.
Bill Wendlingac3fb4c2011-10-04 00:16:40 +0000444 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2e76ca92011-09-28 03:14:05 +0000445 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
446 if (CallInst *CI = dyn_cast<CallInst>(I)) {
447 if (!CI->doesNotThrow())
Bill Wendling7717e9f2012-01-27 02:02:24 +0000448 insertCallSiteStore(CI, -1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000449 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000450 insertCallSiteStore(RI, -1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000451 }
Bill Wendling2e76ca92011-09-28 03:14:05 +0000452
Bill Wendling899da522011-09-28 21:56:53 +0000453 // Register the function context and make sure it's known to not throw
Bill Wendling8faa30e2013-09-23 20:57:47 +0000454 CallInst *Register =
455 CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
Bill Wendling899da522011-09-28 21:56:53 +0000456 Register->setDoesNotThrow();
457
Bob Wilson643e63c2011-11-16 07:12:00 +0000458 // Following any allocas not in the entry block, update the saved SP in the
459 // jmpbuf to the new value.
460 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
461 if (BB == F.begin())
462 continue;
463 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
464 if (CallInst *CI = dyn_cast<CallInst>(I)) {
465 if (CI->getCalledFunction() != StackRestoreFn)
466 continue;
467 } else if (!isa<AllocaInst>(I)) {
468 continue;
469 }
470 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
471 StackAddr->insertAfter(I);
472 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
473 StoreStackAddr->insertAfter(StackAddr);
474 }
475 }
476
Bill Wendling899da522011-09-28 21:56:53 +0000477 // Finally, for any returns from this function, if this function contains an
478 // invoke, add a call to unregister the function context.
479 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000480 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendling899da522011-09-28 21:56:53 +0000481
Bill Wendling2e76ca92011-09-28 03:14:05 +0000482 return true;
483}
484
Bill Wendling12e5adb2012-03-13 20:04:21 +0000485bool SjLjEHPrepare::runOnFunction(Function &F) {
Bill Wendling38f86c52011-10-24 17:12:36 +0000486 bool Res = setupEntryBlockAndCallSites(F);
Jim Grosbach486be662009-08-17 16:41:22 +0000487 return Res;
488}