blob: 5ac0c09ded9990c9dac8987eadf1c7d4df839371 [file] [log] [blame]
Bill Wendlingeabae1d2012-03-13 20:04:21 +00001//===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
Jim Grosbach8b818d72009-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"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/LLVMContext.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
Bill Wendling30442f92012-03-14 07:28:01 +000024#include "llvm/Analysis/Verifier.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000025#include "llvm/CodeGen/Passes.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000026#include "llvm/Target/TargetData.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000027#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
29#include "llvm/Transforms/Utils/Local.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000030#include "llvm/Support/CommandLine.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000031#include "llvm/Support/Debug.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000032#include "llvm/Support/IRBuilder.h"
Andrew Trick9c7b3da2012-01-07 00:54:28 +000033#include "llvm/Support/raw_ostream.h"
Bill Wendlingaef508d2011-08-22 23:38:40 +000034#include "llvm/ADT/DenseMap.h"
Bob Wilsonf1b41dd2011-11-16 07:57:21 +000035#include "llvm/ADT/SetVector.h"
Bill Wendlingd2dae0c2011-10-24 17:12:36 +000036#include "llvm/ADT/SmallPtrSet.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000037#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000039#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000040using namespace llvm;
41
42STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach8b818d72009-08-17 16:41:22 +000043STATISTIC(NumSpilled, "Number of registers live across unwind edges");
44
45namespace {
Bill Wendlingeabae1d2012-03-13 20:04:21 +000046 class SjLjEHPrepare : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000047 const TargetLowering *TLI;
Bill Wendling30442f92012-03-14 07:28:01 +000048
Chris Lattnerdb125cf2011-07-18 04:54:35 +000049 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000050 Constant *RegisterFn;
51 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000052 Constant *BuiltinSetjmpFn;
53 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000054 Constant *StackAddrFn;
Bob Wilson20c918d2011-11-16 07:12:00 +000055 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000056 Constant *LSDAAddrFn;
57 Value *PersonalityFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000058 Constant *CallSiteFn;
Bill Wendlingcc8cf972011-09-28 21:56:53 +000059 Constant *FuncCtxFn;
Bill Wendling4cc46662012-01-27 02:02:24 +000060 AllocaInst *FuncCtx;
Jim Grosbach8b818d72009-08-17 16:41:22 +000061 public:
62 static char ID; // Pass identification, replacement for typeid
Bill Wendlingeabae1d2012-03-13 20:04:21 +000063 explicit SjLjEHPrepare(const TargetLowering *tli = NULL)
Bill Wendling30442f92012-03-14 07:28:01 +000064 : FunctionPass(ID), TLI(tli) {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000065 bool doInitialization(Module &M);
66 bool runOnFunction(Function &F);
67
Bill Wendling30442f92012-03-14 07:28:01 +000068 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 FunctionPass::getAnalysisUsage(AU);
70 }
Jim Grosbach8b818d72009-08-17 16:41:22 +000071 const char *getPassName() const {
72 return "SJLJ Exception Handling preparation";
73 }
74
75 private:
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000076 bool setupEntryBlockAndCallSites(Function &F);
Bill Wendling69fdcd72011-12-14 22:45:33 +000077 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
78 Value *SelVal);
Bill Wendling631d1172011-10-03 21:15:28 +000079 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
Bill Wendlingd5d17002011-10-08 00:56:47 +000080 void lowerIncomingArguments(Function &F);
81 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
Bill Wendling4cc46662012-01-27 02:02:24 +000082 void insertCallSiteStore(Instruction *I, int Number);
Jim Grosbach8b818d72009-08-17 16:41:22 +000083 };
84} // end anonymous namespace
85
Bill Wendlingeabae1d2012-03-13 20:04:21 +000086char SjLjEHPrepare::ID = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +000087
Bill Wendlingeabae1d2012-03-13 20:04:21 +000088// Public Interface To the SjLjEHPrepare pass.
89FunctionPass *llvm::createSjLjEHPreparePass(const TargetLowering *TLI) {
90 return new SjLjEHPrepare(TLI);
Jim Grosbach8b818d72009-08-17 16:41:22 +000091}
Jim Grosbacha235d132009-08-23 18:13:48 +000092// doInitialization - Set up decalarations and types needed to process
93// exceptions.
Bill Wendlingeabae1d2012-03-13 20:04:21 +000094bool SjLjEHPrepare::doInitialization(Module &M) {
Jim Grosbach8b818d72009-08-17 16:41:22 +000095 // Build the function context structure.
96 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +000097 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
98 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000099 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +0000100 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +0000101 Int32Ty, // call_site
102 ArrayType::get(Int32Ty, 4), // __data
103 VoidPtrTy, // __personality
104 VoidPtrTy, // __lsda
105 ArrayType::get(VoidPtrTy, 5), // __jbuf
106 NULL);
107 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
108 Type::getVoidTy(M.getContext()),
109 PointerType::getUnqual(FunctionContextTy),
110 (Type *)0);
111 UnregisterFn =
112 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
113 Type::getVoidTy(M.getContext()),
114 PointerType::getUnqual(FunctionContextTy),
115 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000116 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000117 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
Bob Wilson20c918d2011-11-16 07:12:00 +0000118 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000119 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
120 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Jim Grosbachca752c92010-01-28 01:45:32 +0000121 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000122 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Jim Grosbacha235d132009-08-23 18:13:48 +0000123 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000124
125 return true;
126}
127
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000128/// insertCallSiteStore - Insert a store of the call-site value to the
129/// function context
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000130void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
Bill Wendling4cc46662012-01-27 02:02:24 +0000131 IRBuilder<> Builder(I);
132
133 // Get a reference to the call_site field.
134 Type *Int32Ty = Type::getInt32Ty(I->getContext());
135 Value *Zero = ConstantInt::get(Int32Ty, 0);
136 Value *One = ConstantInt::get(Int32Ty, 1);
137 Value *Idxs[2] = { Zero, One };
138 Value *CallSite = Builder.CreateGEP(FuncCtx, Idxs, "call_site");
139
140 // Insert a store of the call-site number
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000141 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
142 Number);
Bill Wendling4cc46662012-01-27 02:02:24 +0000143 Builder.CreateStore(CallSiteNoC, CallSite, true/*volatile*/);
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000144}
145
Bill Wendling30442f92012-03-14 07:28:01 +0000146/// markBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
Jim Grosbach8b818d72009-08-17 16:41:22 +0000147/// we reach blocks we've already seen.
Bill Wendling30442f92012-03-14 07:28:01 +0000148static void markBlocksLiveIn(BasicBlock *BB, Instruction *Inst,
149 SmallPtrSet<BasicBlock*, 64> &LiveBBs,
150 SmallPtrSet<BasicBlock*, 4> &InvokesCrossed,
151 bool &FoundDef) {
152 if (!LiveBBs.insert(BB)) return; // Already been here.
153 if (BB == Inst->getParent()) {
154 FoundDef = true;
155 return;
156 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000157
Bill Wendling30442f92012-03-14 07:28:01 +0000158 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
159 BasicBlock *Pred = *PI;
160 if (BB->isLandingPad() && BB != Inst->getParent()) {
161 InvokesCrossed.insert(Pred);
162 continue;
163 }
164 markBlocksLiveIn(Pred, Inst, LiveBBs, InvokesCrossed, FoundDef);
165 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000166}
167
Bill Wendling69fdcd72011-12-14 22:45:33 +0000168/// substituteLPadValues - Substitute the values returned by the landingpad
169/// instruction with those returned by the personality function.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000170void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
171 Value *SelVal) {
Bill Wendling69fdcd72011-12-14 22:45:33 +0000172 SmallVector<Value*, 8> UseWorkList(LPI->use_begin(), LPI->use_end());
173 while (!UseWorkList.empty()) {
174 Value *Val = UseWorkList.pop_back_val();
175 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
176 if (!EVI) continue;
177 if (EVI->getNumIndices() != 1) continue;
178 if (*EVI->idx_begin() == 0)
179 EVI->replaceAllUsesWith(ExnVal);
180 else if (*EVI->idx_begin() == 1)
181 EVI->replaceAllUsesWith(SelVal);
182 if (EVI->getNumUses() == 0)
183 EVI->eraseFromParent();
184 }
185
186 if (LPI->getNumUses() == 0) return;
187
188 // There are still some uses of LPI. Construct an aggregate with the exception
189 // values and replace the LPI with that aggregate.
190 Type *LPadType = LPI->getType();
191 Value *LPadVal = UndefValue::get(LPadType);
192 IRBuilder<>
193 Builder(llvm::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
194 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
195 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
196
197 LPI->replaceAllUsesWith(LPadVal);
198}
199
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000200/// setupFunctionContext - Allocate the function context on the stack and fill
201/// it with all of the data that we know at this point.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000202Value *SjLjEHPrepare::
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000203setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000204 BasicBlock *EntryBB = F.begin();
205
206 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
207 // that needs to be restored on all exits from the function. This is an alloca
208 // because the value needs to be added to the global context list.
209 unsigned Align =
210 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
Bill Wendling4cc46662012-01-27 02:02:24 +0000211 FuncCtx =
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000212 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
213
214 // Fill in the function context structure.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000215 Type *Int32Ty = Type::getInt32Ty(F.getContext());
216 Value *Zero = ConstantInt::get(Int32Ty, 0);
217 Value *One = ConstantInt::get(Int32Ty, 1);
Bill Wendling4cc46662012-01-27 02:02:24 +0000218 Value *Two = ConstantInt::get(Int32Ty, 2);
219 Value *Three = ConstantInt::get(Int32Ty, 3);
220 Value *Four = ConstantInt::get(Int32Ty, 4);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000221
Bill Wendling4cc46662012-01-27 02:02:24 +0000222 Value *Idxs[2] = { Zero, 0 };
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000223
224 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
225 LandingPadInst *LPI = LPads[I];
226 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
227
Bill Wendling4cc46662012-01-27 02:02:24 +0000228 // Reference the __data field.
229 Idxs[1] = Two;
230 Value *FCData = Builder.CreateGEP(FuncCtx, Idxs, "__data");
231
232 // The exception values come back in context->__data[0].
233 Idxs[1] = Zero;
234 Value *ExceptionAddr = Builder.CreateGEP(FCData, Idxs, "exception_gep");
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000235 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
236 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
Bill Wendling4cc46662012-01-27 02:02:24 +0000237
238 Idxs[1] = One;
239 Value *SelectorAddr = Builder.CreateGEP(FCData, Idxs, "exn_selector_gep");
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000240 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
241
Bill Wendling69fdcd72011-12-14 22:45:33 +0000242 substituteLPadValues(LPI, ExnVal, SelVal);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000243 }
244
245 // Personality function
Bill Wendling4cc46662012-01-27 02:02:24 +0000246 Idxs[1] = Three;
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000247 if (!PersonalityFn)
248 PersonalityFn = LPads[0]->getPersonalityFn();
249 Value *PersonalityFieldPtr =
250 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
251 EntryBB->getTerminator());
252 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
253 EntryBB->getTerminator());
254
255 // LSDA address
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000256 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
257 EntryBB->getTerminator());
Bill Wendling4cc46662012-01-27 02:02:24 +0000258 Idxs[1] = Four;
259 Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
260 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000261 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
262
Bill Wendling631d1172011-10-03 21:15:28 +0000263 return FuncCtx;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000264}
265
Bill Wendlingd5d17002011-10-08 00:56:47 +0000266/// lowerIncomingArguments - To avoid having to handle incoming arguments
267/// specially, we lower each arg to a copy instruction in the entry block. This
268/// ensures that the argument value itself cannot be live out of the entry
269/// block.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000270void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
Bill Wendlingd5d17002011-10-08 00:56:47 +0000271 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
272 while (isa<AllocaInst>(AfterAllocaInsPt) &&
273 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
274 ++AfterAllocaInsPt;
275
276 for (Function::arg_iterator
277 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
278 Type *Ty = AI->getType();
279
280 // Aggregate types can't be cast, but are legal argument types, so we have
281 // to handle them differently. We use an extract/insert pair as a
282 // lightweight method to achieve the same goal.
283 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
284 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
285 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
286 NI->insertAfter(EI);
287 AI->replaceAllUsesWith(NI);
288
289 // Set the operand of the instructions back to the AllocaInst.
290 EI->setOperand(0, AI);
291 NI->setOperand(0, AI);
292 } else {
293 // This is always a no-op cast because we're casting AI to AI->getType()
294 // so src and destination types are identical. BitCast is the only
295 // possibility.
296 CastInst *NC =
297 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
298 AfterAllocaInsPt);
299 AI->replaceAllUsesWith(NC);
300
301 // Set the operand of the cast instruction back to the AllocaInst.
302 // Normally it's forbidden to replace a CastInst's operand because it
303 // could cause the opcode to reflect an illegal conversion. However, we're
304 // replacing it here with the same value it was constructed with. We do
305 // this because the above replaceAllUsesWith() clobbered the operand, but
306 // we want this one to remain.
307 NC->setOperand(0, AI);
308 }
309 }
310}
311
312/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
313/// edge and spill them.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000314void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
315 ArrayRef<InvokeInst*> Invokes) {
Bill Wendling30442f92012-03-14 07:28:01 +0000316 SmallVector<std::pair<Instruction*, Instruction*>, 32> ReloadUsers;
317 DenseMap<std::pair<Instruction*, Instruction*>, AllocaInst*> AllocaMap;
318
Bill Wendlingd5d17002011-10-08 00:56:47 +0000319 // Finally, scan the code looking for instructions with bad live ranges.
320 for (Function::iterator
321 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
322 for (BasicBlock::iterator
323 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
324 // Ignore obvious cases we don't have to handle. In particular, most
325 // instructions either have no uses or only have a single use inside the
326 // current block. Ignore them quickly.
327 Instruction *Inst = II;
328 if (Inst->use_empty()) continue;
329 if (Inst->hasOneUse() &&
330 cast<Instruction>(Inst->use_back())->getParent() == BB &&
331 !isa<PHINode>(Inst->use_back())) continue;
332
333 // If this is an alloca in the entry block, it's not a real register
334 // value.
335 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
336 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
337 continue;
338
339 // Avoid iterator invalidation by copying users to a temporary vector.
340 SmallVector<Instruction*, 16> Users;
341 for (Value::use_iterator
342 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
343 Instruction *User = cast<Instruction>(*UI);
344 if (User->getParent() != BB || isa<PHINode>(User))
345 Users.push_back(User);
346 }
347
348 // Find all of the blocks that this value is live in.
Bill Wendling30442f92012-03-14 07:28:01 +0000349 std::map<Instruction*, SmallPtrSet<BasicBlock*, 4> > InvokesCrossed;
350 std::map<Instruction*, SmallPtrSet<BasicBlock*, 64> > LiveBBs;
351 bool FoundDef = false;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000352 while (!Users.empty()) {
Bill Wendling30442f92012-03-14 07:28:01 +0000353 Instruction *U = Users.pop_back_val();
Bill Wendlingd5d17002011-10-08 00:56:47 +0000354
Bill Wendling30442f92012-03-14 07:28:01 +0000355 if (PHINode *PN = dyn_cast<PHINode>(U)) {
Bill Wendlingd5d17002011-10-08 00:56:47 +0000356 // Uses for a PHI node occur in their predecessor block.
Bill Wendlingd5d17002011-10-08 00:56:47 +0000357 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
358 if (PN->getIncomingValue(i) == Inst)
Bill Wendling30442f92012-03-14 07:28:01 +0000359 markBlocksLiveIn(PN->getIncomingBlock(i), Inst, LiveBBs[U],
360 InvokesCrossed[U], FoundDef);
361 } else {
362 markBlocksLiveIn(U->getParent(), Inst, LiveBBs[U],
363 InvokesCrossed[U], FoundDef);
Bill Wendlingd5d17002011-10-08 00:56:47 +0000364 }
365 }
366
Bill Wendling30442f92012-03-14 07:28:01 +0000367 // If we hit the definition, resort to the dump-this-value-everywhere
368 // method.
369 if (FoundDef) {
370 // Now that we know all of the blocks that this thing is live in, see if
371 // it includes any of the unwind locations.
372 bool NeedsSpill = false;
373 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
374 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
375 if (UnwindBlock == BB) continue;
376
377 for (std::map<Instruction*, SmallPtrSet<BasicBlock*, 64> >::iterator
378 MI = LiveBBs.begin(), ME = LiveBBs.end(); MI != ME; ++MI) {
379 if (MI->second.count(UnwindBlock)) {
380 DEBUG({
381 dbgs() << "SJLJ Spill: " << *Inst << " around "
382 << UnwindBlock->getName() << "\n";
383 });
384 NeedsSpill = true;
385 break;
386 }
387 }
388
389 // If we decided we need a spill, do it.
390 if (NeedsSpill) {
391 DemoteRegToStack(*Inst, true);
392 ++NumSpilled;
393 }
Bill Wendlingd5d17002011-10-08 00:56:47 +0000394 }
Bill Wendling30442f92012-03-14 07:28:01 +0000395
396 // We don't need this map anymore.
397 InvokesCrossed.clear();
Bill Wendlingd5d17002011-10-08 00:56:47 +0000398 }
399
Bill Wendling30442f92012-03-14 07:28:01 +0000400 // Go through the invokes the value crosses and insert a spill right
401 // before the invoke.
402 for (std::map<Instruction*, SmallPtrSet<BasicBlock*, 4> >::iterator
403 MI = InvokesCrossed.begin(), ME = InvokesCrossed.end();
404 MI != ME; ++MI) {
405 Instruction *User = MI->first;
406 SmallPtrSet<BasicBlock*, 4> &Crossings = MI->second;
407 if (Crossings.empty()) continue;
408
409 ReloadUsers.push_back(std::make_pair(Inst, User));
410
411 AllocaInst *&Slot = AllocaMap[std::make_pair(Inst, User)];
412 if (!Slot)
413 Slot = new AllocaInst(Inst->getType(), 0,
414 Inst->getName() + ".reg2mem",
415 F.getEntryBlock().begin());
416
417 for (SmallPtrSet<BasicBlock*, 4>::iterator
418 CI = Crossings.begin(), CE = Crossings.end(); CI != CE; ++CI) {
419 new StoreInst(Inst, Slot, (*CI)->getTerminator());
420 ++NumSpilled;
421 }
Bill Wendling9eb5f172012-03-12 20:19:41 +0000422 }
Bill Wendlingd5d17002011-10-08 00:56:47 +0000423 }
424 }
Bill Wendling0ad56122011-10-21 22:08:56 +0000425
Bill Wendling30442f92012-03-14 07:28:01 +0000426 // Now go through the instructions which were spilled and replace their uses
427 // after a crossed invoke with a reload instruction.
428 for (SmallVectorImpl<std::pair<Instruction*, Instruction*> >::iterator
429 I = ReloadUsers.begin(), E = ReloadUsers.end(); I != E; ++I) {
430 Instruction *User = I->second;
431 AllocaInst *Slot = AllocaMap[*I];
432 assert(Slot && "A spill slot hasn't been allocated yet!");
433
434 if (PHINode *PN = dyn_cast<PHINode>(User)) {
435 // If this is a PHI node, we can't insert a load of the value before the
436 // use. Instead insert the load in the predecessor block corresponding to
437 // the incoming value.
438 //
439 // Note that if there are multiple edges from a basic block to this PHI
440 // node that we cannot have multiple loads. The problem is that the
441 // resulting PHI node will have multiple values (from each load) coming in
442 // from the same block, which is illegal SSA form. For this reason, we
443 // keep track of and reuse loads we insert.
444 DenseMap<BasicBlock*, Value*> Loads;
445 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
446 if (PN->getIncomingValue(i) == I->first) {
447 Value *&V = Loads[PN->getIncomingBlock(i)];
448 if (V == 0)
449 // Insert the load into the predecessor block
450 V = new LoadInst(Slot, I->first->getName() + ".reload", true,
451 PN->getIncomingBlock(i)->getTerminator());
452
453 PN->setIncomingValue(i, V);
454 }
455 } else {
456 LoadInst *Reload = new LoadInst(Slot, Slot->getName() + ".reload", User);
457 User->replaceUsesOfWith(I->first, Reload);
458 }
459 }
460
Bill Wendling0ad56122011-10-21 22:08:56 +0000461 // Go through the landing pads and remove any PHIs there.
462 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
463 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
464 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
465
466 // Place PHIs into a set to avoid invalidating the iterator.
467 SmallPtrSet<PHINode*, 8> PHIsToDemote;
468 for (BasicBlock::iterator
469 PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
470 PHIsToDemote.insert(cast<PHINode>(PN));
471 if (PHIsToDemote.empty()) continue;
472
473 // Demote the PHIs to the stack.
474 for (SmallPtrSet<PHINode*, 8>::iterator
475 I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
476 DemotePHIToStack(*I);
477
478 // Move the landingpad instruction back to the top of the landing pad block.
479 LPI->moveBefore(UnwindBlock->begin());
480 }
Bill Wendlingd5d17002011-10-08 00:56:47 +0000481}
482
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000483/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
484/// the function context and marking the call sites with the appropriate
485/// values. These values are used by the DWARF EH emitter.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000486bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000487 SmallVector<ReturnInst*, 16> Returns;
488 SmallVector<InvokeInst*, 16> Invokes;
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000489 SmallSetVector<LandingPadInst*, 16> LPads;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000490
491 // Look through the terminators of the basic blocks to find invokes.
492 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
493 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
494 Invokes.push_back(II);
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000495 LPads.insert(II->getUnwindDest()->getLandingPadInst());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000496 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
497 Returns.push_back(RI);
498 }
499
500 if (Invokes.empty()) return false;
501
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000502 NumInvokes += Invokes.size();
503
Bill Wendlingd5d17002011-10-08 00:56:47 +0000504 lowerIncomingArguments(F);
505 lowerAcrossUnwindEdges(F, Invokes);
506
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000507 Value *FuncCtx =
508 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000509 BasicBlock *EntryBB = F.begin();
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000510 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling631d1172011-10-03 21:15:28 +0000511
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000512 Value *Idxs[2] = {
Bill Wendling631d1172011-10-03 21:15:28 +0000513 ConstantInt::get(Int32Ty, 0), 0
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000514 };
Bill Wendling631d1172011-10-03 21:15:28 +0000515
516 // Get a reference to the jump buffer.
517 Idxs[1] = ConstantInt::get(Int32Ty, 5);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000518 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
519 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000520
Bill Wendling631d1172011-10-03 21:15:28 +0000521 // Save the frame pointer.
522 Idxs[1] = ConstantInt::get(Int32Ty, 0);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000523 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
524 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000525
526 Value *Val = CallInst::Create(FrameAddrFn,
527 ConstantInt::get(Int32Ty, 0),
528 "fp",
529 EntryBB->getTerminator());
530 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
531
532 // Save the stack pointer.
533 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000534 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
535 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000536
537 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000538 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
539
540 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000541 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
542 Type::getInt8PtrTy(F.getContext()), "",
543 EntryBB->getTerminator());
Bill Wendlingf8520d52011-10-03 22:42:40 +0000544 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000545
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000546 // Store a pointer to the function context so that the back-end will know
547 // where to look for it.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000548 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
549 Type::getInt8PtrTy(F.getContext()), "",
550 EntryBB->getTerminator());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000551 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000552
553 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendling2130ab02011-10-05 22:04:08 +0000554 // their call_site values.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000555 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
Bill Wendling4cc46662012-01-27 02:02:24 +0000556 insertCallSiteStore(Invokes[I], I + 1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000557
558 ConstantInt *CallSiteNum =
559 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
560
561 // Record the call site value for the back end so it stays associated with
562 // the invoke.
563 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
564 }
565
566 // Mark call instructions that aren't nounwind as no-action (call_site ==
567 // -1). Skip the entry block, as prior to then, no function context has been
568 // created for this function and any unexpected exceptions thrown will go
569 // directly to the caller's context, which is what we want anyway, so no need
570 // to do anything here.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000571 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000572 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
573 if (CallInst *CI = dyn_cast<CallInst>(I)) {
574 if (!CI->doesNotThrow())
Bill Wendling4cc46662012-01-27 02:02:24 +0000575 insertCallSiteStore(CI, -1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000576 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
Bill Wendling4cc46662012-01-27 02:02:24 +0000577 insertCallSiteStore(RI, -1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000578 }
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000579
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000580 // Register the function context and make sure it's known to not throw
Bill Wendling631d1172011-10-03 21:15:28 +0000581 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000582 EntryBB->getTerminator());
583 Register->setDoesNotThrow();
584
Bob Wilson20c918d2011-11-16 07:12:00 +0000585 // Following any allocas not in the entry block, update the saved SP in the
586 // jmpbuf to the new value.
587 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
588 if (BB == F.begin())
589 continue;
590 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
591 if (CallInst *CI = dyn_cast<CallInst>(I)) {
592 if (CI->getCalledFunction() != StackRestoreFn)
593 continue;
594 } else if (!isa<AllocaInst>(I)) {
595 continue;
596 }
597 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
598 StackAddr->insertAfter(I);
599 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
600 StoreStackAddr->insertAfter(StackAddr);
601 }
602 }
603
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000604 // Finally, for any returns from this function, if this function contains an
605 // invoke, add a call to unregister the function context.
606 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling631d1172011-10-03 21:15:28 +0000607 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000608
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000609 return true;
610}
611
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000612bool SjLjEHPrepare::runOnFunction(Function &F) {
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000613 bool Res = setupEntryBlockAndCallSites(F);
Bill Wendling30442f92012-03-14 07:28:01 +0000614 DEBUG({
615 if (verifyFunction(F))
616 report_fatal_error("verifyFunction failed!");
617 });
Jim Grosbach8b818d72009-08-17 16:41:22 +0000618 return Res;
619}