blob: 1063e28b8493a157e4d310f75d9d2936c9a94073 [file] [log] [blame]
Anders Carlsson756b5c42009-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 Stump2bf701e2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCallf1549f62010-07-06 01:34:17 +000017#include "llvm/Support/CallSite.h"
Mike Stump2bf701e2009-11-20 23:44:51 +000018
John McCall5a180392010-07-24 00:37:23 +000019#include "CGObjCRuntime.h"
Anders Carlsson756b5c42009-10-30 01:42:31 +000020#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000021#include "CGException.h"
John McCall204b0752010-07-20 22:17:55 +000022#include "TargetInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000023
Anders Carlsson756b5c42009-10-30 01:42:31 +000024using namespace clang;
25using namespace CodeGen;
26
John McCallf1549f62010-07-06 01:34:17 +000027/// Push an entry of the given size onto this protected-scope stack.
28char *EHScopeStack::allocate(size_t Size) {
29 if (!StartOfBuffer) {
30 unsigned Capacity = 1024;
31 while (Capacity < Size) Capacity *= 2;
32 StartOfBuffer = new char[Capacity];
33 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
34 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
35 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
36 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
37
38 unsigned NewCapacity = CurrentCapacity;
39 do {
40 NewCapacity *= 2;
41 } while (NewCapacity < UsedCapacity + Size);
42
43 char *NewStartOfBuffer = new char[NewCapacity];
44 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
45 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
46 memcpy(NewStartOfData, StartOfData, UsedCapacity);
47 delete [] StartOfBuffer;
48 StartOfBuffer = NewStartOfBuffer;
49 EndOfBuffer = NewEndOfBuffer;
50 StartOfData = NewStartOfData;
51 }
52
53 assert(StartOfBuffer + Size <= StartOfData);
54 StartOfData -= Size;
55 return StartOfData;
56}
57
58EHScopeStack::stable_iterator
59EHScopeStack::getEnclosingEHCleanup(iterator it) const {
60 assert(it != end());
61 do {
John McCall1f0fca52010-07-21 07:22:38 +000062 if (isa<EHCleanupScope>(*it)) {
63 if (cast<EHCleanupScope>(*it).isEHCleanup())
John McCallda65ea82010-07-13 20:32:21 +000064 return stabilize(it);
John McCall1f0fca52010-07-21 07:22:38 +000065 return cast<EHCleanupScope>(*it).getEnclosingEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +000066 }
John McCallf1549f62010-07-06 01:34:17 +000067 ++it;
68 } while (it != end());
69 return stable_end();
70}
71
72
John McCall1f0fca52010-07-21 07:22:38 +000073void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCallda65ea82010-07-13 20:32:21 +000074 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
John McCall1f0fca52010-07-21 07:22:38 +000075 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
John McCallcd2d2b72010-08-13 21:20:51 +000076 bool IsNormalCleanup = Kind & NormalCleanup;
77 bool IsEHCleanup = Kind & EHCleanup;
78 bool IsActive = !(Kind & InactiveCleanup);
John McCall1f0fca52010-07-21 07:22:38 +000079 EHCleanupScope *Scope =
80 new (Buffer) EHCleanupScope(IsNormalCleanup,
81 IsEHCleanup,
John McCallcd2d2b72010-08-13 21:20:51 +000082 IsActive,
John McCall1f0fca52010-07-21 07:22:38 +000083 Size,
84 BranchFixups.size(),
85 InnermostNormalCleanup,
86 InnermostEHCleanup);
John McCallda65ea82010-07-13 20:32:21 +000087 if (IsNormalCleanup)
88 InnermostNormalCleanup = stable_begin();
89 if (IsEHCleanup)
90 InnermostEHCleanup = stable_begin();
91
92 return Scope->getCleanupBuffer();
93}
94
John McCallf1549f62010-07-06 01:34:17 +000095void EHScopeStack::popCleanup() {
96 assert(!empty() && "popping exception stack when not empty");
97
John McCall1f0fca52010-07-21 07:22:38 +000098 assert(isa<EHCleanupScope>(*begin()));
99 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
John McCall7495f222010-07-21 07:11:21 +0000100 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
101 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
102 StartOfData += Cleanup.getAllocatedSize();
John McCallf1549f62010-07-06 01:34:17 +0000103
John McCallff8e1152010-07-23 21:56:41 +0000104 if (empty()) NextEHDestIndex = FirstEHDestIndex;
105
106 // Destroy the cleanup.
107 Cleanup.~EHCleanupScope();
108
John McCallf1549f62010-07-06 01:34:17 +0000109 // Check whether we can shrink the branch-fixups stack.
110 if (!BranchFixups.empty()) {
111 // If we no longer have any normal cleanups, all the fixups are
112 // complete.
113 if (!hasNormalCleanups())
114 BranchFixups.clear();
115
116 // Otherwise we can still trim out unnecessary nulls.
117 else
118 popNullFixups();
119 }
120}
121
122EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
123 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
124 CatchDepth++;
125 return new (Buffer) EHFilterScope(NumFilters);
126}
127
128void EHScopeStack::popFilter() {
129 assert(!empty() && "popping exception stack when not empty");
130
131 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
132 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
133
John McCallff8e1152010-07-23 21:56:41 +0000134 if (empty()) NextEHDestIndex = FirstEHDestIndex;
135
John McCallf1549f62010-07-06 01:34:17 +0000136 assert(CatchDepth > 0 && "mismatched filter push/pop");
137 CatchDepth--;
138}
139
140EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
141 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
142 CatchDepth++;
John McCallff8e1152010-07-23 21:56:41 +0000143 EHCatchScope *Scope = new (Buffer) EHCatchScope(NumHandlers);
144 for (unsigned I = 0; I != NumHandlers; ++I)
145 Scope->getHandlers()[I].Index = getNextEHDestIndex();
146 return Scope;
John McCallf1549f62010-07-06 01:34:17 +0000147}
148
149void EHScopeStack::pushTerminate() {
150 char *Buffer = allocate(EHTerminateScope::getSize());
151 CatchDepth++;
John McCallff8e1152010-07-23 21:56:41 +0000152 new (Buffer) EHTerminateScope(getNextEHDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000153}
154
155/// Remove any 'null' fixups on the stack. However, we can't pop more
156/// fixups than the fixup depth on the innermost normal cleanup, or
157/// else fixups that we try to add to that cleanup will end up in the
158/// wrong place. We *could* try to shrink fixup depths, but that's
159/// actually a lot of work for little benefit.
160void EHScopeStack::popNullFixups() {
161 // We expect this to only be called when there's still an innermost
162 // normal cleanup; otherwise there really shouldn't be any fixups.
163 assert(hasNormalCleanups());
164
165 EHScopeStack::iterator it = find(InnermostNormalCleanup);
John McCall1f0fca52010-07-21 07:22:38 +0000166 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
John McCallf1549f62010-07-06 01:34:17 +0000167 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
168
169 while (BranchFixups.size() > MinSize &&
170 BranchFixups.back().Destination == 0)
171 BranchFixups.pop_back();
172}
173
Anders Carlssond3379292009-10-30 02:27:02 +0000174static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
175 // void *__cxa_allocate_exception(size_t thrown_size);
176 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
177 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000178
179 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +0000180 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
181 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000182
Anders Carlssond3379292009-10-30 02:27:02 +0000183 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
184}
185
Mike Stump99533832009-12-02 07:41:41 +0000186static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
187 // void __cxa_free_exception(void *thrown_exception);
188 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
189 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000190
191 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000192 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
193 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000194
Mike Stump99533832009-12-02 07:41:41 +0000195 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
196}
197
Anders Carlssond3379292009-10-30 02:27:02 +0000198static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +0000199 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +0000200 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +0000201
202 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
203 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000204
205 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000206 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
207 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000208
Anders Carlssond3379292009-10-30 02:27:02 +0000209 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
210}
211
Mike Stumpb4eea692009-11-20 00:56:31 +0000212static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000213 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +0000214
Mike Stump8755ec32009-12-10 00:06:18 +0000215 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000216 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000217
Mike Stumpb4eea692009-11-20 00:56:31 +0000218 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
219}
220
John McCallf1549f62010-07-06 01:34:17 +0000221static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
222 // void *__cxa_get_exception_ptr(void*);
223 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
224 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
225
226 const llvm::FunctionType *FTy =
227 llvm::FunctionType::get(Int8PtrTy, Args, false);
228
229 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
230}
231
Mike Stump2bf701e2009-11-20 23:44:51 +0000232static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +0000233 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +0000234
235 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
236 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000237
238 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +0000239 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000240
Mike Stump2bf701e2009-11-20 23:44:51 +0000241 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
242}
243
244static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000245 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000246
Mike Stump8755ec32009-12-10 00:06:18 +0000247 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000248 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000249
Mike Stump2bf701e2009-11-20 23:44:51 +0000250 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
251}
252
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000253static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
254 // void __cxa_call_unexepcted(void *thrown_exception);
255
256 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
257 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000258
259 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000260 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
261 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000262
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000263 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
264}
265
Douglas Gregor86a3a032010-05-16 01:24:12 +0000266llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
267 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000268 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000269
270 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000271 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000272 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000273
Douglas Gregor86a3a032010-05-16 01:24:12 +0000274 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000275 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000276 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000277}
278
Mike Stump99533832009-12-02 07:41:41 +0000279static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
280 // void __terminate();
281
Mike Stump8755ec32009-12-10 00:06:18 +0000282 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000283 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000284
David Chisnall79a9ad82010-05-17 13:49:20 +0000285 return CGF.CGM.CreateRuntimeFunction(FTy,
286 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
287}
288
John McCall8262b6a2010-07-17 00:43:08 +0000289static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
290 const char *Name) {
291 const llvm::Type *Int8PtrTy =
292 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
293 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
294
295 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
296 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
297
298 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000299}
300
John McCall8262b6a2010-07-17 00:43:08 +0000301const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
302const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
303const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
304const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
305const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
306 "objc_exception_throw");
307
308static const EHPersonality &getCPersonality(const LangOptions &L) {
309 return EHPersonality::GNU_C;
310}
311
312static const EHPersonality &getObjCPersonality(const LangOptions &L) {
313 if (L.NeXTRuntime) {
314 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
315 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000316 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000317 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000318 }
319}
320
John McCall8262b6a2010-07-17 00:43:08 +0000321static const EHPersonality &getCXXPersonality(const LangOptions &L) {
322 if (L.SjLjExceptions)
323 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000324 else
John McCall8262b6a2010-07-17 00:43:08 +0000325 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000326}
327
328/// Determines the personality function to use when both C++
329/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000330static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000331 // The ObjC personality defers to the C++ personality for non-ObjC
332 // handlers. Unlike the C++ case, we use the same personality
333 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000334 if (L.NeXTRuntime) {
335 if (L.ObjCNonFragileABI)
336 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000337
338 // In the fragile ABI, just use C++ exception handling and hope
339 // they're not doing crazy exception mixing.
340 else
John McCall8262b6a2010-07-17 00:43:08 +0000341 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000342 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000343
John McCall8262b6a2010-07-17 00:43:08 +0000344 // The GNU runtime's personality function inherently doesn't support
345 // mixed EH. Use the C++ personality just to avoid returning null.
346 return getCXXPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000347}
348
John McCall8262b6a2010-07-17 00:43:08 +0000349const EHPersonality &EHPersonality::get(const LangOptions &L) {
350 if (L.CPlusPlus && L.ObjC1)
351 return getObjCXXPersonality(L);
352 else if (L.CPlusPlus)
353 return getCXXPersonality(L);
354 else if (L.ObjC1)
355 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000356 else
John McCall8262b6a2010-07-17 00:43:08 +0000357 return getCPersonality(L);
358}
John McCallf1549f62010-07-06 01:34:17 +0000359
John McCall8262b6a2010-07-17 00:43:08 +0000360static llvm::Constant *getPersonalityFn(CodeGenFunction &CGF,
361 const EHPersonality &Personality) {
362 const char *Name = Personality.getPersonalityFnName();
363
364 llvm::Constant *Fn =
John McCallf1549f62010-07-06 01:34:17 +0000365 CGF.CGM.CreateRuntimeFunction(llvm::FunctionType::get(
366 llvm::Type::getInt32Ty(
367 CGF.CGM.getLLVMContext()),
368 true),
369 Name);
John McCall8262b6a2010-07-17 00:43:08 +0000370 return llvm::ConstantExpr::getBitCast(Fn, CGF.CGM.PtrToInt8Ty);
John McCallf1549f62010-07-06 01:34:17 +0000371}
372
373/// Returns the value to inject into a selector to indicate the
374/// presence of a catch-all.
375static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
376 // Possibly we should use @llvm.eh.catch.all.value here.
377 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
378}
379
380/// Returns the value to inject into a selector to indicate the
381/// presence of a cleanup.
382static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
383 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000384}
385
John McCall09faeab2010-07-13 21:17:51 +0000386namespace {
387 /// A cleanup to free the exception object if its initialization
388 /// throws.
John McCall1f0fca52010-07-21 07:22:38 +0000389 struct FreeExceptionCleanup : EHScopeStack::Cleanup {
John McCall09faeab2010-07-13 21:17:51 +0000390 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
391 llvm::Value *ExnLocVar)
392 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
393
394 llvm::Value *ShouldFreeVar;
395 llvm::Value *ExnLocVar;
396
397 void Emit(CodeGenFunction &CGF, bool IsForEH) {
398 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
399 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
400
401 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
402 "should-free-exnobj");
403 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
404 CGF.EmitBlock(FreeBB);
405 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
406 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
407 ->setDoesNotThrow();
408 CGF.EmitBlock(DoneBB);
409 }
410 };
411}
412
John McCallac418162010-04-22 01:10:34 +0000413// Emits an exception expression into the given location. This
414// differs from EmitAnyExprToMem only in that, if a final copy-ctor
415// call is required, an exception within that copy ctor causes
416// std::terminate to be invoked.
417static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
418 llvm::Value *ExnLoc) {
419 // We want to release the allocated exception object if this
420 // expression throws. We do this by pushing an EH-only cleanup
421 // block which, furthermore, deactivates itself after the expression
422 // is complete.
423 llvm::AllocaInst *ShouldFreeVar =
424 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
425 "should-free-exnobj.var");
426 CGF.InitTempAlloca(ShouldFreeVar,
427 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump0f590be2009-12-01 03:41:18 +0000428
John McCallac418162010-04-22 01:10:34 +0000429 // A variable holding the exception pointer. This is necessary
430 // because the throw expression does not necessarily dominate the
431 // cleanup, for example if it appears in a conditional expression.
432 llvm::AllocaInst *ExnLocVar =
433 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump8755ec32009-12-10 00:06:18 +0000434
John McCallf1549f62010-07-06 01:34:17 +0000435 // Make sure the exception object is cleaned up if there's an
436 // exception during initialization.
John McCall09faeab2010-07-13 21:17:51 +0000437 // FIXME: stmt expressions might require this to be a normal
438 // cleanup, too.
John McCall1f0fca52010-07-21 07:22:38 +0000439 CGF.EHStack.pushCleanup<FreeExceptionCleanup>(EHCleanup,
440 ShouldFreeVar,
441 ExnLocVar);
John McCallf1549f62010-07-06 01:34:17 +0000442 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000443
444 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
445 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
446 ShouldFreeVar);
447
448 // __cxa_allocate_exception returns a void*; we need to cast this
449 // to the appropriate type for the object.
450 const llvm::Type *Ty = CGF.ConvertType(E->getType())->getPointerTo();
451 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
452
453 // FIXME: this isn't quite right! If there's a final unelided call
454 // to a copy constructor, then according to [except.terminate]p1 we
455 // must call std::terminate() if that constructor throws, because
456 // technically that copy occurs after the exception expression is
457 // evaluated but before the exception is caught. But the best way
458 // to handle that is to teach EmitAggExpr to do the final copy
459 // differently if it can't be elided.
John McCall558d2ab2010-09-15 10:14:12 +0000460 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false, /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000461
462 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
463 ShouldFreeVar);
464
John McCallf1549f62010-07-06 01:34:17 +0000465 // Technically, the exception object is like a temporary; it has to
466 // be cleaned up when its full-expression is complete.
467 // Unfortunately, the AST represents full-expressions by creating a
468 // CXXExprWithTemporaries, which it only does when there are actually
469 // temporaries.
470 //
471 // If any cleanups have been added since we pushed ours, they must
472 // be from temporaries; this will get popped at the same time.
473 // Otherwise we need to pop ours off. FIXME: this is very brittle.
474 if (Cleanup == CGF.EHStack.stable_begin())
475 CGF.PopCleanupBlock();
Mike Stump0f590be2009-12-01 03:41:18 +0000476}
477
John McCallf1549f62010-07-06 01:34:17 +0000478llvm::Value *CodeGenFunction::getExceptionSlot() {
479 if (!ExceptionSlot) {
480 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
481 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000482 }
John McCallf1549f62010-07-06 01:34:17 +0000483 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000484}
485
Anders Carlsson756b5c42009-10-30 01:42:31 +0000486void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000487 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000488 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000489 Builder.CreateInvoke(getReThrowFn(*this),
490 getUnreachableBlock(),
491 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000492 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000493 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000494 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000495 Builder.CreateUnreachable();
496 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000497
498 // Clear the insertion point to indicate we are in unreachable code.
499 Builder.ClearInsertionPoint();
Anders Carlssond3379292009-10-30 02:27:02 +0000500 return;
501 }
Mike Stump8755ec32009-12-10 00:06:18 +0000502
Anders Carlssond3379292009-10-30 02:27:02 +0000503 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000504
Anders Carlssond3379292009-10-30 02:27:02 +0000505 // Now allocate the exception object.
506 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000507 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000508
Anders Carlssond3379292009-10-30 02:27:02 +0000509 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000510 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000511 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000512 llvm::ConstantInt::get(SizeTy, TypeSize),
513 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000514 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000515
John McCallac418162010-04-22 01:10:34 +0000516 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000517
Anders Carlssond3379292009-10-30 02:27:02 +0000518 // Now throw the exception.
519 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall9dffe6f2010-04-30 01:15:21 +0000520 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
John McCallac418162010-04-22 01:10:34 +0000521
522 // The address of the destructor. If the exception type has a
523 // trivial destructor (or isn't a record), we just pass null.
524 llvm::Constant *Dtor = 0;
525 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
526 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
527 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000528 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000529 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
530 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
531 }
532 }
533 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000534
Mike Stump0a3816e2009-12-04 01:51:45 +0000535 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000536 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000537 Builder.CreateInvoke3(getThrowFn(*this),
538 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000539 ExceptionPtr, TypeInfo, Dtor);
540 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000541 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000542 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000543 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
544 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000545 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000546 }
Mike Stump8755ec32009-12-10 00:06:18 +0000547
Anders Carlssond3379292009-10-30 02:27:02 +0000548 // Clear the insertion point to indicate we are in unreachable code.
549 Builder.ClearInsertionPoint();
Mike Stumpc2ab4862009-12-07 20:12:14 +0000550
551 // FIXME: For now, emit a dummy basic block because expr emitters in generally
552 // are not ready to handle emitting expressions at unreachable points.
553 EnsureInsertPoint();
Anders Carlsson756b5c42009-10-30 01:42:31 +0000554}
Mike Stump2bf701e2009-11-20 23:44:51 +0000555
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000556void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000557 if (!Exceptions)
558 return;
559
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000560 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
561 if (FD == 0)
562 return;
563 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
564 if (Proto == 0)
565 return;
566
567 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
568
569 if (!Proto->hasExceptionSpec())
570 return;
571
John McCallf1549f62010-07-06 01:34:17 +0000572 unsigned NumExceptions = Proto->getNumExceptions();
573 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000574
John McCallf1549f62010-07-06 01:34:17 +0000575 for (unsigned I = 0; I != NumExceptions; ++I) {
576 QualType Ty = Proto->getExceptionType(I);
577 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
John McCall9dffe6f2010-04-30 01:15:21 +0000578 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
John McCallf1549f62010-07-06 01:34:17 +0000579 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000580 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000581}
582
583void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000584 if (!Exceptions)
585 return;
586
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000587 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
588 if (FD == 0)
589 return;
590 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
591 if (Proto == 0)
592 return;
593
594 if (!Proto->hasExceptionSpec())
595 return;
596
John McCallf1549f62010-07-06 01:34:17 +0000597 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000598}
599
Mike Stump2bf701e2009-11-20 23:44:51 +0000600void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000601 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000602 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000603 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000604}
605
John McCall59a70002010-07-07 06:56:46 +0000606void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000607 unsigned NumHandlers = S.getNumHandlers();
608 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000609
John McCallf1549f62010-07-06 01:34:17 +0000610 for (unsigned I = 0; I != NumHandlers; ++I) {
611 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000612
John McCallf1549f62010-07-06 01:34:17 +0000613 llvm::BasicBlock *Handler = createBasicBlock("catch");
614 if (C->getExceptionDecl()) {
615 // FIXME: Dropping the reference type on the type into makes it
616 // impossible to correctly implement catch-by-reference
617 // semantics for pointers. Unfortunately, this is what all
618 // existing compilers do, and it's not clear that the standard
619 // personality routine is capable of doing this right. See C++ DR 388:
620 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
621 QualType CaughtType = C->getCaughtType();
622 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000623
624 llvm::Value *TypeInfo = 0;
625 if (CaughtType->isObjCObjectPointerType())
626 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
627 else
628 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, true);
John McCallf1549f62010-07-06 01:34:17 +0000629 CatchScope->setHandler(I, TypeInfo, Handler);
630 } else {
631 // No exception decl indicates '...', a catch-all.
632 CatchScope->setCatchAllHandler(I, Handler);
633 }
634 }
John McCallf1549f62010-07-06 01:34:17 +0000635}
636
637/// Check whether this is a non-EH scope, i.e. a scope which doesn't
638/// affect exception handling. Currently, the only non-EH scopes are
639/// normal-only cleanup scopes.
640static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000641 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000642 case EHScope::Cleanup:
643 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000644 case EHScope::Filter:
645 case EHScope::Catch:
646 case EHScope::Terminate:
647 return false;
648 }
649
650 // Suppress warning.
651 return false;
John McCallf1549f62010-07-06 01:34:17 +0000652}
653
654llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
655 assert(EHStack.requiresLandingPad());
656 assert(!EHStack.empty());
657
John McCallda65ea82010-07-13 20:32:21 +0000658 if (!Exceptions)
659 return 0;
660
John McCallf1549f62010-07-06 01:34:17 +0000661 // Check the innermost scope for a cached landing pad. If this is
662 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
663 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
664 if (LP) return LP;
665
666 // Build the landing pad for this scope.
667 LP = EmitLandingPad();
668 assert(LP);
669
670 // Cache the landing pad on the innermost scope. If this is a
671 // non-EH scope, cache the landing pad on the enclosing scope, too.
672 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
673 ir->setCachedLandingPad(LP);
674 if (!isNonEHScope(*ir)) break;
675 }
676
677 return LP;
678}
679
680llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
681 assert(EHStack.requiresLandingPad());
682
683 // This function contains a hack to work around a design flaw in
684 // LLVM's EH IR which breaks semantics after inlining. This same
685 // hack is implemented in llvm-gcc.
686 //
687 // The LLVM EH abstraction is basically a thin veneer over the
688 // traditional GCC zero-cost design: for each range of instructions
689 // in the function, there is (at most) one "landing pad" with an
690 // associated chain of EH actions. A language-specific personality
691 // function interprets this chain of actions and (1) decides whether
692 // or not to resume execution at the landing pad and (2) if so,
693 // provides an integer indicating why it's stopping. In LLVM IR,
694 // the association of a landing pad with a range of instructions is
695 // achieved via an invoke instruction, the chain of actions becomes
696 // the arguments to the @llvm.eh.selector call, and the selector
697 // call returns the integer indicator. Other than the required
698 // presence of two intrinsic function calls in the landing pad,
699 // the IR exactly describes the layout of the output code.
700 //
701 // A principal advantage of this design is that it is completely
702 // language-agnostic; in theory, the LLVM optimizers can treat
703 // landing pads neutrally, and targets need only know how to lower
704 // the intrinsics to have a functioning exceptions system (assuming
705 // that platform exceptions follow something approximately like the
706 // GCC design). Unfortunately, landing pads cannot be combined in a
707 // language-agnostic way: given selectors A and B, there is no way
708 // to make a single landing pad which faithfully represents the
709 // semantics of propagating an exception first through A, then
710 // through B, without knowing how the personality will interpret the
711 // (lowered form of the) selectors. This means that inlining has no
712 // choice but to crudely chain invokes (i.e., to ignore invokes in
713 // the inlined function, but to turn all unwindable calls into
714 // invokes), which is only semantically valid if every unwind stops
715 // at every landing pad.
716 //
717 // Therefore, the invoke-inline hack is to guarantee that every
718 // landing pad has a catch-all.
719 const bool UseInvokeInlineHack = true;
720
721 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
722 assert(ir != EHStack.end() &&
723 "stack requiring landing pad is nothing but non-EH scopes?");
724
725 // If this is a terminate scope, just use the singleton terminate
726 // landing pad.
727 if (isa<EHTerminateScope>(*ir))
728 return getTerminateLandingPad();
729
730 // If this isn't an EH scope, iterate; otherwise break out.
731 if (!isNonEHScope(*ir)) break;
732 ++ir;
733
734 // We haven't checked this scope for a cached landing pad yet.
735 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
736 return LP;
737 }
738
739 // Save the current IR generation state.
740 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
741
John McCall8262b6a2010-07-17 00:43:08 +0000742 const EHPersonality &Personality =
743 EHPersonality::get(CGF.CGM.getLangOptions());
744
John McCallf1549f62010-07-06 01:34:17 +0000745 // Create and configure the landing pad.
746 llvm::BasicBlock *LP = createBasicBlock("lpad");
747 EmitBlock(LP);
748
749 // Save the exception pointer. It's safe to use a single exception
750 // pointer per function because EH cleanups can never have nested
751 // try/catches.
752 llvm::CallInst *Exn =
753 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
754 Exn->setDoesNotThrow();
755 Builder.CreateStore(Exn, getExceptionSlot());
756
757 // Build the selector arguments.
758 llvm::SmallVector<llvm::Value*, 8> EHSelector;
759 EHSelector.push_back(Exn);
John McCall8262b6a2010-07-17 00:43:08 +0000760 EHSelector.push_back(getPersonalityFn(*this, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000761
762 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000763 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
764 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000765 bool HasEHCleanup = false;
766 bool HasEHFilter = false;
767 llvm::SmallVector<llvm::Value*, 8> EHFilters;
768 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
769 I != E; ++I) {
770
771 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000772 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000773 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000774 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000775 // We otherwise don't care about cleanups.
776 continue;
777
John McCallf1549f62010-07-06 01:34:17 +0000778 case EHScope::Filter: {
779 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000780 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000781
782 // Filter scopes get added to the selector in wierd ways.
783 EHFilterScope &Filter = cast<EHFilterScope>(*I);
784 HasEHFilter = true;
785
786 // Add all the filter values which we aren't already explicitly
787 // catching.
788 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
789 llvm::Value *FV = Filter.getFilter(I);
790 if (!EHHandlers.count(FV))
791 EHFilters.push_back(FV);
792 }
793 goto done;
794 }
795
796 case EHScope::Terminate:
797 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000798 assert(!CatchAll.isValid());
799 CatchAll = UnwindDest(getTerminateHandler(),
800 EHStack.getEnclosingEHCleanup(I),
801 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000802 goto done;
803
804 case EHScope::Catch:
805 break;
806 }
807
808 EHCatchScope &Catch = cast<EHCatchScope>(*I);
809 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
810 EHCatchScope::Handler Handler = Catch.getHandler(HI);
811
812 // Catch-all. We should only have one of these per catch.
813 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000814 assert(!CatchAll.isValid());
815 CatchAll = UnwindDest(Handler.Block,
816 EHStack.getEnclosingEHCleanup(I),
817 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000818 continue;
819 }
820
821 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000822 UnwindDest &Dest = EHHandlers[Handler.Type];
823 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000824
825 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000826 Dest = UnwindDest(Handler.Block,
827 EHStack.getEnclosingEHCleanup(I),
828 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000829 }
830
831 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000832 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000833 }
834
835 done:
836 unsigned LastToEmitInLoop = EHSelector.size();
837
838 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000839 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000840 EHSelector.push_back(getCatchAllValue(CGF));
841
842 // If we have an EH filter, we need to add those handlers in the
843 // right place in the selector, which is to say, at the end.
844 } else if (HasEHFilter) {
845 // Create a filter expression: an integer constant saying how many
846 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
847 // followed by the filter types. The personality routine only
848 // lands here if the filter doesn't match.
849 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
850 EHFilters.size() + 1));
851 EHSelector.append(EHFilters.begin(), EHFilters.end());
852
853 // Also check whether we need a cleanup.
854 if (UseInvokeInlineHack || HasEHCleanup)
855 EHSelector.push_back(UseInvokeInlineHack
856 ? getCatchAllValue(CGF)
857 : getCleanupValue(CGF));
858
859 // Otherwise, signal that we at least have cleanups.
860 } else if (UseInvokeInlineHack || HasEHCleanup) {
861 EHSelector.push_back(UseInvokeInlineHack
862 ? getCatchAllValue(CGF)
863 : getCleanupValue(CGF));
864 } else {
865 assert(LastToEmitInLoop > 2);
866 LastToEmitInLoop--;
867 }
868
869 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
870
871 // Tell the backend how to generate the landing pad.
872 llvm::CallInst *Selection =
873 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
874 EHSelector.begin(), EHSelector.end(), "eh.selector");
875 Selection->setDoesNotThrow();
876
877 // Select the right handler.
878 llvm::Value *llvm_eh_typeid_for =
879 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
880
881 // The results of llvm_eh_typeid_for aren't reliable --- at least
882 // not locally --- so we basically have to do this as an 'if' chain.
883 // We walk through the first N-1 catch clauses, testing and chaining,
884 // and then fall into the final clause (which is either a cleanup, a
885 // filter (possibly with a cleanup), a catch-all, or another catch).
886 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
887 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000888 UnwindDest Dest = EHHandlers[Type];
889 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000890
891 // Figure out where to branch on a match. As a debug code-size
892 // optimization, if the scope depth matches the innermost cleanup,
893 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000894 llvm::BasicBlock *Match = Dest.getBlock();
895 bool MatchNeedsCleanup =
896 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000897 if (MatchNeedsCleanup)
898 Match = createBasicBlock("eh.match");
899
900 llvm::BasicBlock *Next = createBasicBlock("eh.next");
901
902 // Check whether the exception matches.
903 llvm::CallInst *Id
904 = Builder.CreateCall(llvm_eh_typeid_for,
905 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
906 Id->setDoesNotThrow();
907 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
908 Match, Next);
909
910 // Emit match code if necessary.
911 if (MatchNeedsCleanup) {
912 EmitBlock(Match);
913 EmitBranchThroughEHCleanup(Dest);
914 }
915
916 // Continue to the next match.
917 EmitBlock(Next);
918 }
919
920 // Emit the final case in the selector.
921 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000922 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000923 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
924 EmitBranchThroughEHCleanup(CatchAll);
925
926 // ...or an EH filter...
927 } else if (HasEHFilter) {
928 llvm::Value *SavedSelection = Selection;
929
930 // First, unwind out to the outermost scope if necessary.
931 if (EHStack.hasEHCleanups()) {
932 // The end here might not dominate the beginning, so we might need to
933 // save the selector if we need it.
934 llvm::AllocaInst *SelectorVar = 0;
935 if (HasEHCleanup) {
936 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
937 Builder.CreateStore(Selection, SelectorVar);
938 }
939
940 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000941 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
942 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000943 EmitBlock(CleanupContBB);
944
945 if (HasEHCleanup)
946 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
947 }
948
949 // If there was a cleanup, we'll need to actually check whether we
950 // landed here because the filter triggered.
951 if (UseInvokeInlineHack || HasEHCleanup) {
952 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
953 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
954
955 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
956 llvm::Value *FailsFilter =
957 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
958 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
959
960 // The rethrow block is where we land if this was a cleanup.
961 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
962 EmitBlock(RethrowBB);
963 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
964 Builder.CreateLoad(getExceptionSlot()))
965 ->setDoesNotReturn();
966 Builder.CreateUnreachable();
967
968 EmitBlock(UnexpectedBB);
969 }
970
971 // Call __cxa_call_unexpected. This doesn't need to be an invoke
972 // because __cxa_call_unexpected magically filters exceptions
973 // according to the last landing pad the exception was thrown
974 // into. Seriously.
975 Builder.CreateCall(getUnexpectedFn(*this),
976 Builder.CreateLoad(getExceptionSlot()))
977 ->setDoesNotReturn();
978 Builder.CreateUnreachable();
979
980 // ...or a normal catch handler...
981 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
982 llvm::Value *Type = EHSelector.back();
983 EmitBranchThroughEHCleanup(EHHandlers[Type]);
984
985 // ...or a cleanup.
986 } else {
John McCallff8e1152010-07-23 21:56:41 +0000987 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +0000988 }
989
990 // Restore the old IR generation state.
991 Builder.restoreIP(SavedIP);
992
993 return LP;
994}
995
John McCall8e3f8612010-07-13 22:12:14 +0000996namespace {
997 /// A cleanup to call __cxa_end_catch. In many cases, the caught
998 /// exception type lets us state definitively that the thrown exception
999 /// type does not have a destructor. In particular:
1000 /// - Catch-alls tell us nothing, so we have to conservatively
1001 /// assume that the thrown exception might have a destructor.
1002 /// - Catches by reference behave according to their base types.
1003 /// - Catches of non-record types will only trigger for exceptions
1004 /// of non-record types, which never have destructors.
1005 /// - Catches of record types can trigger for arbitrary subclasses
1006 /// of the caught type, so we have to assume the actual thrown
1007 /// exception type might have a throwing destructor, even if the
1008 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +00001009 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +00001010 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1011 bool MightThrow;
1012
1013 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1014 if (!MightThrow) {
1015 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1016 return;
1017 }
1018
1019 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1020 }
1021 };
1022}
1023
John McCallf1549f62010-07-06 01:34:17 +00001024/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1025/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001026///
1027/// \param EndMightThrow - true if __cxa_end_catch might throw
1028static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1029 llvm::Value *Exn,
1030 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +00001031 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1032 Call->setDoesNotThrow();
1033
John McCall1f0fca52010-07-21 07:22:38 +00001034 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +00001035
1036 return Call;
1037}
1038
1039/// A "special initializer" callback for initializing a catch
1040/// parameter during catch initialization.
1041static void InitCatchParam(CodeGenFunction &CGF,
1042 const VarDecl &CatchParam,
1043 llvm::Value *ParamAddr) {
1044 // Load the exception from where the landing pad saved it.
1045 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1046
1047 CanQualType CatchType =
1048 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1049 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1050
1051 // If we're catching by reference, we can just cast the object
1052 // pointer to the appropriate pointer.
1053 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +00001054 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1055 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +00001056
John McCallf1549f62010-07-06 01:34:17 +00001057 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +00001058 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +00001059
1060 // We have no way to tell the personality function that we're
1061 // catching by reference, so if we're catching a pointer,
1062 // __cxa_begin_catch will actually return that pointer by value.
1063 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1064 QualType PointeeType = PT->getPointeeType();
1065
1066 // When catching by reference, generally we should just ignore
1067 // this by-value pointer and use the exception object instead.
1068 if (!PointeeType->isRecordType()) {
1069
1070 // Exn points to the struct _Unwind_Exception header, which
1071 // we have to skip past in order to reach the exception data.
1072 unsigned HeaderSize =
1073 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1074 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1075
1076 // However, if we're catching a pointer-to-record type that won't
1077 // work, because the personality function might have adjusted
1078 // the pointer. There's actually no way for us to fully satisfy
1079 // the language/ABI contract here: we can't use Exn because it
1080 // might have the wrong adjustment, but we can't use the by-value
1081 // pointer because it's off by a level of abstraction.
1082 //
1083 // The current solution is to dump the adjusted pointer into an
1084 // alloca, which breaks language semantics (because changing the
1085 // pointer doesn't change the exception) but at least works.
1086 // The better solution would be to filter out non-exact matches
1087 // and rethrow them, but this is tricky because the rethrow
1088 // really needs to be catchable by other sites at this landing
1089 // pad. The best solution is to fix the personality function.
1090 } else {
1091 // Pull the pointer for the reference type off.
1092 const llvm::Type *PtrTy =
1093 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1094
1095 // Create the temporary and write the adjusted pointer into it.
1096 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1097 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1098 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1099
1100 // Bind the reference to the temporary.
1101 AdjustedExn = ExnPtrTmp;
1102 }
1103 }
1104
John McCallf1549f62010-07-06 01:34:17 +00001105 llvm::Value *ExnCast =
1106 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1107 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1108 return;
1109 }
1110
1111 // Non-aggregates (plus complexes).
1112 bool IsComplex = false;
1113 if (!CGF.hasAggregateLLVMType(CatchType) ||
1114 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001115 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001116
1117 // If the catch type is a pointer type, __cxa_begin_catch returns
1118 // the pointer by value.
1119 if (CatchType->hasPointerRepresentation()) {
1120 llvm::Value *CastExn =
1121 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1122 CGF.Builder.CreateStore(CastExn, ParamAddr);
1123 return;
1124 }
1125
1126 // Otherwise, it returns a pointer into the exception object.
1127
1128 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1129 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1130
1131 if (IsComplex) {
1132 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1133 ParamAddr, /*volatile*/ false);
1134 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001135 unsigned Alignment =
1136 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001137 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001138 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1139 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001140 }
1141 return;
1142 }
1143
1144 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1145 // initializer expression.
1146
1147 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1148 assert(RD && "aggregate catch type was not a record!");
1149
1150 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1151
1152 if (RD->hasTrivialCopyConstructor()) {
John McCall8e3f8612010-07-13 22:12:14 +00001153 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001154 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1155 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1156 return;
1157 }
1158
1159 // We have to call __cxa_get_exception_ptr to get the adjusted
1160 // pointer before copying.
1161 llvm::CallInst *AdjustedExn =
1162 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1163 AdjustedExn->setDoesNotThrow();
1164 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1165
1166 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1167 assert(CD && "record has no copy constructor!");
1168 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1169
1170 CallArgList CallArgs;
1171 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1172 CD->getThisType(CGF.getContext())));
1173 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1174 CD->getParamDecl(0)->getType()));
1175
1176 const FunctionProtoType *FPT
1177 = CD->getType()->getAs<FunctionProtoType>();
1178
1179 // Call the copy ctor in a terminate scope.
1180 CGF.EHStack.pushTerminate();
1181 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1182 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1183 CGF.EHStack.popTerminate();
1184
1185 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001186 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001187}
1188
1189/// Begins a catch statement by initializing the catch variable and
1190/// calling __cxa_begin_catch.
1191static void BeginCatch(CodeGenFunction &CGF,
1192 const CXXCatchStmt *S) {
1193 // We have to be very careful with the ordering of cleanups here:
1194 // C++ [except.throw]p4:
1195 // The destruction [of the exception temporary] occurs
1196 // immediately after the destruction of the object declared in
1197 // the exception-declaration in the handler.
1198 //
1199 // So the precise ordering is:
1200 // 1. Construct catch variable.
1201 // 2. __cxa_begin_catch
1202 // 3. Enter __cxa_end_catch cleanup
1203 // 4. Enter dtor cleanup
1204 //
1205 // We do this by initializing the exception variable with a
1206 // "special initializer", InitCatchParam. Delegation sequence:
1207 // - ExitCXXTryStmt opens a RunCleanupsScope
1208 // - EmitLocalBlockVarDecl creates the variable and debug info
1209 // - InitCatchParam initializes the variable from the exception
1210 // - CallBeginCatch calls __cxa_begin_catch
1211 // - CallBeginCatch enters the __cxa_end_catch cleanup
1212 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1213 // - EmitCXXTryStmt emits the code for the catch body
1214 // - EmitCXXTryStmt close the RunCleanupsScope
1215
1216 VarDecl *CatchParam = S->getExceptionDecl();
1217 if (!CatchParam) {
1218 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001219 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001220 return;
1221 }
1222
1223 // Emit the local.
1224 CGF.EmitLocalBlockVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001225}
1226
John McCallfcd5c0c2010-07-13 22:24:23 +00001227namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001228 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001229 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1230 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1231 }
1232 };
1233}
1234
John McCall59a70002010-07-07 06:56:46 +00001235void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001236 unsigned NumHandlers = S.getNumHandlers();
1237 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1238 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001239
John McCallf1549f62010-07-06 01:34:17 +00001240 // Copy the handler blocks off before we pop the EH stack. Emitting
1241 // the handlers might scribble on this memory.
1242 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1243 memcpy(Handlers.data(), CatchScope.begin(),
1244 NumHandlers * sizeof(EHCatchScope::Handler));
1245 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001246
John McCallf1549f62010-07-06 01:34:17 +00001247 // The fall-through block.
1248 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001249
John McCallf1549f62010-07-06 01:34:17 +00001250 // We just emitted the body of the try; jump to the continue block.
1251 if (HaveInsertPoint())
1252 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001253
John McCall59a70002010-07-07 06:56:46 +00001254 // Determine if we need an implicit rethrow for all these catch handlers.
1255 bool ImplicitRethrow = false;
1256 if (IsFnTryBlock)
1257 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1258 isa<CXXConstructorDecl>(CurCodeDecl);
1259
John McCallf1549f62010-07-06 01:34:17 +00001260 for (unsigned I = 0; I != NumHandlers; ++I) {
1261 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1262 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001263
John McCallf1549f62010-07-06 01:34:17 +00001264 // Catch the exception if this isn't a catch-all.
1265 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001266
John McCallf1549f62010-07-06 01:34:17 +00001267 // Enter a cleanup scope, including the catch variable and the
1268 // end-catch.
1269 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001270
John McCallf1549f62010-07-06 01:34:17 +00001271 // Initialize the catch variable and set up the cleanups.
1272 BeginCatch(*this, C);
1273
John McCall59a70002010-07-07 06:56:46 +00001274 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001275 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1276 // called, and so it is pushed after BeginCatch.
1277 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001278 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001279
John McCallf1549f62010-07-06 01:34:17 +00001280 // Perform the body of the catch.
1281 EmitStmt(C->getHandlerBlock());
1282
1283 // Fall out through the catch cleanups.
1284 CatchScope.ForceCleanup();
1285
1286 // Branch out of the try.
1287 if (HaveInsertPoint())
1288 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001289 }
1290
John McCallf1549f62010-07-06 01:34:17 +00001291 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001292}
Mike Stumpd88ea562009-12-09 03:35:49 +00001293
John McCall55b20fc2010-07-21 00:52:03 +00001294namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001295 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001296 llvm::Value *ForEHVar;
1297 llvm::Value *EndCatchFn;
1298 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1299 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1300
1301 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1302 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1303 llvm::BasicBlock *CleanupContBB =
1304 CGF.createBasicBlock("finally.cleanup.cont");
1305
1306 llvm::Value *ShouldEndCatch =
1307 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1308 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1309 CGF.EmitBlock(EndCatchBB);
1310 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1311 CGF.EmitBlock(CleanupContBB);
1312 }
1313 };
John McCall77199712010-07-21 05:47:49 +00001314
John McCall1f0fca52010-07-21 07:22:38 +00001315 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001316 const Stmt *Body;
1317 llvm::Value *ForEHVar;
1318 llvm::Value *EndCatchFn;
1319 llvm::Value *RethrowFn;
1320 llvm::Value *SavedExnVar;
1321
1322 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1323 llvm::Value *EndCatchFn,
1324 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1325 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1326 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1327
1328 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1329 // Enter a cleanup to call the end-catch function if one was provided.
1330 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001331 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1332 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001333
John McCalld96a8e72010-08-11 00:16:14 +00001334 // Save the current cleanup destination in case there are
1335 // cleanups in the finally block.
1336 llvm::Value *SavedCleanupDest =
1337 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1338 "cleanup.dest.saved");
1339
John McCall77199712010-07-21 05:47:49 +00001340 // Emit the finally block.
1341 CGF.EmitStmt(Body);
1342
1343 // If the end of the finally is reachable, check whether this was
1344 // for EH. If so, rethrow.
1345 if (CGF.HaveInsertPoint()) {
1346 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1347 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1348
1349 llvm::Value *ShouldRethrow =
1350 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1351 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1352
1353 CGF.EmitBlock(RethrowBB);
1354 if (SavedExnVar) {
1355 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1356 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1357 } else {
1358 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1359 }
1360 CGF.Builder.CreateUnreachable();
1361
1362 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001363
1364 // Restore the cleanup destination.
1365 CGF.Builder.CreateStore(SavedCleanupDest,
1366 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001367 }
1368
1369 // Leave the end-catch cleanup. As an optimization, pretend that
1370 // the fallthrough path was inaccessible; we've dynamically proven
1371 // that we're not in the EH case along that path.
1372 if (EndCatchFn) {
1373 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1374 CGF.PopCleanupBlock();
1375 CGF.Builder.restoreIP(SavedIP);
1376 }
1377
1378 // Now make sure we actually have an insertion point or the
1379 // cleanup gods will hate us.
1380 CGF.EnsureInsertPoint();
1381 }
1382 };
John McCall55b20fc2010-07-21 00:52:03 +00001383}
1384
John McCallf1549f62010-07-06 01:34:17 +00001385/// Enters a finally block for an implementation using zero-cost
1386/// exceptions. This is mostly general, but hard-codes some
1387/// language/ABI-specific behavior in the catch-all sections.
1388CodeGenFunction::FinallyInfo
1389CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1390 llvm::Constant *BeginCatchFn,
1391 llvm::Constant *EndCatchFn,
1392 llvm::Constant *RethrowFn) {
1393 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1394 "begin/end catch functions not paired");
1395 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001396
John McCallf1549f62010-07-06 01:34:17 +00001397 // The rethrow function has one of the following two types:
1398 // void (*)()
1399 // void (*)(void*)
1400 // In the latter case we need to pass it the exception object.
1401 // But we can't use the exception slot because the @finally might
1402 // have a landing pad (which would overwrite the exception slot).
1403 const llvm::FunctionType *RethrowFnTy =
1404 cast<llvm::FunctionType>(
1405 cast<llvm::PointerType>(RethrowFn->getType())
1406 ->getElementType());
1407 llvm::Value *SavedExnVar = 0;
1408 if (RethrowFnTy->getNumParams())
1409 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001410
John McCallf1549f62010-07-06 01:34:17 +00001411 // A finally block is a statement which must be executed on any edge
1412 // out of a given scope. Unlike a cleanup, the finally block may
1413 // contain arbitrary control flow leading out of itself. In
1414 // addition, finally blocks should always be executed, even if there
1415 // are no catch handlers higher on the stack. Therefore, we
1416 // surround the protected scope with a combination of a normal
1417 // cleanup (to catch attempts to break out of the block via normal
1418 // control flow) and an EH catch-all (semantically "outside" any try
1419 // statement to which the finally block might have been attached).
1420 // The finally block itself is generated in the context of a cleanup
1421 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001422
John McCallf1549f62010-07-06 01:34:17 +00001423 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001424
John McCallf1549f62010-07-06 01:34:17 +00001425 // Jump destination for performing the finally block on an exception
1426 // edge. We'll never actually reach this block, so unreachable is
1427 // fine.
1428 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001429
John McCallf1549f62010-07-06 01:34:17 +00001430 // Whether the finally block is being executed for EH purposes.
1431 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1432 "finally.for-eh");
1433 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001434
John McCallf1549f62010-07-06 01:34:17 +00001435 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001436 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1437 ForEHVar, EndCatchFn,
1438 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001439
1440 // Enter a catch-all scope.
1441 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1442 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1443 Builder.SetInsertPoint(CatchAllBB);
1444
1445 // If there's a begin-catch function, call it.
1446 if (BeginCatchFn) {
1447 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1448 ->setDoesNotThrow();
1449 }
1450
1451 // If we need to remember the exception pointer to rethrow later, do so.
1452 if (SavedExnVar) {
1453 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1454 Builder.CreateStore(SavedExn, SavedExnVar);
1455 }
1456
1457 // Tell the finally block that we're in EH.
1458 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1459
1460 // Thread a jump through the finally cleanup.
1461 EmitBranchThroughCleanup(RethrowDest);
1462
1463 Builder.restoreIP(SavedIP);
1464
1465 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1466 CatchScope->setCatchAllHandler(0, CatchAllBB);
1467
1468 return Info;
1469}
1470
1471void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1472 // Leave the finally catch-all.
1473 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1474 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1475 EHStack.popCatch();
1476
1477 // And leave the normal cleanup.
1478 PopCleanupBlock();
1479
1480 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1481 EmitBlock(CatchAllBB, true);
1482
1483 Builder.restoreIP(SavedIP);
1484}
1485
1486llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1487 if (TerminateLandingPad)
1488 return TerminateLandingPad;
1489
1490 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1491
1492 // This will get inserted at the end of the function.
1493 TerminateLandingPad = createBasicBlock("terminate.lpad");
1494 Builder.SetInsertPoint(TerminateLandingPad);
1495
1496 // Tell the backend that this is a landing pad.
1497 llvm::CallInst *Exn =
1498 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1499 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001500
1501 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001502
1503 // Tell the backend what the exception table should be:
1504 // nothing but a catch-all.
John McCall8262b6a2010-07-17 00:43:08 +00001505 llvm::Value *Args[3] = { Exn, getPersonalityFn(*this, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001506 getCatchAllValue(*this) };
1507 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1508 Args, Args+3, "eh.selector")
1509 ->setDoesNotThrow();
1510
1511 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1512 TerminateCall->setDoesNotReturn();
1513 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001514 CGF.Builder.CreateUnreachable();
1515
John McCallf1549f62010-07-06 01:34:17 +00001516 // Restore the saved insertion state.
1517 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001518
John McCallf1549f62010-07-06 01:34:17 +00001519 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001520}
Mike Stump9b39c512009-12-09 22:59:31 +00001521
1522llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001523 if (TerminateHandler)
1524 return TerminateHandler;
1525
John McCallf1549f62010-07-06 01:34:17 +00001526 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001527
John McCallf1549f62010-07-06 01:34:17 +00001528 // Set up the terminate handler. This block is inserted at the very
1529 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001530 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001531 Builder.SetInsertPoint(TerminateHandler);
1532 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001533 TerminateCall->setDoesNotReturn();
1534 TerminateCall->setDoesNotThrow();
1535 Builder.CreateUnreachable();
1536
John McCall3d3ec1c2010-04-21 10:05:39 +00001537 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001538 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001539
Mike Stump9b39c512009-12-09 22:59:31 +00001540 return TerminateHandler;
1541}
John McCallf1549f62010-07-06 01:34:17 +00001542
John McCallff8e1152010-07-23 21:56:41 +00001543CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1544 if (RethrowBlock.isValid()) return RethrowBlock;
1545
1546 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1547
1548 // We emit a jump to a notional label at the outermost unwind state.
1549 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1550 Builder.SetInsertPoint(Unwind);
1551
1552 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1553
1554 // This can always be a call because we necessarily didn't find
1555 // anything on the EH stack which needs our help.
1556 llvm::Constant *RethrowFn;
1557 if (const char *RethrowName = Personality.getCatchallRethrowFnName())
1558 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1559 else
1560 RethrowFn = getUnwindResumeOrRethrowFn();
1561
1562 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1563 ->setDoesNotReturn();
1564 Builder.CreateUnreachable();
1565
1566 Builder.restoreIP(SavedIP);
1567
1568 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1569 return RethrowBlock;
1570}
1571
John McCall1f0fca52010-07-21 07:22:38 +00001572EHScopeStack::Cleanup::~Cleanup() {
1573 llvm_unreachable("Cleanup is indestructable");
John McCall3e29f962010-07-13 23:19:49 +00001574}