blob: 99105e165f3a93ebe987072ef61d653e4339cba4 [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 McCallda65ea82010-07-13 20:32:21 +000076 bool IsNormalCleanup = Kind != EHCleanup;
77 bool IsEHCleanup = Kind != NormalCleanup;
John McCall1f0fca52010-07-21 07:22:38 +000078 EHCleanupScope *Scope =
79 new (Buffer) EHCleanupScope(IsNormalCleanup,
80 IsEHCleanup,
81 Size,
82 BranchFixups.size(),
83 InnermostNormalCleanup,
84 InnermostEHCleanup);
John McCallda65ea82010-07-13 20:32:21 +000085 if (IsNormalCleanup)
86 InnermostNormalCleanup = stable_begin();
87 if (IsEHCleanup)
88 InnermostEHCleanup = stable_begin();
89
90 return Scope->getCleanupBuffer();
91}
92
John McCallf1549f62010-07-06 01:34:17 +000093void EHScopeStack::popCleanup() {
94 assert(!empty() && "popping exception stack when not empty");
95
John McCall1f0fca52010-07-21 07:22:38 +000096 assert(isa<EHCleanupScope>(*begin()));
97 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
John McCall7495f222010-07-21 07:11:21 +000098 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
99 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
100 StartOfData += Cleanup.getAllocatedSize();
John McCallf1549f62010-07-06 01:34:17 +0000101
John McCallff8e1152010-07-23 21:56:41 +0000102 if (empty()) NextEHDestIndex = FirstEHDestIndex;
103
104 // Destroy the cleanup.
105 Cleanup.~EHCleanupScope();
106
John McCallf1549f62010-07-06 01:34:17 +0000107 // Check whether we can shrink the branch-fixups stack.
108 if (!BranchFixups.empty()) {
109 // If we no longer have any normal cleanups, all the fixups are
110 // complete.
111 if (!hasNormalCleanups())
112 BranchFixups.clear();
113
114 // Otherwise we can still trim out unnecessary nulls.
115 else
116 popNullFixups();
117 }
118}
119
120EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
121 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
122 CatchDepth++;
123 return new (Buffer) EHFilterScope(NumFilters);
124}
125
126void EHScopeStack::popFilter() {
127 assert(!empty() && "popping exception stack when not empty");
128
129 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
130 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
131
John McCallff8e1152010-07-23 21:56:41 +0000132 if (empty()) NextEHDestIndex = FirstEHDestIndex;
133
John McCallf1549f62010-07-06 01:34:17 +0000134 assert(CatchDepth > 0 && "mismatched filter push/pop");
135 CatchDepth--;
136}
137
138EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
139 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
140 CatchDepth++;
John McCallff8e1152010-07-23 21:56:41 +0000141 EHCatchScope *Scope = new (Buffer) EHCatchScope(NumHandlers);
142 for (unsigned I = 0; I != NumHandlers; ++I)
143 Scope->getHandlers()[I].Index = getNextEHDestIndex();
144 return Scope;
John McCallf1549f62010-07-06 01:34:17 +0000145}
146
147void EHScopeStack::pushTerminate() {
148 char *Buffer = allocate(EHTerminateScope::getSize());
149 CatchDepth++;
John McCallff8e1152010-07-23 21:56:41 +0000150 new (Buffer) EHTerminateScope(getNextEHDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000151}
152
153/// Remove any 'null' fixups on the stack. However, we can't pop more
154/// fixups than the fixup depth on the innermost normal cleanup, or
155/// else fixups that we try to add to that cleanup will end up in the
156/// wrong place. We *could* try to shrink fixup depths, but that's
157/// actually a lot of work for little benefit.
158void EHScopeStack::popNullFixups() {
159 // We expect this to only be called when there's still an innermost
160 // normal cleanup; otherwise there really shouldn't be any fixups.
161 assert(hasNormalCleanups());
162
163 EHScopeStack::iterator it = find(InnermostNormalCleanup);
John McCall1f0fca52010-07-21 07:22:38 +0000164 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
John McCallf1549f62010-07-06 01:34:17 +0000165 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
166
167 while (BranchFixups.size() > MinSize &&
168 BranchFixups.back().Destination == 0)
169 BranchFixups.pop_back();
170}
171
Anders Carlssond3379292009-10-30 02:27:02 +0000172static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
173 // void *__cxa_allocate_exception(size_t thrown_size);
174 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
175 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000176
177 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +0000178 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
179 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000180
Anders Carlssond3379292009-10-30 02:27:02 +0000181 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
182}
183
Mike Stump99533832009-12-02 07:41:41 +0000184static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
185 // void __cxa_free_exception(void *thrown_exception);
186 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
187 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000188
189 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000190 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
191 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000192
Mike Stump99533832009-12-02 07:41:41 +0000193 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
194}
195
Anders Carlssond3379292009-10-30 02:27:02 +0000196static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +0000197 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +0000198 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +0000199
200 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
201 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000202
203 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000204 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
205 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000206
Anders Carlssond3379292009-10-30 02:27:02 +0000207 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
208}
209
Mike Stumpb4eea692009-11-20 00:56:31 +0000210static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000211 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +0000212
Mike Stump8755ec32009-12-10 00:06:18 +0000213 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000214 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000215
Mike Stumpb4eea692009-11-20 00:56:31 +0000216 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
217}
218
John McCallf1549f62010-07-06 01:34:17 +0000219static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
220 // void *__cxa_get_exception_ptr(void*);
221 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
222 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
223
224 const llvm::FunctionType *FTy =
225 llvm::FunctionType::get(Int8PtrTy, Args, false);
226
227 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
228}
229
Mike Stump2bf701e2009-11-20 23:44:51 +0000230static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +0000231 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +0000232
233 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
234 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000235
236 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +0000237 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000238
Mike Stump2bf701e2009-11-20 23:44:51 +0000239 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
240}
241
242static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000243 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000244
Mike Stump8755ec32009-12-10 00:06:18 +0000245 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000246 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000247
Mike Stump2bf701e2009-11-20 23:44:51 +0000248 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
249}
250
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000251static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
252 // void __cxa_call_unexepcted(void *thrown_exception);
253
254 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
255 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000256
257 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000258 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
259 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000260
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000261 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
262}
263
Douglas Gregor86a3a032010-05-16 01:24:12 +0000264llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
265 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000266 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000267
268 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000269 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000270 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000271
Douglas Gregor86a3a032010-05-16 01:24:12 +0000272 if (CGM.getLangOptions().SjLjExceptions)
273 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
274 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000275}
276
Mike Stump99533832009-12-02 07:41:41 +0000277static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
278 // void __terminate();
279
Mike Stump8755ec32009-12-10 00:06:18 +0000280 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000281 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000282
David Chisnall79a9ad82010-05-17 13:49:20 +0000283 return CGF.CGM.CreateRuntimeFunction(FTy,
284 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
285}
286
John McCall8262b6a2010-07-17 00:43:08 +0000287static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
288 const char *Name) {
289 const llvm::Type *Int8PtrTy =
290 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
291 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
292
293 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
294 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
295
296 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000297}
298
John McCall8262b6a2010-07-17 00:43:08 +0000299const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
300const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
301const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
302const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
303const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
304 "objc_exception_throw");
305
306static const EHPersonality &getCPersonality(const LangOptions &L) {
307 return EHPersonality::GNU_C;
308}
309
310static const EHPersonality &getObjCPersonality(const LangOptions &L) {
311 if (L.NeXTRuntime) {
312 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
313 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000314 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000315 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000316 }
317}
318
John McCall8262b6a2010-07-17 00:43:08 +0000319static const EHPersonality &getCXXPersonality(const LangOptions &L) {
320 if (L.SjLjExceptions)
321 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000322 else
John McCall8262b6a2010-07-17 00:43:08 +0000323 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000324}
325
326/// Determines the personality function to use when both C++
327/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000328static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000329 // The ObjC personality defers to the C++ personality for non-ObjC
330 // handlers. Unlike the C++ case, we use the same personality
331 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000332 if (L.NeXTRuntime) {
333 if (L.ObjCNonFragileABI)
334 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000335
336 // In the fragile ABI, just use C++ exception handling and hope
337 // they're not doing crazy exception mixing.
338 else
John McCall8262b6a2010-07-17 00:43:08 +0000339 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000340 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000341
John McCall8262b6a2010-07-17 00:43:08 +0000342 // The GNU runtime's personality function inherently doesn't support
343 // mixed EH. Use the C++ personality just to avoid returning null.
344 return getCXXPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000345}
346
John McCall8262b6a2010-07-17 00:43:08 +0000347const EHPersonality &EHPersonality::get(const LangOptions &L) {
348 if (L.CPlusPlus && L.ObjC1)
349 return getObjCXXPersonality(L);
350 else if (L.CPlusPlus)
351 return getCXXPersonality(L);
352 else if (L.ObjC1)
353 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000354 else
John McCall8262b6a2010-07-17 00:43:08 +0000355 return getCPersonality(L);
356}
John McCallf1549f62010-07-06 01:34:17 +0000357
John McCall8262b6a2010-07-17 00:43:08 +0000358static llvm::Constant *getPersonalityFn(CodeGenFunction &CGF,
359 const EHPersonality &Personality) {
360 const char *Name = Personality.getPersonalityFnName();
361
362 llvm::Constant *Fn =
John McCallf1549f62010-07-06 01:34:17 +0000363 CGF.CGM.CreateRuntimeFunction(llvm::FunctionType::get(
364 llvm::Type::getInt32Ty(
365 CGF.CGM.getLLVMContext()),
366 true),
367 Name);
John McCall8262b6a2010-07-17 00:43:08 +0000368 return llvm::ConstantExpr::getBitCast(Fn, CGF.CGM.PtrToInt8Ty);
John McCallf1549f62010-07-06 01:34:17 +0000369}
370
371/// Returns the value to inject into a selector to indicate the
372/// presence of a catch-all.
373static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
374 // Possibly we should use @llvm.eh.catch.all.value here.
375 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
376}
377
378/// Returns the value to inject into a selector to indicate the
379/// presence of a cleanup.
380static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
381 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000382}
383
John McCall09faeab2010-07-13 21:17:51 +0000384namespace {
385 /// A cleanup to free the exception object if its initialization
386 /// throws.
John McCall1f0fca52010-07-21 07:22:38 +0000387 struct FreeExceptionCleanup : EHScopeStack::Cleanup {
John McCall09faeab2010-07-13 21:17:51 +0000388 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
389 llvm::Value *ExnLocVar)
390 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
391
392 llvm::Value *ShouldFreeVar;
393 llvm::Value *ExnLocVar;
394
395 void Emit(CodeGenFunction &CGF, bool IsForEH) {
396 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
397 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
398
399 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
400 "should-free-exnobj");
401 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
402 CGF.EmitBlock(FreeBB);
403 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
404 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
405 ->setDoesNotThrow();
406 CGF.EmitBlock(DoneBB);
407 }
408 };
409}
410
John McCallac418162010-04-22 01:10:34 +0000411// Emits an exception expression into the given location. This
412// differs from EmitAnyExprToMem only in that, if a final copy-ctor
413// call is required, an exception within that copy ctor causes
414// std::terminate to be invoked.
415static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
416 llvm::Value *ExnLoc) {
417 // We want to release the allocated exception object if this
418 // expression throws. We do this by pushing an EH-only cleanup
419 // block which, furthermore, deactivates itself after the expression
420 // is complete.
421 llvm::AllocaInst *ShouldFreeVar =
422 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
423 "should-free-exnobj.var");
424 CGF.InitTempAlloca(ShouldFreeVar,
425 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump0f590be2009-12-01 03:41:18 +0000426
John McCallac418162010-04-22 01:10:34 +0000427 // A variable holding the exception pointer. This is necessary
428 // because the throw expression does not necessarily dominate the
429 // cleanup, for example if it appears in a conditional expression.
430 llvm::AllocaInst *ExnLocVar =
431 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump8755ec32009-12-10 00:06:18 +0000432
John McCallf1549f62010-07-06 01:34:17 +0000433 // Make sure the exception object is cleaned up if there's an
434 // exception during initialization.
John McCall09faeab2010-07-13 21:17:51 +0000435 // FIXME: stmt expressions might require this to be a normal
436 // cleanup, too.
John McCall1f0fca52010-07-21 07:22:38 +0000437 CGF.EHStack.pushCleanup<FreeExceptionCleanup>(EHCleanup,
438 ShouldFreeVar,
439 ExnLocVar);
John McCallf1549f62010-07-06 01:34:17 +0000440 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000441
442 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
443 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
444 ShouldFreeVar);
445
446 // __cxa_allocate_exception returns a void*; we need to cast this
447 // to the appropriate type for the object.
448 const llvm::Type *Ty = CGF.ConvertType(E->getType())->getPointerTo();
449 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
450
451 // FIXME: this isn't quite right! If there's a final unelided call
452 // to a copy constructor, then according to [except.terminate]p1 we
453 // must call std::terminate() if that constructor throws, because
454 // technically that copy occurs after the exception expression is
455 // evaluated but before the exception is caught. But the best way
456 // to handle that is to teach EmitAggExpr to do the final copy
457 // differently if it can't be elided.
458 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false);
459
460 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
461 ShouldFreeVar);
462
John McCallf1549f62010-07-06 01:34:17 +0000463 // Technically, the exception object is like a temporary; it has to
464 // be cleaned up when its full-expression is complete.
465 // Unfortunately, the AST represents full-expressions by creating a
466 // CXXExprWithTemporaries, which it only does when there are actually
467 // temporaries.
468 //
469 // If any cleanups have been added since we pushed ours, they must
470 // be from temporaries; this will get popped at the same time.
471 // Otherwise we need to pop ours off. FIXME: this is very brittle.
472 if (Cleanup == CGF.EHStack.stable_begin())
473 CGF.PopCleanupBlock();
Mike Stump0f590be2009-12-01 03:41:18 +0000474}
475
John McCallf1549f62010-07-06 01:34:17 +0000476llvm::Value *CodeGenFunction::getExceptionSlot() {
477 if (!ExceptionSlot) {
478 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
479 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000480 }
John McCallf1549f62010-07-06 01:34:17 +0000481 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000482}
483
Anders Carlsson756b5c42009-10-30 01:42:31 +0000484void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000485 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000486 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000487 Builder.CreateInvoke(getReThrowFn(*this),
488 getUnreachableBlock(),
489 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000490 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000491 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000492 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000493 Builder.CreateUnreachable();
494 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000495
496 // Clear the insertion point to indicate we are in unreachable code.
497 Builder.ClearInsertionPoint();
Anders Carlssond3379292009-10-30 02:27:02 +0000498 return;
499 }
Mike Stump8755ec32009-12-10 00:06:18 +0000500
Anders Carlssond3379292009-10-30 02:27:02 +0000501 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000502
Anders Carlssond3379292009-10-30 02:27:02 +0000503 // Now allocate the exception object.
504 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000505 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000506
Anders Carlssond3379292009-10-30 02:27:02 +0000507 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000508 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000509 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000510 llvm::ConstantInt::get(SizeTy, TypeSize),
511 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000512 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000513
John McCallac418162010-04-22 01:10:34 +0000514 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000515
Anders Carlssond3379292009-10-30 02:27:02 +0000516 // Now throw the exception.
517 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall9dffe6f2010-04-30 01:15:21 +0000518 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
John McCallac418162010-04-22 01:10:34 +0000519
520 // The address of the destructor. If the exception type has a
521 // trivial destructor (or isn't a record), we just pass null.
522 llvm::Constant *Dtor = 0;
523 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
524 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
525 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000526 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000527 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
528 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
529 }
530 }
531 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000532
Mike Stump0a3816e2009-12-04 01:51:45 +0000533 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000534 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000535 Builder.CreateInvoke3(getThrowFn(*this),
536 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000537 ExceptionPtr, TypeInfo, Dtor);
538 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000539 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000540 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000541 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
542 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000543 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000544 }
Mike Stump8755ec32009-12-10 00:06:18 +0000545
Anders Carlssond3379292009-10-30 02:27:02 +0000546 // Clear the insertion point to indicate we are in unreachable code.
547 Builder.ClearInsertionPoint();
Mike Stumpc2ab4862009-12-07 20:12:14 +0000548
549 // FIXME: For now, emit a dummy basic block because expr emitters in generally
550 // are not ready to handle emitting expressions at unreachable points.
551 EnsureInsertPoint();
Anders Carlsson756b5c42009-10-30 01:42:31 +0000552}
Mike Stump2bf701e2009-11-20 23:44:51 +0000553
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000554void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000555 if (!Exceptions)
556 return;
557
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000558 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
559 if (FD == 0)
560 return;
561 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
562 if (Proto == 0)
563 return;
564
565 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
566
567 if (!Proto->hasExceptionSpec())
568 return;
569
John McCallf1549f62010-07-06 01:34:17 +0000570 unsigned NumExceptions = Proto->getNumExceptions();
571 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000572
John McCallf1549f62010-07-06 01:34:17 +0000573 for (unsigned I = 0; I != NumExceptions; ++I) {
574 QualType Ty = Proto->getExceptionType(I);
575 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
John McCall9dffe6f2010-04-30 01:15:21 +0000576 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
John McCallf1549f62010-07-06 01:34:17 +0000577 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000578 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000579}
580
581void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000582 if (!Exceptions)
583 return;
584
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000585 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
586 if (FD == 0)
587 return;
588 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
589 if (Proto == 0)
590 return;
591
592 if (!Proto->hasExceptionSpec())
593 return;
594
John McCallf1549f62010-07-06 01:34:17 +0000595 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000596}
597
Mike Stump2bf701e2009-11-20 23:44:51 +0000598void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000599 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000600 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000601 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000602}
603
John McCall59a70002010-07-07 06:56:46 +0000604void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000605 unsigned NumHandlers = S.getNumHandlers();
606 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000607
John McCallf1549f62010-07-06 01:34:17 +0000608 for (unsigned I = 0; I != NumHandlers; ++I) {
609 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000610
John McCallf1549f62010-07-06 01:34:17 +0000611 llvm::BasicBlock *Handler = createBasicBlock("catch");
612 if (C->getExceptionDecl()) {
613 // FIXME: Dropping the reference type on the type into makes it
614 // impossible to correctly implement catch-by-reference
615 // semantics for pointers. Unfortunately, this is what all
616 // existing compilers do, and it's not clear that the standard
617 // personality routine is capable of doing this right. See C++ DR 388:
618 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
619 QualType CaughtType = C->getCaughtType();
620 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000621
622 llvm::Value *TypeInfo = 0;
623 if (CaughtType->isObjCObjectPointerType())
624 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
625 else
626 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, true);
John McCallf1549f62010-07-06 01:34:17 +0000627 CatchScope->setHandler(I, TypeInfo, Handler);
628 } else {
629 // No exception decl indicates '...', a catch-all.
630 CatchScope->setCatchAllHandler(I, Handler);
631 }
632 }
John McCallf1549f62010-07-06 01:34:17 +0000633}
634
635/// Check whether this is a non-EH scope, i.e. a scope which doesn't
636/// affect exception handling. Currently, the only non-EH scopes are
637/// normal-only cleanup scopes.
638static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000639 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000640 case EHScope::Cleanup:
641 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000642 case EHScope::Filter:
643 case EHScope::Catch:
644 case EHScope::Terminate:
645 return false;
646 }
647
648 // Suppress warning.
649 return false;
John McCallf1549f62010-07-06 01:34:17 +0000650}
651
652llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
653 assert(EHStack.requiresLandingPad());
654 assert(!EHStack.empty());
655
John McCallda65ea82010-07-13 20:32:21 +0000656 if (!Exceptions)
657 return 0;
658
John McCallf1549f62010-07-06 01:34:17 +0000659 // Check the innermost scope for a cached landing pad. If this is
660 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
661 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
662 if (LP) return LP;
663
664 // Build the landing pad for this scope.
665 LP = EmitLandingPad();
666 assert(LP);
667
668 // Cache the landing pad on the innermost scope. If this is a
669 // non-EH scope, cache the landing pad on the enclosing scope, too.
670 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
671 ir->setCachedLandingPad(LP);
672 if (!isNonEHScope(*ir)) break;
673 }
674
675 return LP;
676}
677
678llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
679 assert(EHStack.requiresLandingPad());
680
681 // This function contains a hack to work around a design flaw in
682 // LLVM's EH IR which breaks semantics after inlining. This same
683 // hack is implemented in llvm-gcc.
684 //
685 // The LLVM EH abstraction is basically a thin veneer over the
686 // traditional GCC zero-cost design: for each range of instructions
687 // in the function, there is (at most) one "landing pad" with an
688 // associated chain of EH actions. A language-specific personality
689 // function interprets this chain of actions and (1) decides whether
690 // or not to resume execution at the landing pad and (2) if so,
691 // provides an integer indicating why it's stopping. In LLVM IR,
692 // the association of a landing pad with a range of instructions is
693 // achieved via an invoke instruction, the chain of actions becomes
694 // the arguments to the @llvm.eh.selector call, and the selector
695 // call returns the integer indicator. Other than the required
696 // presence of two intrinsic function calls in the landing pad,
697 // the IR exactly describes the layout of the output code.
698 //
699 // A principal advantage of this design is that it is completely
700 // language-agnostic; in theory, the LLVM optimizers can treat
701 // landing pads neutrally, and targets need only know how to lower
702 // the intrinsics to have a functioning exceptions system (assuming
703 // that platform exceptions follow something approximately like the
704 // GCC design). Unfortunately, landing pads cannot be combined in a
705 // language-agnostic way: given selectors A and B, there is no way
706 // to make a single landing pad which faithfully represents the
707 // semantics of propagating an exception first through A, then
708 // through B, without knowing how the personality will interpret the
709 // (lowered form of the) selectors. This means that inlining has no
710 // choice but to crudely chain invokes (i.e., to ignore invokes in
711 // the inlined function, but to turn all unwindable calls into
712 // invokes), which is only semantically valid if every unwind stops
713 // at every landing pad.
714 //
715 // Therefore, the invoke-inline hack is to guarantee that every
716 // landing pad has a catch-all.
717 const bool UseInvokeInlineHack = true;
718
719 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
720 assert(ir != EHStack.end() &&
721 "stack requiring landing pad is nothing but non-EH scopes?");
722
723 // If this is a terminate scope, just use the singleton terminate
724 // landing pad.
725 if (isa<EHTerminateScope>(*ir))
726 return getTerminateLandingPad();
727
728 // If this isn't an EH scope, iterate; otherwise break out.
729 if (!isNonEHScope(*ir)) break;
730 ++ir;
731
732 // We haven't checked this scope for a cached landing pad yet.
733 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
734 return LP;
735 }
736
737 // Save the current IR generation state.
738 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
739
John McCall8262b6a2010-07-17 00:43:08 +0000740 const EHPersonality &Personality =
741 EHPersonality::get(CGF.CGM.getLangOptions());
742
John McCallf1549f62010-07-06 01:34:17 +0000743 // Create and configure the landing pad.
744 llvm::BasicBlock *LP = createBasicBlock("lpad");
745 EmitBlock(LP);
746
747 // Save the exception pointer. It's safe to use a single exception
748 // pointer per function because EH cleanups can never have nested
749 // try/catches.
750 llvm::CallInst *Exn =
751 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
752 Exn->setDoesNotThrow();
753 Builder.CreateStore(Exn, getExceptionSlot());
754
755 // Build the selector arguments.
756 llvm::SmallVector<llvm::Value*, 8> EHSelector;
757 EHSelector.push_back(Exn);
John McCall8262b6a2010-07-17 00:43:08 +0000758 EHSelector.push_back(getPersonalityFn(*this, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000759
760 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000761 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
762 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000763 bool HasEHCleanup = false;
764 bool HasEHFilter = false;
765 llvm::SmallVector<llvm::Value*, 8> EHFilters;
766 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
767 I != E; ++I) {
768
769 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000770 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000771 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000772 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000773 // We otherwise don't care about cleanups.
774 continue;
775
John McCallf1549f62010-07-06 01:34:17 +0000776 case EHScope::Filter: {
777 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000778 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000779
780 // Filter scopes get added to the selector in wierd ways.
781 EHFilterScope &Filter = cast<EHFilterScope>(*I);
782 HasEHFilter = true;
783
784 // Add all the filter values which we aren't already explicitly
785 // catching.
786 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
787 llvm::Value *FV = Filter.getFilter(I);
788 if (!EHHandlers.count(FV))
789 EHFilters.push_back(FV);
790 }
791 goto done;
792 }
793
794 case EHScope::Terminate:
795 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000796 assert(!CatchAll.isValid());
797 CatchAll = UnwindDest(getTerminateHandler(),
798 EHStack.getEnclosingEHCleanup(I),
799 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000800 goto done;
801
802 case EHScope::Catch:
803 break;
804 }
805
806 EHCatchScope &Catch = cast<EHCatchScope>(*I);
807 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
808 EHCatchScope::Handler Handler = Catch.getHandler(HI);
809
810 // Catch-all. We should only have one of these per catch.
811 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000812 assert(!CatchAll.isValid());
813 CatchAll = UnwindDest(Handler.Block,
814 EHStack.getEnclosingEHCleanup(I),
815 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000816 continue;
817 }
818
819 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000820 UnwindDest &Dest = EHHandlers[Handler.Type];
821 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000822
823 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000824 Dest = UnwindDest(Handler.Block,
825 EHStack.getEnclosingEHCleanup(I),
826 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000827 }
828
829 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000830 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000831 }
832
833 done:
834 unsigned LastToEmitInLoop = EHSelector.size();
835
836 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000837 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000838 EHSelector.push_back(getCatchAllValue(CGF));
839
840 // If we have an EH filter, we need to add those handlers in the
841 // right place in the selector, which is to say, at the end.
842 } else if (HasEHFilter) {
843 // Create a filter expression: an integer constant saying how many
844 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
845 // followed by the filter types. The personality routine only
846 // lands here if the filter doesn't match.
847 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
848 EHFilters.size() + 1));
849 EHSelector.append(EHFilters.begin(), EHFilters.end());
850
851 // Also check whether we need a cleanup.
852 if (UseInvokeInlineHack || HasEHCleanup)
853 EHSelector.push_back(UseInvokeInlineHack
854 ? getCatchAllValue(CGF)
855 : getCleanupValue(CGF));
856
857 // Otherwise, signal that we at least have cleanups.
858 } else if (UseInvokeInlineHack || HasEHCleanup) {
859 EHSelector.push_back(UseInvokeInlineHack
860 ? getCatchAllValue(CGF)
861 : getCleanupValue(CGF));
862 } else {
863 assert(LastToEmitInLoop > 2);
864 LastToEmitInLoop--;
865 }
866
867 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
868
869 // Tell the backend how to generate the landing pad.
870 llvm::CallInst *Selection =
871 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
872 EHSelector.begin(), EHSelector.end(), "eh.selector");
873 Selection->setDoesNotThrow();
874
875 // Select the right handler.
876 llvm::Value *llvm_eh_typeid_for =
877 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
878
879 // The results of llvm_eh_typeid_for aren't reliable --- at least
880 // not locally --- so we basically have to do this as an 'if' chain.
881 // We walk through the first N-1 catch clauses, testing and chaining,
882 // and then fall into the final clause (which is either a cleanup, a
883 // filter (possibly with a cleanup), a catch-all, or another catch).
884 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
885 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000886 UnwindDest Dest = EHHandlers[Type];
887 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000888
889 // Figure out where to branch on a match. As a debug code-size
890 // optimization, if the scope depth matches the innermost cleanup,
891 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000892 llvm::BasicBlock *Match = Dest.getBlock();
893 bool MatchNeedsCleanup =
894 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000895 if (MatchNeedsCleanup)
896 Match = createBasicBlock("eh.match");
897
898 llvm::BasicBlock *Next = createBasicBlock("eh.next");
899
900 // Check whether the exception matches.
901 llvm::CallInst *Id
902 = Builder.CreateCall(llvm_eh_typeid_for,
903 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
904 Id->setDoesNotThrow();
905 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
906 Match, Next);
907
908 // Emit match code if necessary.
909 if (MatchNeedsCleanup) {
910 EmitBlock(Match);
911 EmitBranchThroughEHCleanup(Dest);
912 }
913
914 // Continue to the next match.
915 EmitBlock(Next);
916 }
917
918 // Emit the final case in the selector.
919 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000920 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000921 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
922 EmitBranchThroughEHCleanup(CatchAll);
923
924 // ...or an EH filter...
925 } else if (HasEHFilter) {
926 llvm::Value *SavedSelection = Selection;
927
928 // First, unwind out to the outermost scope if necessary.
929 if (EHStack.hasEHCleanups()) {
930 // The end here might not dominate the beginning, so we might need to
931 // save the selector if we need it.
932 llvm::AllocaInst *SelectorVar = 0;
933 if (HasEHCleanup) {
934 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
935 Builder.CreateStore(Selection, SelectorVar);
936 }
937
938 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000939 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
940 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000941 EmitBlock(CleanupContBB);
942
943 if (HasEHCleanup)
944 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
945 }
946
947 // If there was a cleanup, we'll need to actually check whether we
948 // landed here because the filter triggered.
949 if (UseInvokeInlineHack || HasEHCleanup) {
950 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
951 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
952
953 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
954 llvm::Value *FailsFilter =
955 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
956 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
957
958 // The rethrow block is where we land if this was a cleanup.
959 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
960 EmitBlock(RethrowBB);
961 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
962 Builder.CreateLoad(getExceptionSlot()))
963 ->setDoesNotReturn();
964 Builder.CreateUnreachable();
965
966 EmitBlock(UnexpectedBB);
967 }
968
969 // Call __cxa_call_unexpected. This doesn't need to be an invoke
970 // because __cxa_call_unexpected magically filters exceptions
971 // according to the last landing pad the exception was thrown
972 // into. Seriously.
973 Builder.CreateCall(getUnexpectedFn(*this),
974 Builder.CreateLoad(getExceptionSlot()))
975 ->setDoesNotReturn();
976 Builder.CreateUnreachable();
977
978 // ...or a normal catch handler...
979 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
980 llvm::Value *Type = EHSelector.back();
981 EmitBranchThroughEHCleanup(EHHandlers[Type]);
982
983 // ...or a cleanup.
984 } else {
John McCallff8e1152010-07-23 21:56:41 +0000985 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +0000986 }
987
988 // Restore the old IR generation state.
989 Builder.restoreIP(SavedIP);
990
991 return LP;
992}
993
John McCall8e3f8612010-07-13 22:12:14 +0000994namespace {
995 /// A cleanup to call __cxa_end_catch. In many cases, the caught
996 /// exception type lets us state definitively that the thrown exception
997 /// type does not have a destructor. In particular:
998 /// - Catch-alls tell us nothing, so we have to conservatively
999 /// assume that the thrown exception might have a destructor.
1000 /// - Catches by reference behave according to their base types.
1001 /// - Catches of non-record types will only trigger for exceptions
1002 /// of non-record types, which never have destructors.
1003 /// - Catches of record types can trigger for arbitrary subclasses
1004 /// of the caught type, so we have to assume the actual thrown
1005 /// exception type might have a throwing destructor, even if the
1006 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +00001007 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +00001008 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1009 bool MightThrow;
1010
1011 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1012 if (!MightThrow) {
1013 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1014 return;
1015 }
1016
1017 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1018 }
1019 };
1020}
1021
John McCallf1549f62010-07-06 01:34:17 +00001022/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1023/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001024///
1025/// \param EndMightThrow - true if __cxa_end_catch might throw
1026static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1027 llvm::Value *Exn,
1028 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +00001029 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1030 Call->setDoesNotThrow();
1031
John McCall1f0fca52010-07-21 07:22:38 +00001032 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +00001033
1034 return Call;
1035}
1036
1037/// A "special initializer" callback for initializing a catch
1038/// parameter during catch initialization.
1039static void InitCatchParam(CodeGenFunction &CGF,
1040 const VarDecl &CatchParam,
1041 llvm::Value *ParamAddr) {
1042 // Load the exception from where the landing pad saved it.
1043 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1044
1045 CanQualType CatchType =
1046 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1047 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1048
1049 // If we're catching by reference, we can just cast the object
1050 // pointer to the appropriate pointer.
1051 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +00001052 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1053 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +00001054
John McCallf1549f62010-07-06 01:34:17 +00001055 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +00001056 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +00001057
1058 // We have no way to tell the personality function that we're
1059 // catching by reference, so if we're catching a pointer,
1060 // __cxa_begin_catch will actually return that pointer by value.
1061 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1062 QualType PointeeType = PT->getPointeeType();
1063
1064 // When catching by reference, generally we should just ignore
1065 // this by-value pointer and use the exception object instead.
1066 if (!PointeeType->isRecordType()) {
1067
1068 // Exn points to the struct _Unwind_Exception header, which
1069 // we have to skip past in order to reach the exception data.
1070 unsigned HeaderSize =
1071 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1072 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1073
1074 // However, if we're catching a pointer-to-record type that won't
1075 // work, because the personality function might have adjusted
1076 // the pointer. There's actually no way for us to fully satisfy
1077 // the language/ABI contract here: we can't use Exn because it
1078 // might have the wrong adjustment, but we can't use the by-value
1079 // pointer because it's off by a level of abstraction.
1080 //
1081 // The current solution is to dump the adjusted pointer into an
1082 // alloca, which breaks language semantics (because changing the
1083 // pointer doesn't change the exception) but at least works.
1084 // The better solution would be to filter out non-exact matches
1085 // and rethrow them, but this is tricky because the rethrow
1086 // really needs to be catchable by other sites at this landing
1087 // pad. The best solution is to fix the personality function.
1088 } else {
1089 // Pull the pointer for the reference type off.
1090 const llvm::Type *PtrTy =
1091 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1092
1093 // Create the temporary and write the adjusted pointer into it.
1094 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1095 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1096 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1097
1098 // Bind the reference to the temporary.
1099 AdjustedExn = ExnPtrTmp;
1100 }
1101 }
1102
John McCallf1549f62010-07-06 01:34:17 +00001103 llvm::Value *ExnCast =
1104 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1105 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1106 return;
1107 }
1108
1109 // Non-aggregates (plus complexes).
1110 bool IsComplex = false;
1111 if (!CGF.hasAggregateLLVMType(CatchType) ||
1112 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001113 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001114
1115 // If the catch type is a pointer type, __cxa_begin_catch returns
1116 // the pointer by value.
1117 if (CatchType->hasPointerRepresentation()) {
1118 llvm::Value *CastExn =
1119 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1120 CGF.Builder.CreateStore(CastExn, ParamAddr);
1121 return;
1122 }
1123
1124 // Otherwise, it returns a pointer into the exception object.
1125
1126 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1127 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1128
1129 if (IsComplex) {
1130 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1131 ParamAddr, /*volatile*/ false);
1132 } else {
1133 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1134 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, CatchType);
1135 }
1136 return;
1137 }
1138
1139 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1140 // initializer expression.
1141
1142 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1143 assert(RD && "aggregate catch type was not a record!");
1144
1145 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1146
1147 if (RD->hasTrivialCopyConstructor()) {
John McCall8e3f8612010-07-13 22:12:14 +00001148 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001149 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1150 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1151 return;
1152 }
1153
1154 // We have to call __cxa_get_exception_ptr to get the adjusted
1155 // pointer before copying.
1156 llvm::CallInst *AdjustedExn =
1157 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1158 AdjustedExn->setDoesNotThrow();
1159 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1160
1161 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1162 assert(CD && "record has no copy constructor!");
1163 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1164
1165 CallArgList CallArgs;
1166 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1167 CD->getThisType(CGF.getContext())));
1168 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1169 CD->getParamDecl(0)->getType()));
1170
1171 const FunctionProtoType *FPT
1172 = CD->getType()->getAs<FunctionProtoType>();
1173
1174 // Call the copy ctor in a terminate scope.
1175 CGF.EHStack.pushTerminate();
1176 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1177 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1178 CGF.EHStack.popTerminate();
1179
1180 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001181 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001182}
1183
1184/// Begins a catch statement by initializing the catch variable and
1185/// calling __cxa_begin_catch.
1186static void BeginCatch(CodeGenFunction &CGF,
1187 const CXXCatchStmt *S) {
1188 // We have to be very careful with the ordering of cleanups here:
1189 // C++ [except.throw]p4:
1190 // The destruction [of the exception temporary] occurs
1191 // immediately after the destruction of the object declared in
1192 // the exception-declaration in the handler.
1193 //
1194 // So the precise ordering is:
1195 // 1. Construct catch variable.
1196 // 2. __cxa_begin_catch
1197 // 3. Enter __cxa_end_catch cleanup
1198 // 4. Enter dtor cleanup
1199 //
1200 // We do this by initializing the exception variable with a
1201 // "special initializer", InitCatchParam. Delegation sequence:
1202 // - ExitCXXTryStmt opens a RunCleanupsScope
1203 // - EmitLocalBlockVarDecl creates the variable and debug info
1204 // - InitCatchParam initializes the variable from the exception
1205 // - CallBeginCatch calls __cxa_begin_catch
1206 // - CallBeginCatch enters the __cxa_end_catch cleanup
1207 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1208 // - EmitCXXTryStmt emits the code for the catch body
1209 // - EmitCXXTryStmt close the RunCleanupsScope
1210
1211 VarDecl *CatchParam = S->getExceptionDecl();
1212 if (!CatchParam) {
1213 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001214 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001215 return;
1216 }
1217
1218 // Emit the local.
1219 CGF.EmitLocalBlockVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001220}
1221
John McCallfcd5c0c2010-07-13 22:24:23 +00001222namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001223 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001224 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1225 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1226 }
1227 };
1228}
1229
John McCall59a70002010-07-07 06:56:46 +00001230void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001231 unsigned NumHandlers = S.getNumHandlers();
1232 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1233 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001234
John McCallf1549f62010-07-06 01:34:17 +00001235 // Copy the handler blocks off before we pop the EH stack. Emitting
1236 // the handlers might scribble on this memory.
1237 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1238 memcpy(Handlers.data(), CatchScope.begin(),
1239 NumHandlers * sizeof(EHCatchScope::Handler));
1240 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001241
John McCallf1549f62010-07-06 01:34:17 +00001242 // The fall-through block.
1243 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001244
John McCallf1549f62010-07-06 01:34:17 +00001245 // We just emitted the body of the try; jump to the continue block.
1246 if (HaveInsertPoint())
1247 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001248
John McCall59a70002010-07-07 06:56:46 +00001249 // Determine if we need an implicit rethrow for all these catch handlers.
1250 bool ImplicitRethrow = false;
1251 if (IsFnTryBlock)
1252 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1253 isa<CXXConstructorDecl>(CurCodeDecl);
1254
John McCallf1549f62010-07-06 01:34:17 +00001255 for (unsigned I = 0; I != NumHandlers; ++I) {
1256 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1257 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001258
John McCallf1549f62010-07-06 01:34:17 +00001259 // Catch the exception if this isn't a catch-all.
1260 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001261
John McCallf1549f62010-07-06 01:34:17 +00001262 // Enter a cleanup scope, including the catch variable and the
1263 // end-catch.
1264 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001265
John McCallf1549f62010-07-06 01:34:17 +00001266 // Initialize the catch variable and set up the cleanups.
1267 BeginCatch(*this, C);
1268
John McCall59a70002010-07-07 06:56:46 +00001269 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001270 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1271 // called, and so it is pushed after BeginCatch.
1272 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001273 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001274
John McCallf1549f62010-07-06 01:34:17 +00001275 // Perform the body of the catch.
1276 EmitStmt(C->getHandlerBlock());
1277
1278 // Fall out through the catch cleanups.
1279 CatchScope.ForceCleanup();
1280
1281 // Branch out of the try.
1282 if (HaveInsertPoint())
1283 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001284 }
1285
John McCallf1549f62010-07-06 01:34:17 +00001286 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001287}
Mike Stumpd88ea562009-12-09 03:35:49 +00001288
John McCall55b20fc2010-07-21 00:52:03 +00001289namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001290 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001291 llvm::Value *ForEHVar;
1292 llvm::Value *EndCatchFn;
1293 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1294 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1295
1296 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1297 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1298 llvm::BasicBlock *CleanupContBB =
1299 CGF.createBasicBlock("finally.cleanup.cont");
1300
1301 llvm::Value *ShouldEndCatch =
1302 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1303 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1304 CGF.EmitBlock(EndCatchBB);
1305 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1306 CGF.EmitBlock(CleanupContBB);
1307 }
1308 };
John McCall77199712010-07-21 05:47:49 +00001309
John McCall1f0fca52010-07-21 07:22:38 +00001310 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001311 const Stmt *Body;
1312 llvm::Value *ForEHVar;
1313 llvm::Value *EndCatchFn;
1314 llvm::Value *RethrowFn;
1315 llvm::Value *SavedExnVar;
1316
1317 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1318 llvm::Value *EndCatchFn,
1319 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1320 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1321 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1322
1323 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1324 // Enter a cleanup to call the end-catch function if one was provided.
1325 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001326 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1327 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001328
1329 // Emit the finally block.
1330 CGF.EmitStmt(Body);
1331
1332 // If the end of the finally is reachable, check whether this was
1333 // for EH. If so, rethrow.
1334 if (CGF.HaveInsertPoint()) {
1335 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1336 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1337
1338 llvm::Value *ShouldRethrow =
1339 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1340 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1341
1342 CGF.EmitBlock(RethrowBB);
1343 if (SavedExnVar) {
1344 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1345 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1346 } else {
1347 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1348 }
1349 CGF.Builder.CreateUnreachable();
1350
1351 CGF.EmitBlock(ContBB);
1352 }
1353
1354 // Leave the end-catch cleanup. As an optimization, pretend that
1355 // the fallthrough path was inaccessible; we've dynamically proven
1356 // that we're not in the EH case along that path.
1357 if (EndCatchFn) {
1358 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1359 CGF.PopCleanupBlock();
1360 CGF.Builder.restoreIP(SavedIP);
1361 }
1362
1363 // Now make sure we actually have an insertion point or the
1364 // cleanup gods will hate us.
1365 CGF.EnsureInsertPoint();
1366 }
1367 };
John McCall55b20fc2010-07-21 00:52:03 +00001368}
1369
John McCallf1549f62010-07-06 01:34:17 +00001370/// Enters a finally block for an implementation using zero-cost
1371/// exceptions. This is mostly general, but hard-codes some
1372/// language/ABI-specific behavior in the catch-all sections.
1373CodeGenFunction::FinallyInfo
1374CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1375 llvm::Constant *BeginCatchFn,
1376 llvm::Constant *EndCatchFn,
1377 llvm::Constant *RethrowFn) {
1378 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1379 "begin/end catch functions not paired");
1380 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001381
John McCallf1549f62010-07-06 01:34:17 +00001382 // The rethrow function has one of the following two types:
1383 // void (*)()
1384 // void (*)(void*)
1385 // In the latter case we need to pass it the exception object.
1386 // But we can't use the exception slot because the @finally might
1387 // have a landing pad (which would overwrite the exception slot).
1388 const llvm::FunctionType *RethrowFnTy =
1389 cast<llvm::FunctionType>(
1390 cast<llvm::PointerType>(RethrowFn->getType())
1391 ->getElementType());
1392 llvm::Value *SavedExnVar = 0;
1393 if (RethrowFnTy->getNumParams())
1394 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001395
John McCallf1549f62010-07-06 01:34:17 +00001396 // A finally block is a statement which must be executed on any edge
1397 // out of a given scope. Unlike a cleanup, the finally block may
1398 // contain arbitrary control flow leading out of itself. In
1399 // addition, finally blocks should always be executed, even if there
1400 // are no catch handlers higher on the stack. Therefore, we
1401 // surround the protected scope with a combination of a normal
1402 // cleanup (to catch attempts to break out of the block via normal
1403 // control flow) and an EH catch-all (semantically "outside" any try
1404 // statement to which the finally block might have been attached).
1405 // The finally block itself is generated in the context of a cleanup
1406 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001407
John McCallf1549f62010-07-06 01:34:17 +00001408 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001409
John McCallf1549f62010-07-06 01:34:17 +00001410 // Jump destination for performing the finally block on an exception
1411 // edge. We'll never actually reach this block, so unreachable is
1412 // fine.
1413 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001414
John McCallf1549f62010-07-06 01:34:17 +00001415 // Whether the finally block is being executed for EH purposes.
1416 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1417 "finally.for-eh");
1418 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001419
John McCallf1549f62010-07-06 01:34:17 +00001420 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001421 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1422 ForEHVar, EndCatchFn,
1423 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001424
1425 // Enter a catch-all scope.
1426 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1427 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1428 Builder.SetInsertPoint(CatchAllBB);
1429
1430 // If there's a begin-catch function, call it.
1431 if (BeginCatchFn) {
1432 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1433 ->setDoesNotThrow();
1434 }
1435
1436 // If we need to remember the exception pointer to rethrow later, do so.
1437 if (SavedExnVar) {
1438 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1439 Builder.CreateStore(SavedExn, SavedExnVar);
1440 }
1441
1442 // Tell the finally block that we're in EH.
1443 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1444
1445 // Thread a jump through the finally cleanup.
1446 EmitBranchThroughCleanup(RethrowDest);
1447
1448 Builder.restoreIP(SavedIP);
1449
1450 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1451 CatchScope->setCatchAllHandler(0, CatchAllBB);
1452
1453 return Info;
1454}
1455
1456void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1457 // Leave the finally catch-all.
1458 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1459 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1460 EHStack.popCatch();
1461
1462 // And leave the normal cleanup.
1463 PopCleanupBlock();
1464
1465 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1466 EmitBlock(CatchAllBB, true);
1467
1468 Builder.restoreIP(SavedIP);
1469}
1470
1471llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1472 if (TerminateLandingPad)
1473 return TerminateLandingPad;
1474
1475 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1476
1477 // This will get inserted at the end of the function.
1478 TerminateLandingPad = createBasicBlock("terminate.lpad");
1479 Builder.SetInsertPoint(TerminateLandingPad);
1480
1481 // Tell the backend that this is a landing pad.
1482 llvm::CallInst *Exn =
1483 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1484 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001485
1486 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001487
1488 // Tell the backend what the exception table should be:
1489 // nothing but a catch-all.
John McCall8262b6a2010-07-17 00:43:08 +00001490 llvm::Value *Args[3] = { Exn, getPersonalityFn(*this, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001491 getCatchAllValue(*this) };
1492 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1493 Args, Args+3, "eh.selector")
1494 ->setDoesNotThrow();
1495
1496 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1497 TerminateCall->setDoesNotReturn();
1498 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001499 CGF.Builder.CreateUnreachable();
1500
John McCallf1549f62010-07-06 01:34:17 +00001501 // Restore the saved insertion state.
1502 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001503
John McCallf1549f62010-07-06 01:34:17 +00001504 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001505}
Mike Stump9b39c512009-12-09 22:59:31 +00001506
1507llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001508 if (TerminateHandler)
1509 return TerminateHandler;
1510
John McCallf1549f62010-07-06 01:34:17 +00001511 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001512
John McCallf1549f62010-07-06 01:34:17 +00001513 // Set up the terminate handler. This block is inserted at the very
1514 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001515 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001516 Builder.SetInsertPoint(TerminateHandler);
1517 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001518 TerminateCall->setDoesNotReturn();
1519 TerminateCall->setDoesNotThrow();
1520 Builder.CreateUnreachable();
1521
John McCall3d3ec1c2010-04-21 10:05:39 +00001522 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001523 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001524
Mike Stump9b39c512009-12-09 22:59:31 +00001525 return TerminateHandler;
1526}
John McCallf1549f62010-07-06 01:34:17 +00001527
John McCallff8e1152010-07-23 21:56:41 +00001528CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1529 if (RethrowBlock.isValid()) return RethrowBlock;
1530
1531 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1532
1533 // We emit a jump to a notional label at the outermost unwind state.
1534 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1535 Builder.SetInsertPoint(Unwind);
1536
1537 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1538
1539 // This can always be a call because we necessarily didn't find
1540 // anything on the EH stack which needs our help.
1541 llvm::Constant *RethrowFn;
1542 if (const char *RethrowName = Personality.getCatchallRethrowFnName())
1543 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1544 else
1545 RethrowFn = getUnwindResumeOrRethrowFn();
1546
1547 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1548 ->setDoesNotReturn();
1549 Builder.CreateUnreachable();
1550
1551 Builder.restoreIP(SavedIP);
1552
1553 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1554 return RethrowBlock;
1555}
1556
John McCall1f0fca52010-07-21 07:22:38 +00001557EHScopeStack::Cleanup::~Cleanup() {
1558 llvm_unreachable("Cleanup is indestructable");
John McCall3e29f962010-07-13 23:19:49 +00001559}