blob: 58af36a56d586650001573a8a0eb17776aa89289 [file] [log] [blame]
Anders Carlsson4b08db72009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
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 contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stump58ef18b2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCall0bdb1fd2010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallbd309292010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump58ef18b2009-11-20 23:44:51 +000019
John McCall2ca705e2010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson4b08db72009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallbd309292010-07-06 01:34:17 +000022#include "CGException.h"
John McCall5add20c2010-07-20 22:17:55 +000023#include "TargetInfo.h"
John McCallbd309292010-07-06 01:34:17 +000024
Anders Carlsson4b08db72009-10-30 01:42:31 +000025using namespace clang;
26using namespace CodeGen;
27
John McCallbd309292010-07-06 01:34:17 +000028/// Push an entry of the given size onto this protected-scope stack.
29char *EHScopeStack::allocate(size_t Size) {
30 if (!StartOfBuffer) {
31 unsigned Capacity = 1024;
32 while (Capacity < Size) Capacity *= 2;
33 StartOfBuffer = new char[Capacity];
34 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
35 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
36 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
37 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
38
39 unsigned NewCapacity = CurrentCapacity;
40 do {
41 NewCapacity *= 2;
42 } while (NewCapacity < UsedCapacity + Size);
43
44 char *NewStartOfBuffer = new char[NewCapacity];
45 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
46 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
47 memcpy(NewStartOfData, StartOfData, UsedCapacity);
48 delete [] StartOfBuffer;
49 StartOfBuffer = NewStartOfBuffer;
50 EndOfBuffer = NewEndOfBuffer;
51 StartOfData = NewStartOfData;
52 }
53
54 assert(StartOfBuffer + Size <= StartOfData);
55 StartOfData -= Size;
56 return StartOfData;
57}
58
59EHScopeStack::stable_iterator
60EHScopeStack::getEnclosingEHCleanup(iterator it) const {
61 assert(it != end());
62 do {
John McCallcda666c2010-07-21 07:22:38 +000063 if (isa<EHCleanupScope>(*it)) {
64 if (cast<EHCleanupScope>(*it).isEHCleanup())
John McCall2b7fc382010-07-13 20:32:21 +000065 return stabilize(it);
John McCallcda666c2010-07-21 07:22:38 +000066 return cast<EHCleanupScope>(*it).getEnclosingEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +000067 }
John McCallbd309292010-07-06 01:34:17 +000068 ++it;
69 } while (it != end());
70 return stable_end();
71}
72
73
John McCallcda666c2010-07-21 07:22:38 +000074void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCall2b7fc382010-07-13 20:32:21 +000075 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
John McCallcda666c2010-07-21 07:22:38 +000076 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
John McCall612942d2010-08-13 21:20:51 +000077 bool IsNormalCleanup = Kind & NormalCleanup;
78 bool IsEHCleanup = Kind & EHCleanup;
79 bool IsActive = !(Kind & InactiveCleanup);
John McCallcda666c2010-07-21 07:22:38 +000080 EHCleanupScope *Scope =
81 new (Buffer) EHCleanupScope(IsNormalCleanup,
82 IsEHCleanup,
John McCall612942d2010-08-13 21:20:51 +000083 IsActive,
John McCallcda666c2010-07-21 07:22:38 +000084 Size,
85 BranchFixups.size(),
86 InnermostNormalCleanup,
87 InnermostEHCleanup);
John McCall2b7fc382010-07-13 20:32:21 +000088 if (IsNormalCleanup)
89 InnermostNormalCleanup = stable_begin();
90 if (IsEHCleanup)
91 InnermostEHCleanup = stable_begin();
92
93 return Scope->getCleanupBuffer();
94}
95
John McCallbd309292010-07-06 01:34:17 +000096void EHScopeStack::popCleanup() {
97 assert(!empty() && "popping exception stack when not empty");
98
John McCallcda666c2010-07-21 07:22:38 +000099 assert(isa<EHCleanupScope>(*begin()));
100 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
John McCall20141f22010-07-21 07:11:21 +0000101 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
102 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
103 StartOfData += Cleanup.getAllocatedSize();
John McCallbd309292010-07-06 01:34:17 +0000104
John McCallad5d61e2010-07-23 21:56:41 +0000105 if (empty()) NextEHDestIndex = FirstEHDestIndex;
106
107 // Destroy the cleanup.
108 Cleanup.~EHCleanupScope();
109
John McCallbd309292010-07-06 01:34:17 +0000110 // Check whether we can shrink the branch-fixups stack.
111 if (!BranchFixups.empty()) {
112 // If we no longer have any normal cleanups, all the fixups are
113 // complete.
114 if (!hasNormalCleanups())
115 BranchFixups.clear();
116
117 // Otherwise we can still trim out unnecessary nulls.
118 else
119 popNullFixups();
120 }
121}
122
123EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
124 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
125 CatchDepth++;
126 return new (Buffer) EHFilterScope(NumFilters);
127}
128
129void EHScopeStack::popFilter() {
130 assert(!empty() && "popping exception stack when not empty");
131
132 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
133 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
134
John McCallad5d61e2010-07-23 21:56:41 +0000135 if (empty()) NextEHDestIndex = FirstEHDestIndex;
136
John McCallbd309292010-07-06 01:34:17 +0000137 assert(CatchDepth > 0 && "mismatched filter push/pop");
138 CatchDepth--;
139}
140
141EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
142 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
143 CatchDepth++;
John McCallad5d61e2010-07-23 21:56:41 +0000144 EHCatchScope *Scope = new (Buffer) EHCatchScope(NumHandlers);
145 for (unsigned I = 0; I != NumHandlers; ++I)
146 Scope->getHandlers()[I].Index = getNextEHDestIndex();
147 return Scope;
John McCallbd309292010-07-06 01:34:17 +0000148}
149
150void EHScopeStack::pushTerminate() {
151 char *Buffer = allocate(EHTerminateScope::getSize());
152 CatchDepth++;
John McCallad5d61e2010-07-23 21:56:41 +0000153 new (Buffer) EHTerminateScope(getNextEHDestIndex());
John McCallbd309292010-07-06 01:34:17 +0000154}
155
156/// Remove any 'null' fixups on the stack. However, we can't pop more
157/// fixups than the fixup depth on the innermost normal cleanup, or
158/// else fixups that we try to add to that cleanup will end up in the
159/// wrong place. We *could* try to shrink fixup depths, but that's
160/// actually a lot of work for little benefit.
161void EHScopeStack::popNullFixups() {
162 // We expect this to only be called when there's still an innermost
163 // normal cleanup; otherwise there really shouldn't be any fixups.
164 assert(hasNormalCleanups());
165
166 EHScopeStack::iterator it = find(InnermostNormalCleanup);
John McCallcda666c2010-07-21 07:22:38 +0000167 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
John McCallbd309292010-07-06 01:34:17 +0000168 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
169
170 while (BranchFixups.size() > MinSize &&
171 BranchFixups.back().Destination == 0)
172 BranchFixups.pop_back();
173}
174
John McCallce1de612011-01-26 04:00:11 +0000175llvm::Value *CodeGenFunction::initFullExprCleanup() {
176 // Create a variable to decide whether the cleanup needs to be run.
177 llvm::AllocaInst *run = CreateTempAlloca(Builder.getInt1Ty(), "cleanup.cond");
178
179 // Initialize it to false at a site that's guaranteed to be run
180 // before each evaluation.
181 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
John McCallf256eb52011-01-26 19:15:39 +0000182 new llvm::StoreInst(Builder.getFalse(), run, &block->back());
John McCallce1de612011-01-26 04:00:11 +0000183
184 // Initialize it to true at the current location.
185 Builder.CreateStore(Builder.getTrue(), run);
186
187 return run;
188}
189
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000190static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
191 // void *__cxa_allocate_exception(size_t thrown_size);
192 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
193 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump75546b82009-12-10 00:06:18 +0000194
195 const llvm::FunctionType *FTy =
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000196 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
197 Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000198
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000199 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
200}
201
Mike Stump33270212009-12-02 07:41:41 +0000202static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
203 // void __cxa_free_exception(void *thrown_exception);
204 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
205 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000206
207 const llvm::FunctionType *FTy =
Mike Stump33270212009-12-02 07:41:41 +0000208 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
209 Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000210
Mike Stump33270212009-12-02 07:41:41 +0000211 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
212}
213
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000214static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump75546b82009-12-10 00:06:18 +0000215 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +0000216 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000217
218 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
219 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000220
221 const llvm::FunctionType *FTy =
Mike Stumpd1782cc2009-11-20 00:56:31 +0000222 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
223 Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000224
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000225 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
226}
227
Mike Stumpd1782cc2009-11-20 00:56:31 +0000228static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +0000229 // void __cxa_rethrow();
Mike Stumpd1782cc2009-11-20 00:56:31 +0000230
Mike Stump75546b82009-12-10 00:06:18 +0000231 const llvm::FunctionType *FTy =
Mike Stumpd1782cc2009-11-20 00:56:31 +0000232 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump75546b82009-12-10 00:06:18 +0000233
Mike Stumpd1782cc2009-11-20 00:56:31 +0000234 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
235}
236
John McCallbd309292010-07-06 01:34:17 +0000237static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
238 // void *__cxa_get_exception_ptr(void*);
239 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
240 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
241
242 const llvm::FunctionType *FTy =
243 llvm::FunctionType::get(Int8PtrTy, Args, false);
244
245 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
246}
247
Mike Stump58ef18b2009-11-20 23:44:51 +0000248static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +0000249 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +0000250
251 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
252 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000253
254 const llvm::FunctionType *FTy =
Mike Stump54066142009-12-01 03:41:18 +0000255 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000256
Mike Stump58ef18b2009-11-20 23:44:51 +0000257 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
258}
259
260static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +0000261 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +0000262
Mike Stump75546b82009-12-10 00:06:18 +0000263 const llvm::FunctionType *FTy =
Mike Stump58ef18b2009-11-20 23:44:51 +0000264 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump75546b82009-12-10 00:06:18 +0000265
Mike Stump58ef18b2009-11-20 23:44:51 +0000266 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
267}
268
Mike Stump1d849212009-12-07 23:38:24 +0000269static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
270 // void __cxa_call_unexepcted(void *thrown_exception);
271
272 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
273 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000274
275 const llvm::FunctionType *FTy =
Mike Stump1d849212009-12-07 23:38:24 +0000276 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
277 Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000278
Mike Stump1d849212009-12-07 23:38:24 +0000279 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
280}
281
Douglas Gregor51150ab2010-05-16 01:24:12 +0000282llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
283 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump54066142009-12-01 03:41:18 +0000284 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000285
286 const llvm::FunctionType *FTy =
Douglas Gregor51150ab2010-05-16 01:24:12 +0000287 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump54066142009-12-01 03:41:18 +0000288 false);
Mike Stump75546b82009-12-10 00:06:18 +0000289
Douglas Gregor51150ab2010-05-16 01:24:12 +0000290 if (CGM.getLangOptions().SjLjExceptions)
John McCallffe46302010-08-11 20:59:53 +0000291 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor51150ab2010-05-16 01:24:12 +0000292 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump54066142009-12-01 03:41:18 +0000293}
294
Mike Stump33270212009-12-02 07:41:41 +0000295static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
296 // void __terminate();
297
Mike Stump75546b82009-12-10 00:06:18 +0000298 const llvm::FunctionType *FTy =
Mike Stump33270212009-12-02 07:41:41 +0000299 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump75546b82009-12-10 00:06:18 +0000300
David Chisnallf9c42252010-05-17 13:49:20 +0000301 return CGF.CGM.CreateRuntimeFunction(FTy,
302 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
303}
304
John McCall36ea3722010-07-17 00:43:08 +0000305static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCall0bdb1fd2010-09-16 06:16:50 +0000306 llvm::StringRef Name) {
John McCall36ea3722010-07-17 00:43:08 +0000307 const llvm::Type *Int8PtrTy =
308 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
309 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
310
311 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
312 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
313
314 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000315}
316
John McCall36ea3722010-07-17 00:43:08 +0000317const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall2faab302010-11-07 02:35:25 +0000318const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall36ea3722010-07-17 00:43:08 +0000319const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
320const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
321const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
322const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
323 "objc_exception_throw");
324
325static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000326 if (L.SjLjExceptions)
327 return EHPersonality::GNU_C_SJLJ;
John McCall36ea3722010-07-17 00:43:08 +0000328 return EHPersonality::GNU_C;
329}
330
331static const EHPersonality &getObjCPersonality(const LangOptions &L) {
332 if (L.NeXTRuntime) {
333 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
334 else return getCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000335 } else {
John McCall36ea3722010-07-17 00:43:08 +0000336 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000337 }
338}
339
John McCall36ea3722010-07-17 00:43:08 +0000340static const EHPersonality &getCXXPersonality(const LangOptions &L) {
341 if (L.SjLjExceptions)
342 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallbd309292010-07-06 01:34:17 +0000343 else
John McCall36ea3722010-07-17 00:43:08 +0000344 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000345}
346
347/// Determines the personality function to use when both C++
348/// and Objective-C exceptions are being caught.
John McCall36ea3722010-07-17 00:43:08 +0000349static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallbd309292010-07-06 01:34:17 +0000350 // The ObjC personality defers to the C++ personality for non-ObjC
351 // handlers. Unlike the C++ case, we use the same personality
352 // function on targets using (backend-driven) SJLJ EH.
John McCall36ea3722010-07-17 00:43:08 +0000353 if (L.NeXTRuntime) {
354 if (L.ObjCNonFragileABI)
355 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000356
357 // In the fragile ABI, just use C++ exception handling and hope
358 // they're not doing crazy exception mixing.
359 else
John McCall36ea3722010-07-17 00:43:08 +0000360 return getCXXPersonality(L);
Chandler Carruth0450cc62010-05-17 20:58:49 +0000361 }
David Chisnallf9c42252010-05-17 13:49:20 +0000362
John McCall36ea3722010-07-17 00:43:08 +0000363 // The GNU runtime's personality function inherently doesn't support
364 // mixed EH. Use the C++ personality just to avoid returning null.
365 return getCXXPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000366}
367
John McCall36ea3722010-07-17 00:43:08 +0000368const EHPersonality &EHPersonality::get(const LangOptions &L) {
369 if (L.CPlusPlus && L.ObjC1)
370 return getObjCXXPersonality(L);
371 else if (L.CPlusPlus)
372 return getCXXPersonality(L);
373 else if (L.ObjC1)
374 return getObjCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000375 else
John McCall36ea3722010-07-17 00:43:08 +0000376 return getCPersonality(L);
377}
John McCallbd309292010-07-06 01:34:17 +0000378
John McCall0bdb1fd2010-09-16 06:16:50 +0000379static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000380 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000381 llvm::Constant *Fn =
John McCall0bdb1fd2010-09-16 06:16:50 +0000382 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
383 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
384 true),
385 Personality.getPersonalityFnName());
386 return Fn;
387}
388
389static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
390 const EHPersonality &Personality) {
391 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
392 return llvm::ConstantExpr::getBitCast(Fn, CGM.PtrToInt8Ty);
393}
394
395/// Check whether a personality function could reasonably be swapped
396/// for a C++ personality function.
397static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
398 for (llvm::Constant::use_iterator
399 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
400 llvm::User *User = *I;
401
402 // Conditionally white-list bitcasts.
403 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
404 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
405 if (!PersonalityHasOnlyCXXUses(CE))
406 return false;
407 continue;
408 }
409
410 // Otherwise, it has to be a selector call.
411 if (!isa<llvm::EHSelectorInst>(User)) return false;
412
413 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
414 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
415 // Look for something that would've been returned by the ObjC
416 // runtime's GetEHType() method.
417 llvm::GlobalVariable *GV
418 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
419 if (!GV) continue;
420
421 // ObjC EH selector entries are always global variables with
422 // names starting like this.
423 if (GV->getName().startswith("OBJC_EHTYPE"))
424 return false;
425 }
426 }
427
428 return true;
429}
430
431/// Try to use the C++ personality function in ObjC++. Not doing this
432/// can cause some incompatibilities with gcc, which is more
433/// aggressive about only using the ObjC++ personality in a function
434/// when it really needs it.
435void CodeGenModule::SimplifyPersonality() {
436 // For now, this is really a Darwin-specific operation.
437 if (Context.Target.getTriple().getOS() != llvm::Triple::Darwin)
438 return;
439
440 // If we're not in ObjC++ -fexceptions, there's nothing to do.
441 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
442 return;
443
444 const EHPersonality &ObjCXX = EHPersonality::get(Features);
445 const EHPersonality &CXX = getCXXPersonality(Features);
446 if (&ObjCXX == &CXX ||
447 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
448 return;
449
450 llvm::Function *Fn =
451 getModule().getFunction(ObjCXX.getPersonalityFnName());
452
453 // Nothing to do if it's unused.
454 if (!Fn || Fn->use_empty()) return;
455
456 // Can't do the optimization if it has non-C++ uses.
457 if (!PersonalityHasOnlyCXXUses(Fn)) return;
458
459 // Create the C++ personality function and kill off the old
460 // function.
461 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
462
463 // This can happen if the user is screwing with us.
464 if (Fn->getType() != CXXFn->getType()) return;
465
466 Fn->replaceAllUsesWith(CXXFn);
467 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000468}
469
470/// Returns the value to inject into a selector to indicate the
471/// presence of a catch-all.
472static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
473 // Possibly we should use @llvm.eh.catch.all.value here.
474 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
475}
476
477/// Returns the value to inject into a selector to indicate the
478/// presence of a cleanup.
479static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
480 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump33270212009-12-02 07:41:41 +0000481}
482
John McCallbb026012010-07-13 21:17:51 +0000483namespace {
484 /// A cleanup to free the exception object if its initialization
485 /// throws.
John McCallcda666c2010-07-21 07:22:38 +0000486 struct FreeExceptionCleanup : EHScopeStack::Cleanup {
John McCallbb026012010-07-13 21:17:51 +0000487 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
488 llvm::Value *ExnLocVar)
489 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
490
491 llvm::Value *ShouldFreeVar;
492 llvm::Value *ExnLocVar;
493
494 void Emit(CodeGenFunction &CGF, bool IsForEH) {
495 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
496 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
497
498 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
499 "should-free-exnobj");
500 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
501 CGF.EmitBlock(FreeBB);
502 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
503 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
504 ->setDoesNotThrow();
505 CGF.EmitBlock(DoneBB);
506 }
507 };
508}
509
John McCall2e6567a2010-04-22 01:10:34 +0000510// Emits an exception expression into the given location. This
511// differs from EmitAnyExprToMem only in that, if a final copy-ctor
512// call is required, an exception within that copy ctor causes
513// std::terminate to be invoked.
514static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
515 llvm::Value *ExnLoc) {
516 // We want to release the allocated exception object if this
517 // expression throws. We do this by pushing an EH-only cleanup
518 // block which, furthermore, deactivates itself after the expression
519 // is complete.
520 llvm::AllocaInst *ShouldFreeVar =
521 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
522 "should-free-exnobj.var");
523 CGF.InitTempAlloca(ShouldFreeVar,
524 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump54066142009-12-01 03:41:18 +0000525
John McCall2e6567a2010-04-22 01:10:34 +0000526 // A variable holding the exception pointer. This is necessary
527 // because the throw expression does not necessarily dominate the
528 // cleanup, for example if it appears in a conditional expression.
529 llvm::AllocaInst *ExnLocVar =
530 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump75546b82009-12-10 00:06:18 +0000531
John McCallbd309292010-07-06 01:34:17 +0000532 // Make sure the exception object is cleaned up if there's an
533 // exception during initialization.
John McCallbb026012010-07-13 21:17:51 +0000534 // FIXME: stmt expressions might require this to be a normal
535 // cleanup, too.
John McCallcda666c2010-07-21 07:22:38 +0000536 CGF.EHStack.pushCleanup<FreeExceptionCleanup>(EHCleanup,
537 ShouldFreeVar,
538 ExnLocVar);
John McCallbd309292010-07-06 01:34:17 +0000539 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000540
541 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
542 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
543 ShouldFreeVar);
544
545 // __cxa_allocate_exception returns a void*; we need to cast this
546 // to the appropriate type for the object.
John McCall077dc602010-10-29 08:14:02 +0000547 const llvm::Type *Ty = CGF.ConvertTypeForMem(E->getType())->getPointerTo();
John McCall2e6567a2010-04-22 01:10:34 +0000548 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
549
550 // FIXME: this isn't quite right! If there's a final unelided call
551 // to a copy constructor, then according to [except.terminate]p1 we
552 // must call std::terminate() if that constructor throws, because
553 // technically that copy occurs after the exception expression is
554 // evaluated but before the exception is caught. But the best way
555 // to handle that is to teach EmitAggExpr to do the final copy
556 // differently if it can't be elided.
John McCall7a626f62010-09-15 10:14:12 +0000557 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false, /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000558
559 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
560 ShouldFreeVar);
561
John McCallbd309292010-07-06 01:34:17 +0000562 // Technically, the exception object is like a temporary; it has to
563 // be cleaned up when its full-expression is complete.
564 // Unfortunately, the AST represents full-expressions by creating a
John McCall5d413782010-12-06 08:20:24 +0000565 // ExprWithCleanups, which it only does when there are actually
John McCallbd309292010-07-06 01:34:17 +0000566 // temporaries.
567 //
568 // If any cleanups have been added since we pushed ours, they must
569 // be from temporaries; this will get popped at the same time.
570 // Otherwise we need to pop ours off. FIXME: this is very brittle.
571 if (Cleanup == CGF.EHStack.stable_begin())
572 CGF.PopCleanupBlock();
Mike Stump54066142009-12-01 03:41:18 +0000573}
574
John McCallbd309292010-07-06 01:34:17 +0000575llvm::Value *CodeGenFunction::getExceptionSlot() {
576 if (!ExceptionSlot) {
577 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
578 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump54066142009-12-01 03:41:18 +0000579 }
John McCallbd309292010-07-06 01:34:17 +0000580 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000581}
582
Anders Carlsson4b08db72009-10-30 01:42:31 +0000583void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000584 if (!E->getSubExpr()) {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000585 if (getInvokeDest()) {
John McCallbd309292010-07-06 01:34:17 +0000586 Builder.CreateInvoke(getReThrowFn(*this),
587 getUnreachableBlock(),
588 getInvokeDest())
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000589 ->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000590 } else {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000591 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000592 Builder.CreateUnreachable();
593 }
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000594
John McCall20f6ab82011-01-12 03:41:02 +0000595 // throw is an expression, and the expression emitters expect us
596 // to leave ourselves at a valid insertion point.
597 EmitBlock(createBasicBlock("throw.cont"));
598
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000599 return;
600 }
Mike Stump75546b82009-12-10 00:06:18 +0000601
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000602 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000603
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000604 // Now allocate the exception object.
605 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000606 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000607
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000608 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallbd309292010-07-06 01:34:17 +0000609 llvm::CallInst *ExceptionPtr =
Mike Stump75546b82009-12-10 00:06:18 +0000610 Builder.CreateCall(AllocExceptionFn,
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000611 llvm::ConstantInt::get(SizeTy, TypeSize),
612 "exception");
John McCallbd309292010-07-06 01:34:17 +0000613 ExceptionPtr->setDoesNotThrow();
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000614
John McCall2e6567a2010-04-22 01:10:34 +0000615 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000616
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000617 // Now throw the exception.
618 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlssonba840fb2011-01-24 01:59:49 +0000619 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
620 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000621
622 // The address of the destructor. If the exception type has a
623 // trivial destructor (or isn't a record), we just pass null.
624 llvm::Constant *Dtor = 0;
625 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
626 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
627 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000628 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCall2e6567a2010-04-22 01:10:34 +0000629 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
630 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
631 }
632 }
633 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000634
Mike Stump114ab9f2009-12-04 01:51:45 +0000635 if (getInvokeDest()) {
Mike Stump75546b82009-12-10 00:06:18 +0000636 llvm::InvokeInst *ThrowCall =
John McCallbd309292010-07-06 01:34:17 +0000637 Builder.CreateInvoke3(getThrowFn(*this),
638 getUnreachableBlock(), getInvokeDest(),
Mike Stump114ab9f2009-12-04 01:51:45 +0000639 ExceptionPtr, TypeInfo, Dtor);
640 ThrowCall->setDoesNotReturn();
Mike Stump114ab9f2009-12-04 01:51:45 +0000641 } else {
Mike Stump75546b82009-12-10 00:06:18 +0000642 llvm::CallInst *ThrowCall =
Mike Stump114ab9f2009-12-04 01:51:45 +0000643 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
644 ThrowCall->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000645 Builder.CreateUnreachable();
Mike Stump114ab9f2009-12-04 01:51:45 +0000646 }
Mike Stump75546b82009-12-10 00:06:18 +0000647
John McCall20f6ab82011-01-12 03:41:02 +0000648 // throw is an expression, and the expression emitters expect us
649 // to leave ourselves at a valid insertion point.
650 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000651}
Mike Stump58ef18b2009-11-20 23:44:51 +0000652
Mike Stump1d849212009-12-07 23:38:24 +0000653void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000654 if (!Exceptions)
655 return;
656
Mike Stump1d849212009-12-07 23:38:24 +0000657 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
658 if (FD == 0)
659 return;
660 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
661 if (Proto == 0)
662 return;
663
664 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
665
666 if (!Proto->hasExceptionSpec())
667 return;
668
John McCallbd309292010-07-06 01:34:17 +0000669 unsigned NumExceptions = Proto->getNumExceptions();
670 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000671
John McCallbd309292010-07-06 01:34:17 +0000672 for (unsigned I = 0; I != NumExceptions; ++I) {
673 QualType Ty = Proto->getExceptionType(I);
674 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
Anders Carlssonba840fb2011-01-24 01:59:49 +0000675 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
676 /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000677 Filter->setFilter(I, EHType);
Mike Stump1d849212009-12-07 23:38:24 +0000678 }
Mike Stump1d849212009-12-07 23:38:24 +0000679}
680
681void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000682 if (!Exceptions)
683 return;
684
Mike Stump1d849212009-12-07 23:38:24 +0000685 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
686 if (FD == 0)
687 return;
688 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
689 if (Proto == 0)
690 return;
691
692 if (!Proto->hasExceptionSpec())
693 return;
694
John McCallbd309292010-07-06 01:34:17 +0000695 EHStack.popFilter();
Mike Stump1d849212009-12-07 23:38:24 +0000696}
697
Mike Stump58ef18b2009-11-20 23:44:51 +0000698void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000699 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000700 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000701 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000702}
703
John McCallb609d3f2010-07-07 06:56:46 +0000704void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000705 unsigned NumHandlers = S.getNumHandlers();
706 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000707
John McCallbd309292010-07-06 01:34:17 +0000708 for (unsigned I = 0; I != NumHandlers; ++I) {
709 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000710
John McCallbd309292010-07-06 01:34:17 +0000711 llvm::BasicBlock *Handler = createBasicBlock("catch");
712 if (C->getExceptionDecl()) {
713 // FIXME: Dropping the reference type on the type into makes it
714 // impossible to correctly implement catch-by-reference
715 // semantics for pointers. Unfortunately, this is what all
716 // existing compilers do, and it's not clear that the standard
717 // personality routine is capable of doing this right. See C++ DR 388:
718 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
719 QualType CaughtType = C->getCaughtType();
720 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall2ca705e2010-07-24 00:37:23 +0000721
722 llvm::Value *TypeInfo = 0;
723 if (CaughtType->isObjCObjectPointerType())
724 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
725 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000726 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000727 CatchScope->setHandler(I, TypeInfo, Handler);
728 } else {
729 // No exception decl indicates '...', a catch-all.
730 CatchScope->setCatchAllHandler(I, Handler);
731 }
732 }
John McCallbd309292010-07-06 01:34:17 +0000733}
734
735/// Check whether this is a non-EH scope, i.e. a scope which doesn't
736/// affect exception handling. Currently, the only non-EH scopes are
737/// normal-only cleanup scopes.
738static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000739 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000740 case EHScope::Cleanup:
741 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000742 case EHScope::Filter:
743 case EHScope::Catch:
744 case EHScope::Terminate:
745 return false;
746 }
747
748 // Suppress warning.
749 return false;
John McCallbd309292010-07-06 01:34:17 +0000750}
751
752llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
753 assert(EHStack.requiresLandingPad());
754 assert(!EHStack.empty());
755
John McCall2b7fc382010-07-13 20:32:21 +0000756 if (!Exceptions)
757 return 0;
758
John McCallbd309292010-07-06 01:34:17 +0000759 // Check the innermost scope for a cached landing pad. If this is
760 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
761 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
762 if (LP) return LP;
763
764 // Build the landing pad for this scope.
765 LP = EmitLandingPad();
766 assert(LP);
767
768 // Cache the landing pad on the innermost scope. If this is a
769 // non-EH scope, cache the landing pad on the enclosing scope, too.
770 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
771 ir->setCachedLandingPad(LP);
772 if (!isNonEHScope(*ir)) break;
773 }
774
775 return LP;
776}
777
778llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
779 assert(EHStack.requiresLandingPad());
780
781 // This function contains a hack to work around a design flaw in
782 // LLVM's EH IR which breaks semantics after inlining. This same
783 // hack is implemented in llvm-gcc.
784 //
785 // The LLVM EH abstraction is basically a thin veneer over the
786 // traditional GCC zero-cost design: for each range of instructions
787 // in the function, there is (at most) one "landing pad" with an
788 // associated chain of EH actions. A language-specific personality
789 // function interprets this chain of actions and (1) decides whether
790 // or not to resume execution at the landing pad and (2) if so,
791 // provides an integer indicating why it's stopping. In LLVM IR,
792 // the association of a landing pad with a range of instructions is
793 // achieved via an invoke instruction, the chain of actions becomes
794 // the arguments to the @llvm.eh.selector call, and the selector
795 // call returns the integer indicator. Other than the required
796 // presence of two intrinsic function calls in the landing pad,
797 // the IR exactly describes the layout of the output code.
798 //
799 // A principal advantage of this design is that it is completely
800 // language-agnostic; in theory, the LLVM optimizers can treat
801 // landing pads neutrally, and targets need only know how to lower
802 // the intrinsics to have a functioning exceptions system (assuming
803 // that platform exceptions follow something approximately like the
804 // GCC design). Unfortunately, landing pads cannot be combined in a
805 // language-agnostic way: given selectors A and B, there is no way
806 // to make a single landing pad which faithfully represents the
807 // semantics of propagating an exception first through A, then
808 // through B, without knowing how the personality will interpret the
809 // (lowered form of the) selectors. This means that inlining has no
810 // choice but to crudely chain invokes (i.e., to ignore invokes in
811 // the inlined function, but to turn all unwindable calls into
812 // invokes), which is only semantically valid if every unwind stops
813 // at every landing pad.
814 //
815 // Therefore, the invoke-inline hack is to guarantee that every
816 // landing pad has a catch-all.
817 const bool UseInvokeInlineHack = true;
818
819 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
820 assert(ir != EHStack.end() &&
821 "stack requiring landing pad is nothing but non-EH scopes?");
822
823 // If this is a terminate scope, just use the singleton terminate
824 // landing pad.
825 if (isa<EHTerminateScope>(*ir))
826 return getTerminateLandingPad();
827
828 // If this isn't an EH scope, iterate; otherwise break out.
829 if (!isNonEHScope(*ir)) break;
830 ++ir;
831
832 // We haven't checked this scope for a cached landing pad yet.
833 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
834 return LP;
835 }
836
837 // Save the current IR generation state.
838 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
839
John McCall36ea3722010-07-17 00:43:08 +0000840 const EHPersonality &Personality =
841 EHPersonality::get(CGF.CGM.getLangOptions());
842
John McCallbd309292010-07-06 01:34:17 +0000843 // Create and configure the landing pad.
844 llvm::BasicBlock *LP = createBasicBlock("lpad");
845 EmitBlock(LP);
846
847 // Save the exception pointer. It's safe to use a single exception
848 // pointer per function because EH cleanups can never have nested
849 // try/catches.
850 llvm::CallInst *Exn =
851 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
852 Exn->setDoesNotThrow();
853 Builder.CreateStore(Exn, getExceptionSlot());
854
855 // Build the selector arguments.
856 llvm::SmallVector<llvm::Value*, 8> EHSelector;
857 EHSelector.push_back(Exn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000858 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallbd309292010-07-06 01:34:17 +0000859
860 // Accumulate all the handlers in scope.
John McCallad5d61e2010-07-23 21:56:41 +0000861 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
862 UnwindDest CatchAll;
John McCallbd309292010-07-06 01:34:17 +0000863 bool HasEHCleanup = false;
864 bool HasEHFilter = false;
865 llvm::SmallVector<llvm::Value*, 8> EHFilters;
866 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
867 I != E; ++I) {
868
869 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000870 case EHScope::Cleanup:
John McCall2b7fc382010-07-13 20:32:21 +0000871 if (!HasEHCleanup)
John McCallcda666c2010-07-21 07:22:38 +0000872 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000873 // We otherwise don't care about cleanups.
874 continue;
875
John McCallbd309292010-07-06 01:34:17 +0000876 case EHScope::Filter: {
877 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallad5d61e2010-07-23 21:56:41 +0000878 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000879
880 // Filter scopes get added to the selector in wierd ways.
881 EHFilterScope &Filter = cast<EHFilterScope>(*I);
882 HasEHFilter = true;
883
884 // Add all the filter values which we aren't already explicitly
885 // catching.
886 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
887 llvm::Value *FV = Filter.getFilter(I);
888 if (!EHHandlers.count(FV))
889 EHFilters.push_back(FV);
890 }
891 goto done;
892 }
893
894 case EHScope::Terminate:
895 // Terminate scopes are basically catch-alls.
John McCallad5d61e2010-07-23 21:56:41 +0000896 assert(!CatchAll.isValid());
897 CatchAll = UnwindDest(getTerminateHandler(),
898 EHStack.getEnclosingEHCleanup(I),
899 cast<EHTerminateScope>(*I).getDestIndex());
John McCallbd309292010-07-06 01:34:17 +0000900 goto done;
901
902 case EHScope::Catch:
903 break;
904 }
905
906 EHCatchScope &Catch = cast<EHCatchScope>(*I);
907 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
908 EHCatchScope::Handler Handler = Catch.getHandler(HI);
909
910 // Catch-all. We should only have one of these per catch.
911 if (!Handler.Type) {
John McCallad5d61e2010-07-23 21:56:41 +0000912 assert(!CatchAll.isValid());
913 CatchAll = UnwindDest(Handler.Block,
914 EHStack.getEnclosingEHCleanup(I),
915 Handler.Index);
John McCallbd309292010-07-06 01:34:17 +0000916 continue;
917 }
918
919 // Check whether we already have a handler for this type.
John McCallad5d61e2010-07-23 21:56:41 +0000920 UnwindDest &Dest = EHHandlers[Handler.Type];
921 if (Dest.isValid()) continue;
John McCallbd309292010-07-06 01:34:17 +0000922
923 EHSelector.push_back(Handler.Type);
John McCallad5d61e2010-07-23 21:56:41 +0000924 Dest = UnwindDest(Handler.Block,
925 EHStack.getEnclosingEHCleanup(I),
926 Handler.Index);
John McCallbd309292010-07-06 01:34:17 +0000927 }
928
929 // Stop if we found a catch-all.
John McCallad5d61e2010-07-23 21:56:41 +0000930 if (CatchAll.isValid()) break;
John McCallbd309292010-07-06 01:34:17 +0000931 }
932
933 done:
934 unsigned LastToEmitInLoop = EHSelector.size();
935
936 // If we have a catch-all, add null to the selector.
John McCallad5d61e2010-07-23 21:56:41 +0000937 if (CatchAll.isValid()) {
John McCallbd309292010-07-06 01:34:17 +0000938 EHSelector.push_back(getCatchAllValue(CGF));
939
940 // If we have an EH filter, we need to add those handlers in the
941 // right place in the selector, which is to say, at the end.
942 } else if (HasEHFilter) {
943 // Create a filter expression: an integer constant saying how many
944 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
945 // followed by the filter types. The personality routine only
946 // lands here if the filter doesn't match.
947 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
948 EHFilters.size() + 1));
949 EHSelector.append(EHFilters.begin(), EHFilters.end());
950
951 // Also check whether we need a cleanup.
952 if (UseInvokeInlineHack || HasEHCleanup)
953 EHSelector.push_back(UseInvokeInlineHack
954 ? getCatchAllValue(CGF)
955 : getCleanupValue(CGF));
956
957 // Otherwise, signal that we at least have cleanups.
958 } else if (UseInvokeInlineHack || HasEHCleanup) {
959 EHSelector.push_back(UseInvokeInlineHack
960 ? getCatchAllValue(CGF)
961 : getCleanupValue(CGF));
962 } else {
963 assert(LastToEmitInLoop > 2);
964 LastToEmitInLoop--;
965 }
966
967 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
968
969 // Tell the backend how to generate the landing pad.
970 llvm::CallInst *Selection =
971 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
972 EHSelector.begin(), EHSelector.end(), "eh.selector");
973 Selection->setDoesNotThrow();
974
975 // Select the right handler.
976 llvm::Value *llvm_eh_typeid_for =
977 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
978
979 // The results of llvm_eh_typeid_for aren't reliable --- at least
980 // not locally --- so we basically have to do this as an 'if' chain.
981 // We walk through the first N-1 catch clauses, testing and chaining,
982 // and then fall into the final clause (which is either a cleanup, a
983 // filter (possibly with a cleanup), a catch-all, or another catch).
984 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
985 llvm::Value *Type = EHSelector[I];
John McCallad5d61e2010-07-23 21:56:41 +0000986 UnwindDest Dest = EHHandlers[Type];
987 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallbd309292010-07-06 01:34:17 +0000988
989 // Figure out where to branch on a match. As a debug code-size
990 // optimization, if the scope depth matches the innermost cleanup,
991 // we branch directly to the catch handler.
John McCallad5d61e2010-07-23 21:56:41 +0000992 llvm::BasicBlock *Match = Dest.getBlock();
993 bool MatchNeedsCleanup =
994 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallbd309292010-07-06 01:34:17 +0000995 if (MatchNeedsCleanup)
996 Match = createBasicBlock("eh.match");
997
998 llvm::BasicBlock *Next = createBasicBlock("eh.next");
999
1000 // Check whether the exception matches.
1001 llvm::CallInst *Id
1002 = Builder.CreateCall(llvm_eh_typeid_for,
1003 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
1004 Id->setDoesNotThrow();
1005 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
1006 Match, Next);
1007
1008 // Emit match code if necessary.
1009 if (MatchNeedsCleanup) {
1010 EmitBlock(Match);
1011 EmitBranchThroughEHCleanup(Dest);
1012 }
1013
1014 // Continue to the next match.
1015 EmitBlock(Next);
1016 }
1017
1018 // Emit the final case in the selector.
1019 // This might be a catch-all....
John McCallad5d61e2010-07-23 21:56:41 +00001020 if (CatchAll.isValid()) {
John McCallbd309292010-07-06 01:34:17 +00001021 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
1022 EmitBranchThroughEHCleanup(CatchAll);
1023
1024 // ...or an EH filter...
1025 } else if (HasEHFilter) {
1026 llvm::Value *SavedSelection = Selection;
1027
1028 // First, unwind out to the outermost scope if necessary.
1029 if (EHStack.hasEHCleanups()) {
1030 // The end here might not dominate the beginning, so we might need to
1031 // save the selector if we need it.
1032 llvm::AllocaInst *SelectorVar = 0;
1033 if (HasEHCleanup) {
1034 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
1035 Builder.CreateStore(Selection, SelectorVar);
1036 }
1037
1038 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallad5d61e2010-07-23 21:56:41 +00001039 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
1040 EHStack.getNextEHDestIndex()));
John McCallbd309292010-07-06 01:34:17 +00001041 EmitBlock(CleanupContBB);
1042
1043 if (HasEHCleanup)
1044 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
1045 }
1046
1047 // If there was a cleanup, we'll need to actually check whether we
1048 // landed here because the filter triggered.
1049 if (UseInvokeInlineHack || HasEHCleanup) {
1050 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
1051 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
1052
1053 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
1054 llvm::Value *FailsFilter =
1055 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
1056 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
1057
1058 // The rethrow block is where we land if this was a cleanup.
1059 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
1060 EmitBlock(RethrowBB);
1061 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
1062 Builder.CreateLoad(getExceptionSlot()))
1063 ->setDoesNotReturn();
1064 Builder.CreateUnreachable();
1065
1066 EmitBlock(UnexpectedBB);
1067 }
1068
1069 // Call __cxa_call_unexpected. This doesn't need to be an invoke
1070 // because __cxa_call_unexpected magically filters exceptions
1071 // according to the last landing pad the exception was thrown
1072 // into. Seriously.
1073 Builder.CreateCall(getUnexpectedFn(*this),
1074 Builder.CreateLoad(getExceptionSlot()))
1075 ->setDoesNotReturn();
1076 Builder.CreateUnreachable();
1077
1078 // ...or a normal catch handler...
1079 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
1080 llvm::Value *Type = EHSelector.back();
1081 EmitBranchThroughEHCleanup(EHHandlers[Type]);
1082
1083 // ...or a cleanup.
1084 } else {
John McCallad5d61e2010-07-23 21:56:41 +00001085 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallbd309292010-07-06 01:34:17 +00001086 }
1087
1088 // Restore the old IR generation state.
1089 Builder.restoreIP(SavedIP);
1090
1091 return LP;
1092}
1093
John McCall5c08ab92010-07-13 22:12:14 +00001094namespace {
1095 /// A cleanup to call __cxa_end_catch. In many cases, the caught
1096 /// exception type lets us state definitively that the thrown exception
1097 /// type does not have a destructor. In particular:
1098 /// - Catch-alls tell us nothing, so we have to conservatively
1099 /// assume that the thrown exception might have a destructor.
1100 /// - Catches by reference behave according to their base types.
1101 /// - Catches of non-record types will only trigger for exceptions
1102 /// of non-record types, which never have destructors.
1103 /// - Catches of record types can trigger for arbitrary subclasses
1104 /// of the caught type, so we have to assume the actual thrown
1105 /// exception type might have a throwing destructor, even if the
1106 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +00001107 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +00001108 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1109 bool MightThrow;
1110
1111 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1112 if (!MightThrow) {
1113 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1114 return;
1115 }
1116
1117 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1118 }
1119 };
1120}
1121
John McCallbd309292010-07-06 01:34:17 +00001122/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1123/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001124///
1125/// \param EndMightThrow - true if __cxa_end_catch might throw
1126static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1127 llvm::Value *Exn,
1128 bool EndMightThrow) {
John McCallbd309292010-07-06 01:34:17 +00001129 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1130 Call->setDoesNotThrow();
1131
John McCallcda666c2010-07-21 07:22:38 +00001132 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +00001133
1134 return Call;
1135}
1136
1137/// A "special initializer" callback for initializing a catch
1138/// parameter during catch initialization.
1139static void InitCatchParam(CodeGenFunction &CGF,
1140 const VarDecl &CatchParam,
1141 llvm::Value *ParamAddr) {
1142 // Load the exception from where the landing pad saved it.
1143 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1144
1145 CanQualType CatchType =
1146 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1147 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1148
1149 // If we're catching by reference, we can just cast the object
1150 // pointer to the appropriate pointer.
1151 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +00001152 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1153 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +00001154
John McCallbd309292010-07-06 01:34:17 +00001155 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +00001156 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +00001157
1158 // We have no way to tell the personality function that we're
1159 // catching by reference, so if we're catching a pointer,
1160 // __cxa_begin_catch will actually return that pointer by value.
1161 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1162 QualType PointeeType = PT->getPointeeType();
1163
1164 // When catching by reference, generally we should just ignore
1165 // this by-value pointer and use the exception object instead.
1166 if (!PointeeType->isRecordType()) {
1167
1168 // Exn points to the struct _Unwind_Exception header, which
1169 // we have to skip past in order to reach the exception data.
1170 unsigned HeaderSize =
1171 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1172 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1173
1174 // However, if we're catching a pointer-to-record type that won't
1175 // work, because the personality function might have adjusted
1176 // the pointer. There's actually no way for us to fully satisfy
1177 // the language/ABI contract here: we can't use Exn because it
1178 // might have the wrong adjustment, but we can't use the by-value
1179 // pointer because it's off by a level of abstraction.
1180 //
1181 // The current solution is to dump the adjusted pointer into an
1182 // alloca, which breaks language semantics (because changing the
1183 // pointer doesn't change the exception) but at least works.
1184 // The better solution would be to filter out non-exact matches
1185 // and rethrow them, but this is tricky because the rethrow
1186 // really needs to be catchable by other sites at this landing
1187 // pad. The best solution is to fix the personality function.
1188 } else {
1189 // Pull the pointer for the reference type off.
1190 const llvm::Type *PtrTy =
1191 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1192
1193 // Create the temporary and write the adjusted pointer into it.
1194 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1195 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1196 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1197
1198 // Bind the reference to the temporary.
1199 AdjustedExn = ExnPtrTmp;
1200 }
1201 }
1202
John McCallbd309292010-07-06 01:34:17 +00001203 llvm::Value *ExnCast =
1204 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1205 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1206 return;
1207 }
1208
1209 // Non-aggregates (plus complexes).
1210 bool IsComplex = false;
1211 if (!CGF.hasAggregateLLVMType(CatchType) ||
1212 (IsComplex = CatchType->isAnyComplexType())) {
John McCall5c08ab92010-07-13 22:12:14 +00001213 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +00001214
1215 // If the catch type is a pointer type, __cxa_begin_catch returns
1216 // the pointer by value.
1217 if (CatchType->hasPointerRepresentation()) {
1218 llvm::Value *CastExn =
1219 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1220 CGF.Builder.CreateStore(CastExn, ParamAddr);
1221 return;
1222 }
1223
1224 // Otherwise, it returns a pointer into the exception object.
1225
1226 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1227 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1228
1229 if (IsComplex) {
1230 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1231 ParamAddr, /*volatile*/ false);
1232 } else {
Daniel Dunbar03816342010-08-21 02:24:36 +00001233 unsigned Alignment =
1234 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallbd309292010-07-06 01:34:17 +00001235 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar03816342010-08-21 02:24:36 +00001236 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1237 CatchType);
John McCallbd309292010-07-06 01:34:17 +00001238 }
1239 return;
1240 }
1241
1242 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1243 // initializer expression.
1244
1245 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1246 assert(RD && "aggregate catch type was not a record!");
1247
1248 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1249
1250 if (RD->hasTrivialCopyConstructor()) {
John McCall5c08ab92010-07-13 22:12:14 +00001251 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001252 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1253 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1254 return;
1255 }
1256
1257 // We have to call __cxa_get_exception_ptr to get the adjusted
1258 // pointer before copying.
1259 llvm::CallInst *AdjustedExn =
1260 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1261 AdjustedExn->setDoesNotThrow();
1262 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1263
1264 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1265 assert(CD && "record has no copy constructor!");
1266 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1267
1268 CallArgList CallArgs;
1269 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1270 CD->getThisType(CGF.getContext())));
1271 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1272 CD->getParamDecl(0)->getType()));
1273
1274 const FunctionProtoType *FPT
1275 = CD->getType()->getAs<FunctionProtoType>();
1276
1277 // Call the copy ctor in a terminate scope.
1278 CGF.EHStack.pushTerminate();
1279 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1280 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1281 CGF.EHStack.popTerminate();
1282
1283 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001284 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001285}
1286
1287/// Begins a catch statement by initializing the catch variable and
1288/// calling __cxa_begin_catch.
1289static void BeginCatch(CodeGenFunction &CGF,
1290 const CXXCatchStmt *S) {
1291 // We have to be very careful with the ordering of cleanups here:
1292 // C++ [except.throw]p4:
1293 // The destruction [of the exception temporary] occurs
1294 // immediately after the destruction of the object declared in
1295 // the exception-declaration in the handler.
1296 //
1297 // So the precise ordering is:
1298 // 1. Construct catch variable.
1299 // 2. __cxa_begin_catch
1300 // 3. Enter __cxa_end_catch cleanup
1301 // 4. Enter dtor cleanup
1302 //
1303 // We do this by initializing the exception variable with a
1304 // "special initializer", InitCatchParam. Delegation sequence:
1305 // - ExitCXXTryStmt opens a RunCleanupsScope
1306 // - EmitLocalBlockVarDecl creates the variable and debug info
1307 // - InitCatchParam initializes the variable from the exception
1308 // - CallBeginCatch calls __cxa_begin_catch
1309 // - CallBeginCatch enters the __cxa_end_catch cleanup
1310 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1311 // - EmitCXXTryStmt emits the code for the catch body
1312 // - EmitCXXTryStmt close the RunCleanupsScope
1313
1314 VarDecl *CatchParam = S->getExceptionDecl();
1315 if (!CatchParam) {
1316 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall5c08ab92010-07-13 22:12:14 +00001317 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001318 return;
1319 }
1320
1321 // Emit the local.
John McCall1c9c3fd2010-10-15 04:57:14 +00001322 CGF.EmitAutoVarDecl(*CatchParam, &InitCatchParam);
John McCallb81884d2010-02-19 09:25:03 +00001323}
1324
John McCall5c0e69e2010-07-13 22:24:23 +00001325namespace {
John McCallcda666c2010-07-21 07:22:38 +00001326 struct CallRethrow : EHScopeStack::Cleanup {
John McCall5c0e69e2010-07-13 22:24:23 +00001327 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1328 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1329 }
1330 };
1331}
1332
John McCallb609d3f2010-07-07 06:56:46 +00001333void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001334 unsigned NumHandlers = S.getNumHandlers();
1335 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1336 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001337
John McCallbd309292010-07-06 01:34:17 +00001338 // Copy the handler blocks off before we pop the EH stack. Emitting
1339 // the handlers might scribble on this memory.
1340 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1341 memcpy(Handlers.data(), CatchScope.begin(),
1342 NumHandlers * sizeof(EHCatchScope::Handler));
1343 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001344
John McCallbd309292010-07-06 01:34:17 +00001345 // The fall-through block.
1346 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001347
John McCallbd309292010-07-06 01:34:17 +00001348 // We just emitted the body of the try; jump to the continue block.
1349 if (HaveInsertPoint())
1350 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001351
John McCallb609d3f2010-07-07 06:56:46 +00001352 // Determine if we need an implicit rethrow for all these catch handlers.
1353 bool ImplicitRethrow = false;
1354 if (IsFnTryBlock)
1355 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1356 isa<CXXConstructorDecl>(CurCodeDecl);
1357
John McCallbd309292010-07-06 01:34:17 +00001358 for (unsigned I = 0; I != NumHandlers; ++I) {
1359 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1360 EmitBlock(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001361
John McCallbd309292010-07-06 01:34:17 +00001362 // Catch the exception if this isn't a catch-all.
1363 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump58ef18b2009-11-20 23:44:51 +00001364
John McCallbd309292010-07-06 01:34:17 +00001365 // Enter a cleanup scope, including the catch variable and the
1366 // end-catch.
1367 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001368
John McCallbd309292010-07-06 01:34:17 +00001369 // Initialize the catch variable and set up the cleanups.
1370 BeginCatch(*this, C);
1371
John McCallb609d3f2010-07-07 06:56:46 +00001372 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCall5c0e69e2010-07-13 22:24:23 +00001373 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1374 // called, and so it is pushed after BeginCatch.
1375 if (ImplicitRethrow)
John McCallcda666c2010-07-21 07:22:38 +00001376 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCallb609d3f2010-07-07 06:56:46 +00001377
John McCallbd309292010-07-06 01:34:17 +00001378 // Perform the body of the catch.
1379 EmitStmt(C->getHandlerBlock());
1380
1381 // Fall out through the catch cleanups.
1382 CatchScope.ForceCleanup();
1383
1384 // Branch out of the try.
1385 if (HaveInsertPoint())
1386 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001387 }
1388
John McCallbd309292010-07-06 01:34:17 +00001389 EmitBlock(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001390}
Mike Stumpaff69af2009-12-09 03:35:49 +00001391
John McCall1e670402010-07-21 00:52:03 +00001392namespace {
John McCallcda666c2010-07-21 07:22:38 +00001393 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001394 llvm::Value *ForEHVar;
1395 llvm::Value *EndCatchFn;
1396 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1397 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1398
1399 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1400 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1401 llvm::BasicBlock *CleanupContBB =
1402 CGF.createBasicBlock("finally.cleanup.cont");
1403
1404 llvm::Value *ShouldEndCatch =
1405 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1406 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1407 CGF.EmitBlock(EndCatchBB);
1408 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1409 CGF.EmitBlock(CleanupContBB);
1410 }
1411 };
John McCall906da4b2010-07-21 05:47:49 +00001412
John McCallcda666c2010-07-21 07:22:38 +00001413 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001414 const Stmt *Body;
1415 llvm::Value *ForEHVar;
1416 llvm::Value *EndCatchFn;
1417 llvm::Value *RethrowFn;
1418 llvm::Value *SavedExnVar;
1419
1420 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1421 llvm::Value *EndCatchFn,
1422 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1423 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1424 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1425
1426 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1427 // Enter a cleanup to call the end-catch function if one was provided.
1428 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001429 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1430 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001431
John McCallcebe0ca2010-08-11 00:16:14 +00001432 // Save the current cleanup destination in case there are
1433 // cleanups in the finally block.
1434 llvm::Value *SavedCleanupDest =
1435 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1436 "cleanup.dest.saved");
1437
John McCall906da4b2010-07-21 05:47:49 +00001438 // Emit the finally block.
1439 CGF.EmitStmt(Body);
1440
1441 // If the end of the finally is reachable, check whether this was
1442 // for EH. If so, rethrow.
1443 if (CGF.HaveInsertPoint()) {
1444 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1445 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1446
1447 llvm::Value *ShouldRethrow =
1448 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1449 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1450
1451 CGF.EmitBlock(RethrowBB);
1452 if (SavedExnVar) {
1453 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1454 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1455 } else {
1456 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1457 }
1458 CGF.Builder.CreateUnreachable();
1459
1460 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001461
1462 // Restore the cleanup destination.
1463 CGF.Builder.CreateStore(SavedCleanupDest,
1464 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001465 }
1466
1467 // Leave the end-catch cleanup. As an optimization, pretend that
1468 // the fallthrough path was inaccessible; we've dynamically proven
1469 // that we're not in the EH case along that path.
1470 if (EndCatchFn) {
1471 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1472 CGF.PopCleanupBlock();
1473 CGF.Builder.restoreIP(SavedIP);
1474 }
1475
1476 // Now make sure we actually have an insertion point or the
1477 // cleanup gods will hate us.
1478 CGF.EnsureInsertPoint();
1479 }
1480 };
John McCall1e670402010-07-21 00:52:03 +00001481}
1482
John McCallbd309292010-07-06 01:34:17 +00001483/// Enters a finally block for an implementation using zero-cost
1484/// exceptions. This is mostly general, but hard-codes some
1485/// language/ABI-specific behavior in the catch-all sections.
1486CodeGenFunction::FinallyInfo
1487CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1488 llvm::Constant *BeginCatchFn,
1489 llvm::Constant *EndCatchFn,
1490 llvm::Constant *RethrowFn) {
1491 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1492 "begin/end catch functions not paired");
1493 assert(RethrowFn && "rethrow function is required");
Mike Stumpaff69af2009-12-09 03:35:49 +00001494
John McCallbd309292010-07-06 01:34:17 +00001495 // The rethrow function has one of the following two types:
1496 // void (*)()
1497 // void (*)(void*)
1498 // In the latter case we need to pass it the exception object.
1499 // But we can't use the exception slot because the @finally might
1500 // have a landing pad (which would overwrite the exception slot).
1501 const llvm::FunctionType *RethrowFnTy =
1502 cast<llvm::FunctionType>(
1503 cast<llvm::PointerType>(RethrowFn->getType())
1504 ->getElementType());
1505 llvm::Value *SavedExnVar = 0;
1506 if (RethrowFnTy->getNumParams())
1507 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001508
John McCallbd309292010-07-06 01:34:17 +00001509 // A finally block is a statement which must be executed on any edge
1510 // out of a given scope. Unlike a cleanup, the finally block may
1511 // contain arbitrary control flow leading out of itself. In
1512 // addition, finally blocks should always be executed, even if there
1513 // are no catch handlers higher on the stack. Therefore, we
1514 // surround the protected scope with a combination of a normal
1515 // cleanup (to catch attempts to break out of the block via normal
1516 // control flow) and an EH catch-all (semantically "outside" any try
1517 // statement to which the finally block might have been attached).
1518 // The finally block itself is generated in the context of a cleanup
1519 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001520
John McCallbd309292010-07-06 01:34:17 +00001521 FinallyInfo Info;
John McCall21886962010-04-21 10:05:39 +00001522
John McCallbd309292010-07-06 01:34:17 +00001523 // Jump destination for performing the finally block on an exception
1524 // edge. We'll never actually reach this block, so unreachable is
1525 // fine.
1526 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001527
John McCallbd309292010-07-06 01:34:17 +00001528 // Whether the finally block is being executed for EH purposes.
1529 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1530 "finally.for-eh");
1531 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpaff69af2009-12-09 03:35:49 +00001532
John McCallbd309292010-07-06 01:34:17 +00001533 // Enter a normal cleanup which will perform the @finally block.
John McCallcda666c2010-07-21 07:22:38 +00001534 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1535 ForEHVar, EndCatchFn,
1536 RethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001537
1538 // Enter a catch-all scope.
1539 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1540 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1541 Builder.SetInsertPoint(CatchAllBB);
1542
1543 // If there's a begin-catch function, call it.
1544 if (BeginCatchFn) {
1545 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1546 ->setDoesNotThrow();
1547 }
1548
1549 // If we need to remember the exception pointer to rethrow later, do so.
1550 if (SavedExnVar) {
1551 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1552 Builder.CreateStore(SavedExn, SavedExnVar);
1553 }
1554
1555 // Tell the finally block that we're in EH.
1556 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1557
1558 // Thread a jump through the finally cleanup.
1559 EmitBranchThroughCleanup(RethrowDest);
1560
1561 Builder.restoreIP(SavedIP);
1562
1563 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1564 CatchScope->setCatchAllHandler(0, CatchAllBB);
1565
1566 return Info;
1567}
1568
1569void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1570 // Leave the finally catch-all.
1571 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1572 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1573 EHStack.popCatch();
1574
1575 // And leave the normal cleanup.
1576 PopCleanupBlock();
1577
1578 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1579 EmitBlock(CatchAllBB, true);
1580
1581 Builder.restoreIP(SavedIP);
1582}
1583
1584llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1585 if (TerminateLandingPad)
1586 return TerminateLandingPad;
1587
1588 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1589
1590 // This will get inserted at the end of the function.
1591 TerminateLandingPad = createBasicBlock("terminate.lpad");
1592 Builder.SetInsertPoint(TerminateLandingPad);
1593
1594 // Tell the backend that this is a landing pad.
1595 llvm::CallInst *Exn =
1596 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1597 Exn->setDoesNotThrow();
John McCall36ea3722010-07-17 00:43:08 +00001598
1599 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallbd309292010-07-06 01:34:17 +00001600
1601 // Tell the backend what the exception table should be:
1602 // nothing but a catch-all.
John McCall0bdb1fd2010-09-16 06:16:50 +00001603 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallbd309292010-07-06 01:34:17 +00001604 getCatchAllValue(*this) };
1605 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1606 Args, Args+3, "eh.selector")
1607 ->setDoesNotThrow();
1608
1609 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1610 TerminateCall->setDoesNotReturn();
1611 TerminateCall->setDoesNotThrow();
Mike Stumpaff69af2009-12-09 03:35:49 +00001612 CGF.Builder.CreateUnreachable();
1613
John McCallbd309292010-07-06 01:34:17 +00001614 // Restore the saved insertion state.
1615 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001616
John McCallbd309292010-07-06 01:34:17 +00001617 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001618}
Mike Stump2b488872009-12-09 22:59:31 +00001619
1620llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001621 if (TerminateHandler)
1622 return TerminateHandler;
1623
John McCallbd309292010-07-06 01:34:17 +00001624 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001625
John McCallbd309292010-07-06 01:34:17 +00001626 // Set up the terminate handler. This block is inserted at the very
1627 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001628 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001629 Builder.SetInsertPoint(TerminateHandler);
1630 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump2b488872009-12-09 22:59:31 +00001631 TerminateCall->setDoesNotReturn();
1632 TerminateCall->setDoesNotThrow();
1633 Builder.CreateUnreachable();
1634
John McCall21886962010-04-21 10:05:39 +00001635 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001636 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001637
Mike Stump2b488872009-12-09 22:59:31 +00001638 return TerminateHandler;
1639}
John McCallbd309292010-07-06 01:34:17 +00001640
John McCallad5d61e2010-07-23 21:56:41 +00001641CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1642 if (RethrowBlock.isValid()) return RethrowBlock;
1643
1644 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1645
1646 // We emit a jump to a notional label at the outermost unwind state.
1647 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1648 Builder.SetInsertPoint(Unwind);
1649
1650 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1651
1652 // This can always be a call because we necessarily didn't find
1653 // anything on the EH stack which needs our help.
John McCall0bdb1fd2010-09-16 06:16:50 +00001654 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCallad5d61e2010-07-23 21:56:41 +00001655 llvm::Constant *RethrowFn;
John McCall0bdb1fd2010-09-16 06:16:50 +00001656 if (!RethrowName.empty())
John McCallad5d61e2010-07-23 21:56:41 +00001657 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1658 else
1659 RethrowFn = getUnwindResumeOrRethrowFn();
1660
1661 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1662 ->setDoesNotReturn();
1663 Builder.CreateUnreachable();
1664
1665 Builder.restoreIP(SavedIP);
1666
1667 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1668 return RethrowBlock;
1669}
1670
John McCallcda666c2010-07-21 07:22:38 +00001671EHScopeStack::Cleanup::~Cleanup() {
1672 llvm_unreachable("Cleanup is indestructable");
John McCall11e577b2010-07-13 23:19:49 +00001673}
John McCallce1de612011-01-26 04:00:11 +00001674
1675void EHScopeStack::ConditionalCleanup::Emit(CodeGenFunction &CGF,
1676 bool IsForEHCleanup) {
1677 // Determine whether we should run the cleanup.
1678 llvm::Value *condVal = CGF.Builder.CreateLoad(cond, "cond.should-run");
1679
1680 llvm::BasicBlock *cleanup = CGF.createBasicBlock("cond-cleanup.run");
1681 llvm::BasicBlock *cont = CGF.createBasicBlock("cond-cleanup.cont");
1682
1683 // If we shouldn't run the cleanup, jump directly to the continuation block.
1684 CGF.Builder.CreateCondBr(condVal, cleanup, cont);
1685 CGF.EmitBlock(cleanup);
1686
1687 // Emit the core of the cleanup.
1688 EmitImpl(CGF, IsForEHCleanup);
1689 assert(CGF.HaveInsertPoint() && "cleanup didn't end with valid IP!");
1690
1691 // Fall into the continuation block.
1692 CGF.EmitBlock(cont);
1693}