blob: d31cab5194985f465415e5631edac705b181e45a [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 McCallbd309292010-07-06 01:34:17 +000017#include "llvm/Support/CallSite.h"
Mike Stump58ef18b2009-11-20 23:44:51 +000018
Anders Carlsson4b08db72009-10-30 01:42:31 +000019#include "CodeGenFunction.h"
John McCallbd309292010-07-06 01:34:17 +000020#include "CGException.h"
John McCall5add20c2010-07-20 22:17:55 +000021#include "TargetInfo.h"
John McCallbd309292010-07-06 01:34:17 +000022
Anders Carlsson4b08db72009-10-30 01:42:31 +000023using namespace clang;
24using namespace CodeGen;
25
John McCallbd309292010-07-06 01:34:17 +000026/// Push an entry of the given size onto this protected-scope stack.
27char *EHScopeStack::allocate(size_t Size) {
28 if (!StartOfBuffer) {
29 unsigned Capacity = 1024;
30 while (Capacity < Size) Capacity *= 2;
31 StartOfBuffer = new char[Capacity];
32 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
33 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
34 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
35 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
36
37 unsigned NewCapacity = CurrentCapacity;
38 do {
39 NewCapacity *= 2;
40 } while (NewCapacity < UsedCapacity + Size);
41
42 char *NewStartOfBuffer = new char[NewCapacity];
43 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
44 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
45 memcpy(NewStartOfData, StartOfData, UsedCapacity);
46 delete [] StartOfBuffer;
47 StartOfBuffer = NewStartOfBuffer;
48 EndOfBuffer = NewEndOfBuffer;
49 StartOfData = NewStartOfData;
50 }
51
52 assert(StartOfBuffer + Size <= StartOfData);
53 StartOfData -= Size;
54 return StartOfData;
55}
56
57EHScopeStack::stable_iterator
58EHScopeStack::getEnclosingEHCleanup(iterator it) const {
59 assert(it != end());
60 do {
John McCallcda666c2010-07-21 07:22:38 +000061 if (isa<EHCleanupScope>(*it)) {
62 if (cast<EHCleanupScope>(*it).isEHCleanup())
John McCall2b7fc382010-07-13 20:32:21 +000063 return stabilize(it);
John McCallcda666c2010-07-21 07:22:38 +000064 return cast<EHCleanupScope>(*it).getEnclosingEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +000065 }
John McCallbd309292010-07-06 01:34:17 +000066 ++it;
67 } while (it != end());
68 return stable_end();
69}
70
71
John McCallcda666c2010-07-21 07:22:38 +000072void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCall2b7fc382010-07-13 20:32:21 +000073 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
John McCallcda666c2010-07-21 07:22:38 +000074 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
John McCall2b7fc382010-07-13 20:32:21 +000075 bool IsNormalCleanup = Kind != EHCleanup;
76 bool IsEHCleanup = Kind != NormalCleanup;
John McCallcda666c2010-07-21 07:22:38 +000077 EHCleanupScope *Scope =
78 new (Buffer) EHCleanupScope(IsNormalCleanup,
79 IsEHCleanup,
80 Size,
81 BranchFixups.size(),
82 InnermostNormalCleanup,
83 InnermostEHCleanup);
John McCall2b7fc382010-07-13 20:32:21 +000084 if (IsNormalCleanup)
85 InnermostNormalCleanup = stable_begin();
86 if (IsEHCleanup)
87 InnermostEHCleanup = stable_begin();
88
89 return Scope->getCleanupBuffer();
90}
91
John McCallbd309292010-07-06 01:34:17 +000092void EHScopeStack::popCleanup() {
93 assert(!empty() && "popping exception stack when not empty");
94
John McCallcda666c2010-07-21 07:22:38 +000095 assert(isa<EHCleanupScope>(*begin()));
96 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
John McCall20141f22010-07-21 07:11:21 +000097 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
98 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
99 StartOfData += Cleanup.getAllocatedSize();
John McCallbd309292010-07-06 01:34:17 +0000100
John McCallad5d61e2010-07-23 21:56:41 +0000101 if (empty()) NextEHDestIndex = FirstEHDestIndex;
102
103 // Destroy the cleanup.
104 Cleanup.~EHCleanupScope();
105
John McCallbd309292010-07-06 01:34:17 +0000106 // Check whether we can shrink the branch-fixups stack.
107 if (!BranchFixups.empty()) {
108 // If we no longer have any normal cleanups, all the fixups are
109 // complete.
110 if (!hasNormalCleanups())
111 BranchFixups.clear();
112
113 // Otherwise we can still trim out unnecessary nulls.
114 else
115 popNullFixups();
116 }
117}
118
119EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
120 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
121 CatchDepth++;
122 return new (Buffer) EHFilterScope(NumFilters);
123}
124
125void EHScopeStack::popFilter() {
126 assert(!empty() && "popping exception stack when not empty");
127
128 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
129 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
130
John McCallad5d61e2010-07-23 21:56:41 +0000131 if (empty()) NextEHDestIndex = FirstEHDestIndex;
132
John McCallbd309292010-07-06 01:34:17 +0000133 assert(CatchDepth > 0 && "mismatched filter push/pop");
134 CatchDepth--;
135}
136
137EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
138 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
139 CatchDepth++;
John McCallad5d61e2010-07-23 21:56:41 +0000140 EHCatchScope *Scope = new (Buffer) EHCatchScope(NumHandlers);
141 for (unsigned I = 0; I != NumHandlers; ++I)
142 Scope->getHandlers()[I].Index = getNextEHDestIndex();
143 return Scope;
John McCallbd309292010-07-06 01:34:17 +0000144}
145
146void EHScopeStack::pushTerminate() {
147 char *Buffer = allocate(EHTerminateScope::getSize());
148 CatchDepth++;
John McCallad5d61e2010-07-23 21:56:41 +0000149 new (Buffer) EHTerminateScope(getNextEHDestIndex());
John McCallbd309292010-07-06 01:34:17 +0000150}
151
152/// Remove any 'null' fixups on the stack. However, we can't pop more
153/// fixups than the fixup depth on the innermost normal cleanup, or
154/// else fixups that we try to add to that cleanup will end up in the
155/// wrong place. We *could* try to shrink fixup depths, but that's
156/// actually a lot of work for little benefit.
157void EHScopeStack::popNullFixups() {
158 // We expect this to only be called when there's still an innermost
159 // normal cleanup; otherwise there really shouldn't be any fixups.
160 assert(hasNormalCleanups());
161
162 EHScopeStack::iterator it = find(InnermostNormalCleanup);
John McCallcda666c2010-07-21 07:22:38 +0000163 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
John McCallbd309292010-07-06 01:34:17 +0000164 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
165
166 while (BranchFixups.size() > MinSize &&
167 BranchFixups.back().Destination == 0)
168 BranchFixups.pop_back();
169}
170
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000171static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
172 // void *__cxa_allocate_exception(size_t thrown_size);
173 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
174 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump75546b82009-12-10 00:06:18 +0000175
176 const llvm::FunctionType *FTy =
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000177 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
178 Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000179
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000180 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
181}
182
Mike Stump33270212009-12-02 07:41:41 +0000183static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
184 // void __cxa_free_exception(void *thrown_exception);
185 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
186 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000187
188 const llvm::FunctionType *FTy =
Mike Stump33270212009-12-02 07:41:41 +0000189 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
190 Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000191
Mike Stump33270212009-12-02 07:41:41 +0000192 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
193}
194
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000195static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump75546b82009-12-10 00:06:18 +0000196 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +0000197 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000198
199 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
200 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000201
202 const llvm::FunctionType *FTy =
Mike Stumpd1782cc2009-11-20 00:56:31 +0000203 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
204 Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000205
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000206 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
207}
208
Mike Stumpd1782cc2009-11-20 00:56:31 +0000209static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +0000210 // void __cxa_rethrow();
Mike Stumpd1782cc2009-11-20 00:56:31 +0000211
Mike Stump75546b82009-12-10 00:06:18 +0000212 const llvm::FunctionType *FTy =
Mike Stumpd1782cc2009-11-20 00:56:31 +0000213 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump75546b82009-12-10 00:06:18 +0000214
Mike Stumpd1782cc2009-11-20 00:56:31 +0000215 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
216}
217
John McCallbd309292010-07-06 01:34:17 +0000218static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
219 // void *__cxa_get_exception_ptr(void*);
220 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
221 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
222
223 const llvm::FunctionType *FTy =
224 llvm::FunctionType::get(Int8PtrTy, Args, false);
225
226 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
227}
228
Mike Stump58ef18b2009-11-20 23:44:51 +0000229static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +0000230 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +0000231
232 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
233 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000234
235 const llvm::FunctionType *FTy =
Mike Stump54066142009-12-01 03:41:18 +0000236 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000237
Mike Stump58ef18b2009-11-20 23:44:51 +0000238 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
239}
240
241static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump33270212009-12-02 07:41:41 +0000242 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +0000243
Mike Stump75546b82009-12-10 00:06:18 +0000244 const llvm::FunctionType *FTy =
Mike Stump58ef18b2009-11-20 23:44:51 +0000245 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump75546b82009-12-10 00:06:18 +0000246
Mike Stump58ef18b2009-11-20 23:44:51 +0000247 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
248}
249
Mike Stump1d849212009-12-07 23:38:24 +0000250static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
251 // void __cxa_call_unexepcted(void *thrown_exception);
252
253 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
254 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000255
256 const llvm::FunctionType *FTy =
Mike Stump1d849212009-12-07 23:38:24 +0000257 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
258 Args, false);
Mike Stump75546b82009-12-10 00:06:18 +0000259
Mike Stump1d849212009-12-07 23:38:24 +0000260 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
261}
262
Douglas Gregor51150ab2010-05-16 01:24:12 +0000263llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
264 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump54066142009-12-01 03:41:18 +0000265 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000266
267 const llvm::FunctionType *FTy =
Douglas Gregor51150ab2010-05-16 01:24:12 +0000268 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump54066142009-12-01 03:41:18 +0000269 false);
Mike Stump75546b82009-12-10 00:06:18 +0000270
Douglas Gregor51150ab2010-05-16 01:24:12 +0000271 if (CGM.getLangOptions().SjLjExceptions)
272 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
273 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump54066142009-12-01 03:41:18 +0000274}
275
Mike Stump33270212009-12-02 07:41:41 +0000276static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
277 // void __terminate();
278
Mike Stump75546b82009-12-10 00:06:18 +0000279 const llvm::FunctionType *FTy =
Mike Stump33270212009-12-02 07:41:41 +0000280 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump75546b82009-12-10 00:06:18 +0000281
David Chisnallf9c42252010-05-17 13:49:20 +0000282 return CGF.CGM.CreateRuntimeFunction(FTy,
283 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
284}
285
John McCall36ea3722010-07-17 00:43:08 +0000286static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
287 const char *Name) {
288 const llvm::Type *Int8PtrTy =
289 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
290 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
291
292 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
293 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
294
295 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000296}
297
John McCall36ea3722010-07-17 00:43:08 +0000298const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
299const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
300const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
301const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
302const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
303 "objc_exception_throw");
304
305static const EHPersonality &getCPersonality(const LangOptions &L) {
306 return EHPersonality::GNU_C;
307}
308
309static const EHPersonality &getObjCPersonality(const LangOptions &L) {
310 if (L.NeXTRuntime) {
311 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
312 else return getCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000313 } else {
John McCall36ea3722010-07-17 00:43:08 +0000314 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000315 }
316}
317
John McCall36ea3722010-07-17 00:43:08 +0000318static const EHPersonality &getCXXPersonality(const LangOptions &L) {
319 if (L.SjLjExceptions)
320 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallbd309292010-07-06 01:34:17 +0000321 else
John McCall36ea3722010-07-17 00:43:08 +0000322 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000323}
324
325/// Determines the personality function to use when both C++
326/// and Objective-C exceptions are being caught.
John McCall36ea3722010-07-17 00:43:08 +0000327static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallbd309292010-07-06 01:34:17 +0000328 // The ObjC personality defers to the C++ personality for non-ObjC
329 // handlers. Unlike the C++ case, we use the same personality
330 // function on targets using (backend-driven) SJLJ EH.
John McCall36ea3722010-07-17 00:43:08 +0000331 if (L.NeXTRuntime) {
332 if (L.ObjCNonFragileABI)
333 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000334
335 // In the fragile ABI, just use C++ exception handling and hope
336 // they're not doing crazy exception mixing.
337 else
John McCall36ea3722010-07-17 00:43:08 +0000338 return getCXXPersonality(L);
Chandler Carruth0450cc62010-05-17 20:58:49 +0000339 }
David Chisnallf9c42252010-05-17 13:49:20 +0000340
John McCall36ea3722010-07-17 00:43:08 +0000341 // The GNU runtime's personality function inherently doesn't support
342 // mixed EH. Use the C++ personality just to avoid returning null.
343 return getCXXPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000344}
345
John McCall36ea3722010-07-17 00:43:08 +0000346const EHPersonality &EHPersonality::get(const LangOptions &L) {
347 if (L.CPlusPlus && L.ObjC1)
348 return getObjCXXPersonality(L);
349 else if (L.CPlusPlus)
350 return getCXXPersonality(L);
351 else if (L.ObjC1)
352 return getObjCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000353 else
John McCall36ea3722010-07-17 00:43:08 +0000354 return getCPersonality(L);
355}
John McCallbd309292010-07-06 01:34:17 +0000356
John McCall36ea3722010-07-17 00:43:08 +0000357static llvm::Constant *getPersonalityFn(CodeGenFunction &CGF,
358 const EHPersonality &Personality) {
359 const char *Name = Personality.getPersonalityFnName();
360
361 llvm::Constant *Fn =
John McCallbd309292010-07-06 01:34:17 +0000362 CGF.CGM.CreateRuntimeFunction(llvm::FunctionType::get(
363 llvm::Type::getInt32Ty(
364 CGF.CGM.getLLVMContext()),
365 true),
366 Name);
John McCall36ea3722010-07-17 00:43:08 +0000367 return llvm::ConstantExpr::getBitCast(Fn, CGF.CGM.PtrToInt8Ty);
John McCallbd309292010-07-06 01:34:17 +0000368}
369
370/// Returns the value to inject into a selector to indicate the
371/// presence of a catch-all.
372static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
373 // Possibly we should use @llvm.eh.catch.all.value here.
374 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
375}
376
377/// Returns the value to inject into a selector to indicate the
378/// presence of a cleanup.
379static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
380 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump33270212009-12-02 07:41:41 +0000381}
382
John McCallbb026012010-07-13 21:17:51 +0000383namespace {
384 /// A cleanup to free the exception object if its initialization
385 /// throws.
John McCallcda666c2010-07-21 07:22:38 +0000386 struct FreeExceptionCleanup : EHScopeStack::Cleanup {
John McCallbb026012010-07-13 21:17:51 +0000387 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
388 llvm::Value *ExnLocVar)
389 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
390
391 llvm::Value *ShouldFreeVar;
392 llvm::Value *ExnLocVar;
393
394 void Emit(CodeGenFunction &CGF, bool IsForEH) {
395 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
396 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
397
398 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
399 "should-free-exnobj");
400 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
401 CGF.EmitBlock(FreeBB);
402 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
403 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
404 ->setDoesNotThrow();
405 CGF.EmitBlock(DoneBB);
406 }
407 };
408}
409
John McCall2e6567a2010-04-22 01:10:34 +0000410// Emits an exception expression into the given location. This
411// differs from EmitAnyExprToMem only in that, if a final copy-ctor
412// call is required, an exception within that copy ctor causes
413// std::terminate to be invoked.
414static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
415 llvm::Value *ExnLoc) {
416 // We want to release the allocated exception object if this
417 // expression throws. We do this by pushing an EH-only cleanup
418 // block which, furthermore, deactivates itself after the expression
419 // is complete.
420 llvm::AllocaInst *ShouldFreeVar =
421 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
422 "should-free-exnobj.var");
423 CGF.InitTempAlloca(ShouldFreeVar,
424 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump54066142009-12-01 03:41:18 +0000425
John McCall2e6567a2010-04-22 01:10:34 +0000426 // A variable holding the exception pointer. This is necessary
427 // because the throw expression does not necessarily dominate the
428 // cleanup, for example if it appears in a conditional expression.
429 llvm::AllocaInst *ExnLocVar =
430 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump75546b82009-12-10 00:06:18 +0000431
John McCallbd309292010-07-06 01:34:17 +0000432 // Make sure the exception object is cleaned up if there's an
433 // exception during initialization.
John McCallbb026012010-07-13 21:17:51 +0000434 // FIXME: stmt expressions might require this to be a normal
435 // cleanup, too.
John McCallcda666c2010-07-21 07:22:38 +0000436 CGF.EHStack.pushCleanup<FreeExceptionCleanup>(EHCleanup,
437 ShouldFreeVar,
438 ExnLocVar);
John McCallbd309292010-07-06 01:34:17 +0000439 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000440
441 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
442 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
443 ShouldFreeVar);
444
445 // __cxa_allocate_exception returns a void*; we need to cast this
446 // to the appropriate type for the object.
447 const llvm::Type *Ty = CGF.ConvertType(E->getType())->getPointerTo();
448 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
449
450 // FIXME: this isn't quite right! If there's a final unelided call
451 // to a copy constructor, then according to [except.terminate]p1 we
452 // must call std::terminate() if that constructor throws, because
453 // technically that copy occurs after the exception expression is
454 // evaluated but before the exception is caught. But the best way
455 // to handle that is to teach EmitAggExpr to do the final copy
456 // differently if it can't be elided.
457 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false);
458
459 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
460 ShouldFreeVar);
461
John McCallbd309292010-07-06 01:34:17 +0000462 // Technically, the exception object is like a temporary; it has to
463 // be cleaned up when its full-expression is complete.
464 // Unfortunately, the AST represents full-expressions by creating a
465 // CXXExprWithTemporaries, which it only does when there are actually
466 // temporaries.
467 //
468 // If any cleanups have been added since we pushed ours, they must
469 // be from temporaries; this will get popped at the same time.
470 // Otherwise we need to pop ours off. FIXME: this is very brittle.
471 if (Cleanup == CGF.EHStack.stable_begin())
472 CGF.PopCleanupBlock();
Mike Stump54066142009-12-01 03:41:18 +0000473}
474
John McCallbd309292010-07-06 01:34:17 +0000475llvm::Value *CodeGenFunction::getExceptionSlot() {
476 if (!ExceptionSlot) {
477 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
478 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump54066142009-12-01 03:41:18 +0000479 }
John McCallbd309292010-07-06 01:34:17 +0000480 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000481}
482
Anders Carlsson4b08db72009-10-30 01:42:31 +0000483void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000484 if (!E->getSubExpr()) {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000485 if (getInvokeDest()) {
John McCallbd309292010-07-06 01:34:17 +0000486 Builder.CreateInvoke(getReThrowFn(*this),
487 getUnreachableBlock(),
488 getInvokeDest())
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000489 ->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000490 } else {
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000491 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000492 Builder.CreateUnreachable();
493 }
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000494
495 // Clear the insertion point to indicate we are in unreachable code.
496 Builder.ClearInsertionPoint();
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000497 return;
498 }
Mike Stump75546b82009-12-10 00:06:18 +0000499
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000500 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000501
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000502 // Now allocate the exception object.
503 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000504 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000505
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000506 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallbd309292010-07-06 01:34:17 +0000507 llvm::CallInst *ExceptionPtr =
Mike Stump75546b82009-12-10 00:06:18 +0000508 Builder.CreateCall(AllocExceptionFn,
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000509 llvm::ConstantInt::get(SizeTy, TypeSize),
510 "exception");
John McCallbd309292010-07-06 01:34:17 +0000511 ExceptionPtr->setDoesNotThrow();
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000512
John McCall2e6567a2010-04-22 01:10:34 +0000513 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000514
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000515 // Now throw the exception.
516 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall48bf3492010-04-30 01:15:21 +0000517 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
John McCall2e6567a2010-04-22 01:10:34 +0000518
519 // The address of the destructor. If the exception type has a
520 // trivial destructor (or isn't a record), we just pass null.
521 llvm::Constant *Dtor = 0;
522 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
523 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
524 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000525 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCall2e6567a2010-04-22 01:10:34 +0000526 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
527 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
528 }
529 }
530 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000531
Mike Stump114ab9f2009-12-04 01:51:45 +0000532 if (getInvokeDest()) {
Mike Stump75546b82009-12-10 00:06:18 +0000533 llvm::InvokeInst *ThrowCall =
John McCallbd309292010-07-06 01:34:17 +0000534 Builder.CreateInvoke3(getThrowFn(*this),
535 getUnreachableBlock(), getInvokeDest(),
Mike Stump114ab9f2009-12-04 01:51:45 +0000536 ExceptionPtr, TypeInfo, Dtor);
537 ThrowCall->setDoesNotReturn();
Mike Stump114ab9f2009-12-04 01:51:45 +0000538 } else {
Mike Stump75546b82009-12-10 00:06:18 +0000539 llvm::CallInst *ThrowCall =
Mike Stump114ab9f2009-12-04 01:51:45 +0000540 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
541 ThrowCall->setDoesNotReturn();
John McCallbd309292010-07-06 01:34:17 +0000542 Builder.CreateUnreachable();
Mike Stump114ab9f2009-12-04 01:51:45 +0000543 }
Mike Stump75546b82009-12-10 00:06:18 +0000544
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000545 // Clear the insertion point to indicate we are in unreachable code.
546 Builder.ClearInsertionPoint();
Mike Stump62afe992009-12-07 20:12:14 +0000547
548 // FIXME: For now, emit a dummy basic block because expr emitters in generally
549 // are not ready to handle emitting expressions at unreachable points.
550 EnsureInsertPoint();
Anders Carlsson4b08db72009-10-30 01:42:31 +0000551}
Mike Stump58ef18b2009-11-20 23:44:51 +0000552
Mike Stump1d849212009-12-07 23:38:24 +0000553void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000554 if (!Exceptions)
555 return;
556
Mike Stump1d849212009-12-07 23:38:24 +0000557 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
558 if (FD == 0)
559 return;
560 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
561 if (Proto == 0)
562 return;
563
564 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
565
566 if (!Proto->hasExceptionSpec())
567 return;
568
John McCallbd309292010-07-06 01:34:17 +0000569 unsigned NumExceptions = Proto->getNumExceptions();
570 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000571
John McCallbd309292010-07-06 01:34:17 +0000572 for (unsigned I = 0; I != NumExceptions; ++I) {
573 QualType Ty = Proto->getExceptionType(I);
574 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
John McCall48bf3492010-04-30 01:15:21 +0000575 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
John McCallbd309292010-07-06 01:34:17 +0000576 Filter->setFilter(I, EHType);
Mike Stump1d849212009-12-07 23:38:24 +0000577 }
Mike Stump1d849212009-12-07 23:38:24 +0000578}
579
580void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000581 if (!Exceptions)
582 return;
583
Mike Stump1d849212009-12-07 23:38:24 +0000584 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
585 if (FD == 0)
586 return;
587 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
588 if (Proto == 0)
589 return;
590
591 if (!Proto->hasExceptionSpec())
592 return;
593
John McCallbd309292010-07-06 01:34:17 +0000594 EHStack.popFilter();
Mike Stump1d849212009-12-07 23:38:24 +0000595}
596
Mike Stump58ef18b2009-11-20 23:44:51 +0000597void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000598 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000599 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000600 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000601}
602
John McCallb609d3f2010-07-07 06:56:46 +0000603void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000604 unsigned NumHandlers = S.getNumHandlers();
605 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000606
John McCallbd309292010-07-06 01:34:17 +0000607 for (unsigned I = 0; I != NumHandlers; ++I) {
608 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000609
John McCallbd309292010-07-06 01:34:17 +0000610 llvm::BasicBlock *Handler = createBasicBlock("catch");
611 if (C->getExceptionDecl()) {
612 // FIXME: Dropping the reference type on the type into makes it
613 // impossible to correctly implement catch-by-reference
614 // semantics for pointers. Unfortunately, this is what all
615 // existing compilers do, and it's not clear that the standard
616 // personality routine is capable of doing this right. See C++ DR 388:
617 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
618 QualType CaughtType = C->getCaughtType();
619 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
620 llvm::Value *TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, true);
621 CatchScope->setHandler(I, TypeInfo, Handler);
622 } else {
623 // No exception decl indicates '...', a catch-all.
624 CatchScope->setCatchAllHandler(I, Handler);
625 }
626 }
John McCallbd309292010-07-06 01:34:17 +0000627}
628
629/// Check whether this is a non-EH scope, i.e. a scope which doesn't
630/// affect exception handling. Currently, the only non-EH scopes are
631/// normal-only cleanup scopes.
632static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000633 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000634 case EHScope::Cleanup:
635 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000636 case EHScope::Filter:
637 case EHScope::Catch:
638 case EHScope::Terminate:
639 return false;
640 }
641
642 // Suppress warning.
643 return false;
John McCallbd309292010-07-06 01:34:17 +0000644}
645
646llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
647 assert(EHStack.requiresLandingPad());
648 assert(!EHStack.empty());
649
John McCall2b7fc382010-07-13 20:32:21 +0000650 if (!Exceptions)
651 return 0;
652
John McCallbd309292010-07-06 01:34:17 +0000653 // Check the innermost scope for a cached landing pad. If this is
654 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
655 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
656 if (LP) return LP;
657
658 // Build the landing pad for this scope.
659 LP = EmitLandingPad();
660 assert(LP);
661
662 // Cache the landing pad on the innermost scope. If this is a
663 // non-EH scope, cache the landing pad on the enclosing scope, too.
664 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
665 ir->setCachedLandingPad(LP);
666 if (!isNonEHScope(*ir)) break;
667 }
668
669 return LP;
670}
671
672llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
673 assert(EHStack.requiresLandingPad());
674
675 // This function contains a hack to work around a design flaw in
676 // LLVM's EH IR which breaks semantics after inlining. This same
677 // hack is implemented in llvm-gcc.
678 //
679 // The LLVM EH abstraction is basically a thin veneer over the
680 // traditional GCC zero-cost design: for each range of instructions
681 // in the function, there is (at most) one "landing pad" with an
682 // associated chain of EH actions. A language-specific personality
683 // function interprets this chain of actions and (1) decides whether
684 // or not to resume execution at the landing pad and (2) if so,
685 // provides an integer indicating why it's stopping. In LLVM IR,
686 // the association of a landing pad with a range of instructions is
687 // achieved via an invoke instruction, the chain of actions becomes
688 // the arguments to the @llvm.eh.selector call, and the selector
689 // call returns the integer indicator. Other than the required
690 // presence of two intrinsic function calls in the landing pad,
691 // the IR exactly describes the layout of the output code.
692 //
693 // A principal advantage of this design is that it is completely
694 // language-agnostic; in theory, the LLVM optimizers can treat
695 // landing pads neutrally, and targets need only know how to lower
696 // the intrinsics to have a functioning exceptions system (assuming
697 // that platform exceptions follow something approximately like the
698 // GCC design). Unfortunately, landing pads cannot be combined in a
699 // language-agnostic way: given selectors A and B, there is no way
700 // to make a single landing pad which faithfully represents the
701 // semantics of propagating an exception first through A, then
702 // through B, without knowing how the personality will interpret the
703 // (lowered form of the) selectors. This means that inlining has no
704 // choice but to crudely chain invokes (i.e., to ignore invokes in
705 // the inlined function, but to turn all unwindable calls into
706 // invokes), which is only semantically valid if every unwind stops
707 // at every landing pad.
708 //
709 // Therefore, the invoke-inline hack is to guarantee that every
710 // landing pad has a catch-all.
711 const bool UseInvokeInlineHack = true;
712
713 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
714 assert(ir != EHStack.end() &&
715 "stack requiring landing pad is nothing but non-EH scopes?");
716
717 // If this is a terminate scope, just use the singleton terminate
718 // landing pad.
719 if (isa<EHTerminateScope>(*ir))
720 return getTerminateLandingPad();
721
722 // If this isn't an EH scope, iterate; otherwise break out.
723 if (!isNonEHScope(*ir)) break;
724 ++ir;
725
726 // We haven't checked this scope for a cached landing pad yet.
727 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
728 return LP;
729 }
730
731 // Save the current IR generation state.
732 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
733
John McCall36ea3722010-07-17 00:43:08 +0000734 const EHPersonality &Personality =
735 EHPersonality::get(CGF.CGM.getLangOptions());
736
John McCallbd309292010-07-06 01:34:17 +0000737 // Create and configure the landing pad.
738 llvm::BasicBlock *LP = createBasicBlock("lpad");
739 EmitBlock(LP);
740
741 // Save the exception pointer. It's safe to use a single exception
742 // pointer per function because EH cleanups can never have nested
743 // try/catches.
744 llvm::CallInst *Exn =
745 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
746 Exn->setDoesNotThrow();
747 Builder.CreateStore(Exn, getExceptionSlot());
748
749 // Build the selector arguments.
750 llvm::SmallVector<llvm::Value*, 8> EHSelector;
751 EHSelector.push_back(Exn);
John McCall36ea3722010-07-17 00:43:08 +0000752 EHSelector.push_back(getPersonalityFn(*this, Personality));
John McCallbd309292010-07-06 01:34:17 +0000753
754 // Accumulate all the handlers in scope.
John McCallad5d61e2010-07-23 21:56:41 +0000755 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
756 UnwindDest CatchAll;
John McCallbd309292010-07-06 01:34:17 +0000757 bool HasEHCleanup = false;
758 bool HasEHFilter = false;
759 llvm::SmallVector<llvm::Value*, 8> EHFilters;
760 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
761 I != E; ++I) {
762
763 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000764 case EHScope::Cleanup:
John McCall2b7fc382010-07-13 20:32:21 +0000765 if (!HasEHCleanup)
John McCallcda666c2010-07-21 07:22:38 +0000766 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000767 // We otherwise don't care about cleanups.
768 continue;
769
John McCallbd309292010-07-06 01:34:17 +0000770 case EHScope::Filter: {
771 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallad5d61e2010-07-23 21:56:41 +0000772 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000773
774 // Filter scopes get added to the selector in wierd ways.
775 EHFilterScope &Filter = cast<EHFilterScope>(*I);
776 HasEHFilter = true;
777
778 // Add all the filter values which we aren't already explicitly
779 // catching.
780 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
781 llvm::Value *FV = Filter.getFilter(I);
782 if (!EHHandlers.count(FV))
783 EHFilters.push_back(FV);
784 }
785 goto done;
786 }
787
788 case EHScope::Terminate:
789 // Terminate scopes are basically catch-alls.
John McCallad5d61e2010-07-23 21:56:41 +0000790 assert(!CatchAll.isValid());
791 CatchAll = UnwindDest(getTerminateHandler(),
792 EHStack.getEnclosingEHCleanup(I),
793 cast<EHTerminateScope>(*I).getDestIndex());
John McCallbd309292010-07-06 01:34:17 +0000794 goto done;
795
796 case EHScope::Catch:
797 break;
798 }
799
800 EHCatchScope &Catch = cast<EHCatchScope>(*I);
801 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
802 EHCatchScope::Handler Handler = Catch.getHandler(HI);
803
804 // Catch-all. We should only have one of these per catch.
805 if (!Handler.Type) {
John McCallad5d61e2010-07-23 21:56:41 +0000806 assert(!CatchAll.isValid());
807 CatchAll = UnwindDest(Handler.Block,
808 EHStack.getEnclosingEHCleanup(I),
809 Handler.Index);
John McCallbd309292010-07-06 01:34:17 +0000810 continue;
811 }
812
813 // Check whether we already have a handler for this type.
John McCallad5d61e2010-07-23 21:56:41 +0000814 UnwindDest &Dest = EHHandlers[Handler.Type];
815 if (Dest.isValid()) continue;
John McCallbd309292010-07-06 01:34:17 +0000816
817 EHSelector.push_back(Handler.Type);
John McCallad5d61e2010-07-23 21:56:41 +0000818 Dest = UnwindDest(Handler.Block,
819 EHStack.getEnclosingEHCleanup(I),
820 Handler.Index);
John McCallbd309292010-07-06 01:34:17 +0000821 }
822
823 // Stop if we found a catch-all.
John McCallad5d61e2010-07-23 21:56:41 +0000824 if (CatchAll.isValid()) break;
John McCallbd309292010-07-06 01:34:17 +0000825 }
826
827 done:
828 unsigned LastToEmitInLoop = EHSelector.size();
829
830 // If we have a catch-all, add null to the selector.
John McCallad5d61e2010-07-23 21:56:41 +0000831 if (CatchAll.isValid()) {
John McCallbd309292010-07-06 01:34:17 +0000832 EHSelector.push_back(getCatchAllValue(CGF));
833
834 // If we have an EH filter, we need to add those handlers in the
835 // right place in the selector, which is to say, at the end.
836 } else if (HasEHFilter) {
837 // Create a filter expression: an integer constant saying how many
838 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
839 // followed by the filter types. The personality routine only
840 // lands here if the filter doesn't match.
841 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
842 EHFilters.size() + 1));
843 EHSelector.append(EHFilters.begin(), EHFilters.end());
844
845 // Also check whether we need a cleanup.
846 if (UseInvokeInlineHack || HasEHCleanup)
847 EHSelector.push_back(UseInvokeInlineHack
848 ? getCatchAllValue(CGF)
849 : getCleanupValue(CGF));
850
851 // Otherwise, signal that we at least have cleanups.
852 } else if (UseInvokeInlineHack || HasEHCleanup) {
853 EHSelector.push_back(UseInvokeInlineHack
854 ? getCatchAllValue(CGF)
855 : getCleanupValue(CGF));
856 } else {
857 assert(LastToEmitInLoop > 2);
858 LastToEmitInLoop--;
859 }
860
861 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
862
863 // Tell the backend how to generate the landing pad.
864 llvm::CallInst *Selection =
865 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
866 EHSelector.begin(), EHSelector.end(), "eh.selector");
867 Selection->setDoesNotThrow();
868
869 // Select the right handler.
870 llvm::Value *llvm_eh_typeid_for =
871 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
872
873 // The results of llvm_eh_typeid_for aren't reliable --- at least
874 // not locally --- so we basically have to do this as an 'if' chain.
875 // We walk through the first N-1 catch clauses, testing and chaining,
876 // and then fall into the final clause (which is either a cleanup, a
877 // filter (possibly with a cleanup), a catch-all, or another catch).
878 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
879 llvm::Value *Type = EHSelector[I];
John McCallad5d61e2010-07-23 21:56:41 +0000880 UnwindDest Dest = EHHandlers[Type];
881 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallbd309292010-07-06 01:34:17 +0000882
883 // Figure out where to branch on a match. As a debug code-size
884 // optimization, if the scope depth matches the innermost cleanup,
885 // we branch directly to the catch handler.
John McCallad5d61e2010-07-23 21:56:41 +0000886 llvm::BasicBlock *Match = Dest.getBlock();
887 bool MatchNeedsCleanup =
888 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallbd309292010-07-06 01:34:17 +0000889 if (MatchNeedsCleanup)
890 Match = createBasicBlock("eh.match");
891
892 llvm::BasicBlock *Next = createBasicBlock("eh.next");
893
894 // Check whether the exception matches.
895 llvm::CallInst *Id
896 = Builder.CreateCall(llvm_eh_typeid_for,
897 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
898 Id->setDoesNotThrow();
899 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
900 Match, Next);
901
902 // Emit match code if necessary.
903 if (MatchNeedsCleanup) {
904 EmitBlock(Match);
905 EmitBranchThroughEHCleanup(Dest);
906 }
907
908 // Continue to the next match.
909 EmitBlock(Next);
910 }
911
912 // Emit the final case in the selector.
913 // This might be a catch-all....
John McCallad5d61e2010-07-23 21:56:41 +0000914 if (CatchAll.isValid()) {
John McCallbd309292010-07-06 01:34:17 +0000915 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
916 EmitBranchThroughEHCleanup(CatchAll);
917
918 // ...or an EH filter...
919 } else if (HasEHFilter) {
920 llvm::Value *SavedSelection = Selection;
921
922 // First, unwind out to the outermost scope if necessary.
923 if (EHStack.hasEHCleanups()) {
924 // The end here might not dominate the beginning, so we might need to
925 // save the selector if we need it.
926 llvm::AllocaInst *SelectorVar = 0;
927 if (HasEHCleanup) {
928 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
929 Builder.CreateStore(Selection, SelectorVar);
930 }
931
932 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallad5d61e2010-07-23 21:56:41 +0000933 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
934 EHStack.getNextEHDestIndex()));
John McCallbd309292010-07-06 01:34:17 +0000935 EmitBlock(CleanupContBB);
936
937 if (HasEHCleanup)
938 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
939 }
940
941 // If there was a cleanup, we'll need to actually check whether we
942 // landed here because the filter triggered.
943 if (UseInvokeInlineHack || HasEHCleanup) {
944 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
945 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
946
947 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
948 llvm::Value *FailsFilter =
949 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
950 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
951
952 // The rethrow block is where we land if this was a cleanup.
953 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
954 EmitBlock(RethrowBB);
955 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
956 Builder.CreateLoad(getExceptionSlot()))
957 ->setDoesNotReturn();
958 Builder.CreateUnreachable();
959
960 EmitBlock(UnexpectedBB);
961 }
962
963 // Call __cxa_call_unexpected. This doesn't need to be an invoke
964 // because __cxa_call_unexpected magically filters exceptions
965 // according to the last landing pad the exception was thrown
966 // into. Seriously.
967 Builder.CreateCall(getUnexpectedFn(*this),
968 Builder.CreateLoad(getExceptionSlot()))
969 ->setDoesNotReturn();
970 Builder.CreateUnreachable();
971
972 // ...or a normal catch handler...
973 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
974 llvm::Value *Type = EHSelector.back();
975 EmitBranchThroughEHCleanup(EHHandlers[Type]);
976
977 // ...or a cleanup.
978 } else {
John McCallad5d61e2010-07-23 21:56:41 +0000979 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallbd309292010-07-06 01:34:17 +0000980 }
981
982 // Restore the old IR generation state.
983 Builder.restoreIP(SavedIP);
984
985 return LP;
986}
987
John McCall5c08ab92010-07-13 22:12:14 +0000988namespace {
989 /// A cleanup to call __cxa_end_catch. In many cases, the caught
990 /// exception type lets us state definitively that the thrown exception
991 /// type does not have a destructor. In particular:
992 /// - Catch-alls tell us nothing, so we have to conservatively
993 /// assume that the thrown exception might have a destructor.
994 /// - Catches by reference behave according to their base types.
995 /// - Catches of non-record types will only trigger for exceptions
996 /// of non-record types, which never have destructors.
997 /// - Catches of record types can trigger for arbitrary subclasses
998 /// of the caught type, so we have to assume the actual thrown
999 /// exception type might have a throwing destructor, even if the
1000 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +00001001 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +00001002 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1003 bool MightThrow;
1004
1005 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1006 if (!MightThrow) {
1007 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1008 return;
1009 }
1010
1011 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1012 }
1013 };
1014}
1015
John McCallbd309292010-07-06 01:34:17 +00001016/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1017/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001018///
1019/// \param EndMightThrow - true if __cxa_end_catch might throw
1020static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1021 llvm::Value *Exn,
1022 bool EndMightThrow) {
John McCallbd309292010-07-06 01:34:17 +00001023 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1024 Call->setDoesNotThrow();
1025
John McCallcda666c2010-07-21 07:22:38 +00001026 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +00001027
1028 return Call;
1029}
1030
1031/// A "special initializer" callback for initializing a catch
1032/// parameter during catch initialization.
1033static void InitCatchParam(CodeGenFunction &CGF,
1034 const VarDecl &CatchParam,
1035 llvm::Value *ParamAddr) {
1036 // Load the exception from where the landing pad saved it.
1037 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1038
1039 CanQualType CatchType =
1040 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1041 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1042
1043 // If we're catching by reference, we can just cast the object
1044 // pointer to the appropriate pointer.
1045 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +00001046 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1047 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +00001048
John McCallbd309292010-07-06 01:34:17 +00001049 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +00001050 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +00001051
1052 // We have no way to tell the personality function that we're
1053 // catching by reference, so if we're catching a pointer,
1054 // __cxa_begin_catch will actually return that pointer by value.
1055 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1056 QualType PointeeType = PT->getPointeeType();
1057
1058 // When catching by reference, generally we should just ignore
1059 // this by-value pointer and use the exception object instead.
1060 if (!PointeeType->isRecordType()) {
1061
1062 // Exn points to the struct _Unwind_Exception header, which
1063 // we have to skip past in order to reach the exception data.
1064 unsigned HeaderSize =
1065 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1066 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1067
1068 // However, if we're catching a pointer-to-record type that won't
1069 // work, because the personality function might have adjusted
1070 // the pointer. There's actually no way for us to fully satisfy
1071 // the language/ABI contract here: we can't use Exn because it
1072 // might have the wrong adjustment, but we can't use the by-value
1073 // pointer because it's off by a level of abstraction.
1074 //
1075 // The current solution is to dump the adjusted pointer into an
1076 // alloca, which breaks language semantics (because changing the
1077 // pointer doesn't change the exception) but at least works.
1078 // The better solution would be to filter out non-exact matches
1079 // and rethrow them, but this is tricky because the rethrow
1080 // really needs to be catchable by other sites at this landing
1081 // pad. The best solution is to fix the personality function.
1082 } else {
1083 // Pull the pointer for the reference type off.
1084 const llvm::Type *PtrTy =
1085 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1086
1087 // Create the temporary and write the adjusted pointer into it.
1088 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1089 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1090 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1091
1092 // Bind the reference to the temporary.
1093 AdjustedExn = ExnPtrTmp;
1094 }
1095 }
1096
John McCallbd309292010-07-06 01:34:17 +00001097 llvm::Value *ExnCast =
1098 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1099 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1100 return;
1101 }
1102
1103 // Non-aggregates (plus complexes).
1104 bool IsComplex = false;
1105 if (!CGF.hasAggregateLLVMType(CatchType) ||
1106 (IsComplex = CatchType->isAnyComplexType())) {
John McCall5c08ab92010-07-13 22:12:14 +00001107 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +00001108
1109 // If the catch type is a pointer type, __cxa_begin_catch returns
1110 // the pointer by value.
1111 if (CatchType->hasPointerRepresentation()) {
1112 llvm::Value *CastExn =
1113 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1114 CGF.Builder.CreateStore(CastExn, ParamAddr);
1115 return;
1116 }
1117
1118 // Otherwise, it returns a pointer into the exception object.
1119
1120 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1121 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1122
1123 if (IsComplex) {
1124 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1125 ParamAddr, /*volatile*/ false);
1126 } else {
1127 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1128 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, CatchType);
1129 }
1130 return;
1131 }
1132
1133 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1134 // initializer expression.
1135
1136 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1137 assert(RD && "aggregate catch type was not a record!");
1138
1139 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1140
1141 if (RD->hasTrivialCopyConstructor()) {
John McCall5c08ab92010-07-13 22:12:14 +00001142 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001143 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1144 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1145 return;
1146 }
1147
1148 // We have to call __cxa_get_exception_ptr to get the adjusted
1149 // pointer before copying.
1150 llvm::CallInst *AdjustedExn =
1151 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1152 AdjustedExn->setDoesNotThrow();
1153 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1154
1155 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1156 assert(CD && "record has no copy constructor!");
1157 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1158
1159 CallArgList CallArgs;
1160 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1161 CD->getThisType(CGF.getContext())));
1162 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1163 CD->getParamDecl(0)->getType()));
1164
1165 const FunctionProtoType *FPT
1166 = CD->getType()->getAs<FunctionProtoType>();
1167
1168 // Call the copy ctor in a terminate scope.
1169 CGF.EHStack.pushTerminate();
1170 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1171 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1172 CGF.EHStack.popTerminate();
1173
1174 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001175 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001176}
1177
1178/// Begins a catch statement by initializing the catch variable and
1179/// calling __cxa_begin_catch.
1180static void BeginCatch(CodeGenFunction &CGF,
1181 const CXXCatchStmt *S) {
1182 // We have to be very careful with the ordering of cleanups here:
1183 // C++ [except.throw]p4:
1184 // The destruction [of the exception temporary] occurs
1185 // immediately after the destruction of the object declared in
1186 // the exception-declaration in the handler.
1187 //
1188 // So the precise ordering is:
1189 // 1. Construct catch variable.
1190 // 2. __cxa_begin_catch
1191 // 3. Enter __cxa_end_catch cleanup
1192 // 4. Enter dtor cleanup
1193 //
1194 // We do this by initializing the exception variable with a
1195 // "special initializer", InitCatchParam. Delegation sequence:
1196 // - ExitCXXTryStmt opens a RunCleanupsScope
1197 // - EmitLocalBlockVarDecl creates the variable and debug info
1198 // - InitCatchParam initializes the variable from the exception
1199 // - CallBeginCatch calls __cxa_begin_catch
1200 // - CallBeginCatch enters the __cxa_end_catch cleanup
1201 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1202 // - EmitCXXTryStmt emits the code for the catch body
1203 // - EmitCXXTryStmt close the RunCleanupsScope
1204
1205 VarDecl *CatchParam = S->getExceptionDecl();
1206 if (!CatchParam) {
1207 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall5c08ab92010-07-13 22:12:14 +00001208 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001209 return;
1210 }
1211
1212 // Emit the local.
1213 CGF.EmitLocalBlockVarDecl(*CatchParam, &InitCatchParam);
John McCallb81884d2010-02-19 09:25:03 +00001214}
1215
John McCall5c0e69e2010-07-13 22:24:23 +00001216namespace {
John McCallcda666c2010-07-21 07:22:38 +00001217 struct CallRethrow : EHScopeStack::Cleanup {
John McCall5c0e69e2010-07-13 22:24:23 +00001218 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1219 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1220 }
1221 };
1222}
1223
John McCallb609d3f2010-07-07 06:56:46 +00001224void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001225 unsigned NumHandlers = S.getNumHandlers();
1226 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1227 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001228
John McCallbd309292010-07-06 01:34:17 +00001229 // Copy the handler blocks off before we pop the EH stack. Emitting
1230 // the handlers might scribble on this memory.
1231 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1232 memcpy(Handlers.data(), CatchScope.begin(),
1233 NumHandlers * sizeof(EHCatchScope::Handler));
1234 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001235
John McCallbd309292010-07-06 01:34:17 +00001236 // The fall-through block.
1237 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001238
John McCallbd309292010-07-06 01:34:17 +00001239 // We just emitted the body of the try; jump to the continue block.
1240 if (HaveInsertPoint())
1241 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001242
John McCallb609d3f2010-07-07 06:56:46 +00001243 // Determine if we need an implicit rethrow for all these catch handlers.
1244 bool ImplicitRethrow = false;
1245 if (IsFnTryBlock)
1246 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1247 isa<CXXConstructorDecl>(CurCodeDecl);
1248
John McCallbd309292010-07-06 01:34:17 +00001249 for (unsigned I = 0; I != NumHandlers; ++I) {
1250 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1251 EmitBlock(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001252
John McCallbd309292010-07-06 01:34:17 +00001253 // Catch the exception if this isn't a catch-all.
1254 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump58ef18b2009-11-20 23:44:51 +00001255
John McCallbd309292010-07-06 01:34:17 +00001256 // Enter a cleanup scope, including the catch variable and the
1257 // end-catch.
1258 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001259
John McCallbd309292010-07-06 01:34:17 +00001260 // Initialize the catch variable and set up the cleanups.
1261 BeginCatch(*this, C);
1262
John McCallb609d3f2010-07-07 06:56:46 +00001263 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCall5c0e69e2010-07-13 22:24:23 +00001264 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1265 // called, and so it is pushed after BeginCatch.
1266 if (ImplicitRethrow)
John McCallcda666c2010-07-21 07:22:38 +00001267 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCallb609d3f2010-07-07 06:56:46 +00001268
John McCallbd309292010-07-06 01:34:17 +00001269 // Perform the body of the catch.
1270 EmitStmt(C->getHandlerBlock());
1271
1272 // Fall out through the catch cleanups.
1273 CatchScope.ForceCleanup();
1274
1275 // Branch out of the try.
1276 if (HaveInsertPoint())
1277 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001278 }
1279
John McCallbd309292010-07-06 01:34:17 +00001280 EmitBlock(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001281}
Mike Stumpaff69af2009-12-09 03:35:49 +00001282
John McCall1e670402010-07-21 00:52:03 +00001283namespace {
John McCallcda666c2010-07-21 07:22:38 +00001284 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001285 llvm::Value *ForEHVar;
1286 llvm::Value *EndCatchFn;
1287 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1288 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1289
1290 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1291 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1292 llvm::BasicBlock *CleanupContBB =
1293 CGF.createBasicBlock("finally.cleanup.cont");
1294
1295 llvm::Value *ShouldEndCatch =
1296 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1297 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1298 CGF.EmitBlock(EndCatchBB);
1299 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1300 CGF.EmitBlock(CleanupContBB);
1301 }
1302 };
John McCall906da4b2010-07-21 05:47:49 +00001303
John McCallcda666c2010-07-21 07:22:38 +00001304 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001305 const Stmt *Body;
1306 llvm::Value *ForEHVar;
1307 llvm::Value *EndCatchFn;
1308 llvm::Value *RethrowFn;
1309 llvm::Value *SavedExnVar;
1310
1311 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1312 llvm::Value *EndCatchFn,
1313 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1314 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1315 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1316
1317 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1318 // Enter a cleanup to call the end-catch function if one was provided.
1319 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001320 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1321 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001322
1323 // Emit the finally block.
1324 CGF.EmitStmt(Body);
1325
1326 // If the end of the finally is reachable, check whether this was
1327 // for EH. If so, rethrow.
1328 if (CGF.HaveInsertPoint()) {
1329 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1330 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1331
1332 llvm::Value *ShouldRethrow =
1333 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1334 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1335
1336 CGF.EmitBlock(RethrowBB);
1337 if (SavedExnVar) {
1338 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1339 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1340 } else {
1341 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1342 }
1343 CGF.Builder.CreateUnreachable();
1344
1345 CGF.EmitBlock(ContBB);
1346 }
1347
1348 // Leave the end-catch cleanup. As an optimization, pretend that
1349 // the fallthrough path was inaccessible; we've dynamically proven
1350 // that we're not in the EH case along that path.
1351 if (EndCatchFn) {
1352 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1353 CGF.PopCleanupBlock();
1354 CGF.Builder.restoreIP(SavedIP);
1355 }
1356
1357 // Now make sure we actually have an insertion point or the
1358 // cleanup gods will hate us.
1359 CGF.EnsureInsertPoint();
1360 }
1361 };
John McCall1e670402010-07-21 00:52:03 +00001362}
1363
John McCallbd309292010-07-06 01:34:17 +00001364/// Enters a finally block for an implementation using zero-cost
1365/// exceptions. This is mostly general, but hard-codes some
1366/// language/ABI-specific behavior in the catch-all sections.
1367CodeGenFunction::FinallyInfo
1368CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1369 llvm::Constant *BeginCatchFn,
1370 llvm::Constant *EndCatchFn,
1371 llvm::Constant *RethrowFn) {
1372 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1373 "begin/end catch functions not paired");
1374 assert(RethrowFn && "rethrow function is required");
Mike Stumpaff69af2009-12-09 03:35:49 +00001375
John McCallbd309292010-07-06 01:34:17 +00001376 // The rethrow function has one of the following two types:
1377 // void (*)()
1378 // void (*)(void*)
1379 // In the latter case we need to pass it the exception object.
1380 // But we can't use the exception slot because the @finally might
1381 // have a landing pad (which would overwrite the exception slot).
1382 const llvm::FunctionType *RethrowFnTy =
1383 cast<llvm::FunctionType>(
1384 cast<llvm::PointerType>(RethrowFn->getType())
1385 ->getElementType());
1386 llvm::Value *SavedExnVar = 0;
1387 if (RethrowFnTy->getNumParams())
1388 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001389
John McCallbd309292010-07-06 01:34:17 +00001390 // A finally block is a statement which must be executed on any edge
1391 // out of a given scope. Unlike a cleanup, the finally block may
1392 // contain arbitrary control flow leading out of itself. In
1393 // addition, finally blocks should always be executed, even if there
1394 // are no catch handlers higher on the stack. Therefore, we
1395 // surround the protected scope with a combination of a normal
1396 // cleanup (to catch attempts to break out of the block via normal
1397 // control flow) and an EH catch-all (semantically "outside" any try
1398 // statement to which the finally block might have been attached).
1399 // The finally block itself is generated in the context of a cleanup
1400 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001401
John McCallbd309292010-07-06 01:34:17 +00001402 FinallyInfo Info;
John McCall21886962010-04-21 10:05:39 +00001403
John McCallbd309292010-07-06 01:34:17 +00001404 // Jump destination for performing the finally block on an exception
1405 // edge. We'll never actually reach this block, so unreachable is
1406 // fine.
1407 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001408
John McCallbd309292010-07-06 01:34:17 +00001409 // Whether the finally block is being executed for EH purposes.
1410 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1411 "finally.for-eh");
1412 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpaff69af2009-12-09 03:35:49 +00001413
John McCallbd309292010-07-06 01:34:17 +00001414 // Enter a normal cleanup which will perform the @finally block.
John McCallcda666c2010-07-21 07:22:38 +00001415 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1416 ForEHVar, EndCatchFn,
1417 RethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001418
1419 // Enter a catch-all scope.
1420 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1421 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1422 Builder.SetInsertPoint(CatchAllBB);
1423
1424 // If there's a begin-catch function, call it.
1425 if (BeginCatchFn) {
1426 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1427 ->setDoesNotThrow();
1428 }
1429
1430 // If we need to remember the exception pointer to rethrow later, do so.
1431 if (SavedExnVar) {
1432 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1433 Builder.CreateStore(SavedExn, SavedExnVar);
1434 }
1435
1436 // Tell the finally block that we're in EH.
1437 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1438
1439 // Thread a jump through the finally cleanup.
1440 EmitBranchThroughCleanup(RethrowDest);
1441
1442 Builder.restoreIP(SavedIP);
1443
1444 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1445 CatchScope->setCatchAllHandler(0, CatchAllBB);
1446
1447 return Info;
1448}
1449
1450void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1451 // Leave the finally catch-all.
1452 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1453 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1454 EHStack.popCatch();
1455
1456 // And leave the normal cleanup.
1457 PopCleanupBlock();
1458
1459 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1460 EmitBlock(CatchAllBB, true);
1461
1462 Builder.restoreIP(SavedIP);
1463}
1464
1465llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1466 if (TerminateLandingPad)
1467 return TerminateLandingPad;
1468
1469 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1470
1471 // This will get inserted at the end of the function.
1472 TerminateLandingPad = createBasicBlock("terminate.lpad");
1473 Builder.SetInsertPoint(TerminateLandingPad);
1474
1475 // Tell the backend that this is a landing pad.
1476 llvm::CallInst *Exn =
1477 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1478 Exn->setDoesNotThrow();
John McCall36ea3722010-07-17 00:43:08 +00001479
1480 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallbd309292010-07-06 01:34:17 +00001481
1482 // Tell the backend what the exception table should be:
1483 // nothing but a catch-all.
John McCall36ea3722010-07-17 00:43:08 +00001484 llvm::Value *Args[3] = { Exn, getPersonalityFn(*this, Personality),
John McCallbd309292010-07-06 01:34:17 +00001485 getCatchAllValue(*this) };
1486 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1487 Args, Args+3, "eh.selector")
1488 ->setDoesNotThrow();
1489
1490 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1491 TerminateCall->setDoesNotReturn();
1492 TerminateCall->setDoesNotThrow();
Mike Stumpaff69af2009-12-09 03:35:49 +00001493 CGF.Builder.CreateUnreachable();
1494
John McCallbd309292010-07-06 01:34:17 +00001495 // Restore the saved insertion state.
1496 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001497
John McCallbd309292010-07-06 01:34:17 +00001498 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001499}
Mike Stump2b488872009-12-09 22:59:31 +00001500
1501llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001502 if (TerminateHandler)
1503 return TerminateHandler;
1504
John McCallbd309292010-07-06 01:34:17 +00001505 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001506
John McCallbd309292010-07-06 01:34:17 +00001507 // Set up the terminate handler. This block is inserted at the very
1508 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001509 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001510 Builder.SetInsertPoint(TerminateHandler);
1511 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump2b488872009-12-09 22:59:31 +00001512 TerminateCall->setDoesNotReturn();
1513 TerminateCall->setDoesNotThrow();
1514 Builder.CreateUnreachable();
1515
John McCall21886962010-04-21 10:05:39 +00001516 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001517 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001518
Mike Stump2b488872009-12-09 22:59:31 +00001519 return TerminateHandler;
1520}
John McCallbd309292010-07-06 01:34:17 +00001521
John McCallad5d61e2010-07-23 21:56:41 +00001522CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1523 if (RethrowBlock.isValid()) return RethrowBlock;
1524
1525 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1526
1527 // We emit a jump to a notional label at the outermost unwind state.
1528 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1529 Builder.SetInsertPoint(Unwind);
1530
1531 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1532
1533 // This can always be a call because we necessarily didn't find
1534 // anything on the EH stack which needs our help.
1535 llvm::Constant *RethrowFn;
1536 if (const char *RethrowName = Personality.getCatchallRethrowFnName())
1537 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1538 else
1539 RethrowFn = getUnwindResumeOrRethrowFn();
1540
1541 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1542 ->setDoesNotReturn();
1543 Builder.CreateUnreachable();
1544
1545 Builder.restoreIP(SavedIP);
1546
1547 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1548 return RethrowBlock;
1549}
1550
John McCallcda666c2010-07-21 07:22:38 +00001551EHScopeStack::Cleanup::~Cleanup() {
1552 llvm_unreachable("Cleanup is indestructable");
John McCall11e577b2010-07-13 23:19:49 +00001553}