blob: cc0a03f8b5f2bf5a7e9571d7a50683d5a402fcef [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
Anders Carlsson756b5c42009-10-30 01:42:31 +000019#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000020#include "CGException.h"
John McCall204b0752010-07-20 22:17:55 +000021#include "TargetInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000022
Anders Carlsson756b5c42009-10-30 01:42:31 +000023using namespace clang;
24using namespace CodeGen;
25
John McCallf1549f62010-07-06 01:34:17 +000026/// Push an entry of the given size onto this protected-scope stack.
27char *EHScopeStack::allocate(size_t Size) {
28 if (!StartOfBuffer) {
29 unsigned Capacity = 1024;
30 while (Capacity < Size) Capacity *= 2;
31 StartOfBuffer = new char[Capacity];
32 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
33 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
34 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
35 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
36
37 unsigned NewCapacity = CurrentCapacity;
38 do {
39 NewCapacity *= 2;
40 } while (NewCapacity < UsedCapacity + Size);
41
42 char *NewStartOfBuffer = new char[NewCapacity];
43 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
44 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
45 memcpy(NewStartOfData, StartOfData, UsedCapacity);
46 delete [] StartOfBuffer;
47 StartOfBuffer = NewStartOfBuffer;
48 EndOfBuffer = NewEndOfBuffer;
49 StartOfData = NewStartOfData;
50 }
51
52 assert(StartOfBuffer + Size <= StartOfData);
53 StartOfData -= Size;
54 return StartOfData;
55}
56
57EHScopeStack::stable_iterator
58EHScopeStack::getEnclosingEHCleanup(iterator it) const {
59 assert(it != end());
60 do {
61 if (isa<EHCleanupScope>(*it)) {
62 if (cast<EHCleanupScope>(*it).isEHCleanup())
63 return stabilize(it);
64 return cast<EHCleanupScope>(*it).getEnclosingEHCleanup();
65 }
John McCallda65ea82010-07-13 20:32:21 +000066 if (isa<EHLazyCleanupScope>(*it)) {
67 if (cast<EHLazyCleanupScope>(*it).isEHCleanup())
68 return stabilize(it);
69 return cast<EHLazyCleanupScope>(*it).getEnclosingEHCleanup();
70 }
John McCallf1549f62010-07-06 01:34:17 +000071 ++it;
72 } while (it != end());
73 return stable_end();
74}
75
76
John McCallda65ea82010-07-13 20:32:21 +000077void *EHScopeStack::pushLazyCleanup(CleanupKind Kind, size_t Size) {
78 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
79 char *Buffer = allocate(EHLazyCleanupScope::getSizeForCleanupSize(Size));
80 bool IsNormalCleanup = Kind != EHCleanup;
81 bool IsEHCleanup = Kind != NormalCleanup;
82 EHLazyCleanupScope *Scope =
83 new (Buffer) EHLazyCleanupScope(IsNormalCleanup,
84 IsEHCleanup,
85 Size,
86 BranchFixups.size(),
87 InnermostNormalCleanup,
88 InnermostEHCleanup);
89 if (IsNormalCleanup)
90 InnermostNormalCleanup = stable_begin();
91 if (IsEHCleanup)
92 InnermostEHCleanup = stable_begin();
93
94 return Scope->getCleanupBuffer();
95}
96
John McCallf1549f62010-07-06 01:34:17 +000097void EHScopeStack::pushCleanup(llvm::BasicBlock *NormalEntry,
98 llvm::BasicBlock *NormalExit,
99 llvm::BasicBlock *EHEntry,
100 llvm::BasicBlock *EHExit) {
101 char *Buffer = allocate(EHCleanupScope::getSize());
102 new (Buffer) EHCleanupScope(BranchFixups.size(),
103 InnermostNormalCleanup,
104 InnermostEHCleanup,
105 NormalEntry, NormalExit, EHEntry, EHExit);
106 if (NormalEntry)
107 InnermostNormalCleanup = stable_begin();
108 if (EHEntry)
109 InnermostEHCleanup = stable_begin();
110}
111
112void EHScopeStack::popCleanup() {
113 assert(!empty() && "popping exception stack when not empty");
114
John McCallda65ea82010-07-13 20:32:21 +0000115 if (isa<EHLazyCleanupScope>(*begin())) {
116 EHLazyCleanupScope &Cleanup = cast<EHLazyCleanupScope>(*begin());
117 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
118 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
119 StartOfData += Cleanup.getAllocatedSize();
120 } else {
121 assert(isa<EHCleanupScope>(*begin()));
122 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
123 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
124 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
125 StartOfData += EHCleanupScope::getSize();
126 }
John McCallf1549f62010-07-06 01:34:17 +0000127
128 // Check whether we can shrink the branch-fixups stack.
129 if (!BranchFixups.empty()) {
130 // If we no longer have any normal cleanups, all the fixups are
131 // complete.
132 if (!hasNormalCleanups())
133 BranchFixups.clear();
134
135 // Otherwise we can still trim out unnecessary nulls.
136 else
137 popNullFixups();
138 }
139}
140
141EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
142 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
143 CatchDepth++;
144 return new (Buffer) EHFilterScope(NumFilters);
145}
146
147void EHScopeStack::popFilter() {
148 assert(!empty() && "popping exception stack when not empty");
149
150 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
151 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
152
153 assert(CatchDepth > 0 && "mismatched filter push/pop");
154 CatchDepth--;
155}
156
157EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
158 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
159 CatchDepth++;
160 return new (Buffer) EHCatchScope(NumHandlers);
161}
162
163void EHScopeStack::pushTerminate() {
164 char *Buffer = allocate(EHTerminateScope::getSize());
165 CatchDepth++;
166 new (Buffer) EHTerminateScope();
167}
168
169/// Remove any 'null' fixups on the stack. However, we can't pop more
170/// fixups than the fixup depth on the innermost normal cleanup, or
171/// else fixups that we try to add to that cleanup will end up in the
172/// wrong place. We *could* try to shrink fixup depths, but that's
173/// actually a lot of work for little benefit.
174void EHScopeStack::popNullFixups() {
175 // We expect this to only be called when there's still an innermost
176 // normal cleanup; otherwise there really shouldn't be any fixups.
177 assert(hasNormalCleanups());
178
179 EHScopeStack::iterator it = find(InnermostNormalCleanup);
John McCallda65ea82010-07-13 20:32:21 +0000180 unsigned MinSize;
181 if (isa<EHCleanupScope>(*it))
182 MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
183 else
184 MinSize = cast<EHLazyCleanupScope>(*it).getFixupDepth();
John McCallf1549f62010-07-06 01:34:17 +0000185 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
186
187 while (BranchFixups.size() > MinSize &&
188 BranchFixups.back().Destination == 0)
189 BranchFixups.pop_back();
190}
191
192void EHScopeStack::resolveBranchFixups(llvm::BasicBlock *Dest) {
193 assert(Dest && "null block passed to resolveBranchFixups");
194
195 if (BranchFixups.empty()) return;
196 assert(hasNormalCleanups() &&
197 "branch fixups exist with no normal cleanups on stack");
198
199 for (unsigned I = 0, E = BranchFixups.size(); I != E; ++I)
200 if (BranchFixups[I].Destination == Dest)
201 BranchFixups[I].Destination = 0;
202
203 popNullFixups();
204}
205
Anders Carlssond3379292009-10-30 02:27:02 +0000206static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
207 // void *__cxa_allocate_exception(size_t thrown_size);
208 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
209 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000210
211 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +0000212 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
213 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000214
Anders Carlssond3379292009-10-30 02:27:02 +0000215 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
216}
217
Mike Stump99533832009-12-02 07:41:41 +0000218static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
219 // void __cxa_free_exception(void *thrown_exception);
220 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
221 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000222
223 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000224 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
225 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000226
Mike Stump99533832009-12-02 07:41:41 +0000227 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
228}
229
Anders Carlssond3379292009-10-30 02:27:02 +0000230static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +0000231 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +0000232 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +0000233
234 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
235 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000236
237 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000238 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
239 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000240
Anders Carlssond3379292009-10-30 02:27:02 +0000241 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
242}
243
Mike Stumpb4eea692009-11-20 00:56:31 +0000244static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000245 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +0000246
Mike Stump8755ec32009-12-10 00:06:18 +0000247 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000248 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000249
Mike Stumpb4eea692009-11-20 00:56:31 +0000250 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
251}
252
John McCallf1549f62010-07-06 01:34:17 +0000253static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
254 // void *__cxa_get_exception_ptr(void*);
255 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
256 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
257
258 const llvm::FunctionType *FTy =
259 llvm::FunctionType::get(Int8PtrTy, Args, false);
260
261 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
262}
263
Mike Stump2bf701e2009-11-20 23:44:51 +0000264static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +0000265 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +0000266
267 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
268 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000269
270 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +0000271 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000272
Mike Stump2bf701e2009-11-20 23:44:51 +0000273 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
274}
275
276static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000277 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000278
Mike Stump8755ec32009-12-10 00:06:18 +0000279 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000280 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000281
Mike Stump2bf701e2009-11-20 23:44:51 +0000282 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
283}
284
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000285static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
286 // void __cxa_call_unexepcted(void *thrown_exception);
287
288 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
289 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000290
291 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000292 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
293 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000294
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000295 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
296}
297
Douglas Gregor86a3a032010-05-16 01:24:12 +0000298llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
299 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000300 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000301
302 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000303 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000304 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000305
Douglas Gregor86a3a032010-05-16 01:24:12 +0000306 if (CGM.getLangOptions().SjLjExceptions)
307 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
308 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000309}
310
Mike Stump99533832009-12-02 07:41:41 +0000311static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
312 // void __terminate();
313
Mike Stump8755ec32009-12-10 00:06:18 +0000314 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000315 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000316
David Chisnall79a9ad82010-05-17 13:49:20 +0000317 return CGF.CGM.CreateRuntimeFunction(FTy,
318 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
319}
320
John McCall8262b6a2010-07-17 00:43:08 +0000321static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
322 const char *Name) {
323 const llvm::Type *Int8PtrTy =
324 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
325 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
326
327 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
328 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
329
330 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000331}
332
John McCall8262b6a2010-07-17 00:43:08 +0000333const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
334const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
335const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
336const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
337const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
338 "objc_exception_throw");
339
340static const EHPersonality &getCPersonality(const LangOptions &L) {
341 return EHPersonality::GNU_C;
342}
343
344static const EHPersonality &getObjCPersonality(const LangOptions &L) {
345 if (L.NeXTRuntime) {
346 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
347 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000348 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000349 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000350 }
351}
352
John McCall8262b6a2010-07-17 00:43:08 +0000353static const EHPersonality &getCXXPersonality(const LangOptions &L) {
354 if (L.SjLjExceptions)
355 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000356 else
John McCall8262b6a2010-07-17 00:43:08 +0000357 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000358}
359
360/// Determines the personality function to use when both C++
361/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000362static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000363 // The ObjC personality defers to the C++ personality for non-ObjC
364 // handlers. Unlike the C++ case, we use the same personality
365 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000366 if (L.NeXTRuntime) {
367 if (L.ObjCNonFragileABI)
368 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000369
370 // In the fragile ABI, just use C++ exception handling and hope
371 // they're not doing crazy exception mixing.
372 else
John McCall8262b6a2010-07-17 00:43:08 +0000373 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000374 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000375
John McCall8262b6a2010-07-17 00:43:08 +0000376 // The GNU runtime's personality function inherently doesn't support
377 // mixed EH. Use the C++ personality just to avoid returning null.
378 return getCXXPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000379}
380
John McCall8262b6a2010-07-17 00:43:08 +0000381const EHPersonality &EHPersonality::get(const LangOptions &L) {
382 if (L.CPlusPlus && L.ObjC1)
383 return getObjCXXPersonality(L);
384 else if (L.CPlusPlus)
385 return getCXXPersonality(L);
386 else if (L.ObjC1)
387 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000388 else
John McCall8262b6a2010-07-17 00:43:08 +0000389 return getCPersonality(L);
390}
John McCallf1549f62010-07-06 01:34:17 +0000391
John McCall8262b6a2010-07-17 00:43:08 +0000392static llvm::Constant *getPersonalityFn(CodeGenFunction &CGF,
393 const EHPersonality &Personality) {
394 const char *Name = Personality.getPersonalityFnName();
395
396 llvm::Constant *Fn =
John McCallf1549f62010-07-06 01:34:17 +0000397 CGF.CGM.CreateRuntimeFunction(llvm::FunctionType::get(
398 llvm::Type::getInt32Ty(
399 CGF.CGM.getLLVMContext()),
400 true),
401 Name);
John McCall8262b6a2010-07-17 00:43:08 +0000402 return llvm::ConstantExpr::getBitCast(Fn, CGF.CGM.PtrToInt8Ty);
John McCallf1549f62010-07-06 01:34:17 +0000403}
404
405/// Returns the value to inject into a selector to indicate the
406/// presence of a catch-all.
407static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
408 // Possibly we should use @llvm.eh.catch.all.value here.
409 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
410}
411
412/// Returns the value to inject into a selector to indicate the
413/// presence of a cleanup.
414static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
415 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000416}
417
John McCall09faeab2010-07-13 21:17:51 +0000418namespace {
419 /// A cleanup to free the exception object if its initialization
420 /// throws.
421 struct FreeExceptionCleanup : EHScopeStack::LazyCleanup {
422 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
423 llvm::Value *ExnLocVar)
424 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
425
426 llvm::Value *ShouldFreeVar;
427 llvm::Value *ExnLocVar;
428
429 void Emit(CodeGenFunction &CGF, bool IsForEH) {
430 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
431 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
432
433 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
434 "should-free-exnobj");
435 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
436 CGF.EmitBlock(FreeBB);
437 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
438 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
439 ->setDoesNotThrow();
440 CGF.EmitBlock(DoneBB);
441 }
442 };
443}
444
John McCallac418162010-04-22 01:10:34 +0000445// Emits an exception expression into the given location. This
446// differs from EmitAnyExprToMem only in that, if a final copy-ctor
447// call is required, an exception within that copy ctor causes
448// std::terminate to be invoked.
449static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
450 llvm::Value *ExnLoc) {
451 // We want to release the allocated exception object if this
452 // expression throws. We do this by pushing an EH-only cleanup
453 // block which, furthermore, deactivates itself after the expression
454 // is complete.
455 llvm::AllocaInst *ShouldFreeVar =
456 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
457 "should-free-exnobj.var");
458 CGF.InitTempAlloca(ShouldFreeVar,
459 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump0f590be2009-12-01 03:41:18 +0000460
John McCallac418162010-04-22 01:10:34 +0000461 // A variable holding the exception pointer. This is necessary
462 // because the throw expression does not necessarily dominate the
463 // cleanup, for example if it appears in a conditional expression.
464 llvm::AllocaInst *ExnLocVar =
465 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump8755ec32009-12-10 00:06:18 +0000466
John McCallf1549f62010-07-06 01:34:17 +0000467 // Make sure the exception object is cleaned up if there's an
468 // exception during initialization.
John McCall09faeab2010-07-13 21:17:51 +0000469 // FIXME: stmt expressions might require this to be a normal
470 // cleanup, too.
471 CGF.EHStack.pushLazyCleanup<FreeExceptionCleanup>(EHCleanup,
472 ShouldFreeVar,
473 ExnLocVar);
John McCallf1549f62010-07-06 01:34:17 +0000474 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000475
476 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
477 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
478 ShouldFreeVar);
479
480 // __cxa_allocate_exception returns a void*; we need to cast this
481 // to the appropriate type for the object.
482 const llvm::Type *Ty = CGF.ConvertType(E->getType())->getPointerTo();
483 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
484
485 // FIXME: this isn't quite right! If there's a final unelided call
486 // to a copy constructor, then according to [except.terminate]p1 we
487 // must call std::terminate() if that constructor throws, because
488 // technically that copy occurs after the exception expression is
489 // evaluated but before the exception is caught. But the best way
490 // to handle that is to teach EmitAggExpr to do the final copy
491 // differently if it can't be elided.
492 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false);
493
494 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
495 ShouldFreeVar);
496
John McCallf1549f62010-07-06 01:34:17 +0000497 // Technically, the exception object is like a temporary; it has to
498 // be cleaned up when its full-expression is complete.
499 // Unfortunately, the AST represents full-expressions by creating a
500 // CXXExprWithTemporaries, which it only does when there are actually
501 // temporaries.
502 //
503 // If any cleanups have been added since we pushed ours, they must
504 // be from temporaries; this will get popped at the same time.
505 // Otherwise we need to pop ours off. FIXME: this is very brittle.
506 if (Cleanup == CGF.EHStack.stable_begin())
507 CGF.PopCleanupBlock();
Mike Stump0f590be2009-12-01 03:41:18 +0000508}
509
John McCallf1549f62010-07-06 01:34:17 +0000510llvm::Value *CodeGenFunction::getExceptionSlot() {
511 if (!ExceptionSlot) {
512 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
513 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000514 }
John McCallf1549f62010-07-06 01:34:17 +0000515 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000516}
517
Anders Carlsson756b5c42009-10-30 01:42:31 +0000518void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000519 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000520 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000521 Builder.CreateInvoke(getReThrowFn(*this),
522 getUnreachableBlock(),
523 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000524 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000525 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000526 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000527 Builder.CreateUnreachable();
528 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000529
530 // Clear the insertion point to indicate we are in unreachable code.
531 Builder.ClearInsertionPoint();
Anders Carlssond3379292009-10-30 02:27:02 +0000532 return;
533 }
Mike Stump8755ec32009-12-10 00:06:18 +0000534
Anders Carlssond3379292009-10-30 02:27:02 +0000535 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000536
Anders Carlssond3379292009-10-30 02:27:02 +0000537 // Now allocate the exception object.
538 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000539 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000540
Anders Carlssond3379292009-10-30 02:27:02 +0000541 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000542 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000543 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000544 llvm::ConstantInt::get(SizeTy, TypeSize),
545 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000546 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000547
John McCallac418162010-04-22 01:10:34 +0000548 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000549
Anders Carlssond3379292009-10-30 02:27:02 +0000550 // Now throw the exception.
551 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall9dffe6f2010-04-30 01:15:21 +0000552 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
John McCallac418162010-04-22 01:10:34 +0000553
554 // The address of the destructor. If the exception type has a
555 // trivial destructor (or isn't a record), we just pass null.
556 llvm::Constant *Dtor = 0;
557 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
558 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
559 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000560 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000561 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
562 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
563 }
564 }
565 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000566
Mike Stump0a3816e2009-12-04 01:51:45 +0000567 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000568 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000569 Builder.CreateInvoke3(getThrowFn(*this),
570 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000571 ExceptionPtr, TypeInfo, Dtor);
572 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000573 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000574 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000575 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
576 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000577 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000578 }
Mike Stump8755ec32009-12-10 00:06:18 +0000579
Anders Carlssond3379292009-10-30 02:27:02 +0000580 // Clear the insertion point to indicate we are in unreachable code.
581 Builder.ClearInsertionPoint();
Mike Stumpc2ab4862009-12-07 20:12:14 +0000582
583 // FIXME: For now, emit a dummy basic block because expr emitters in generally
584 // are not ready to handle emitting expressions at unreachable points.
585 EnsureInsertPoint();
Anders Carlsson756b5c42009-10-30 01:42:31 +0000586}
Mike Stump2bf701e2009-11-20 23:44:51 +0000587
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000588void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000589 if (!Exceptions)
590 return;
591
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000592 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
593 if (FD == 0)
594 return;
595 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
596 if (Proto == 0)
597 return;
598
599 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
600
601 if (!Proto->hasExceptionSpec())
602 return;
603
John McCallf1549f62010-07-06 01:34:17 +0000604 unsigned NumExceptions = Proto->getNumExceptions();
605 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000606
John McCallf1549f62010-07-06 01:34:17 +0000607 for (unsigned I = 0; I != NumExceptions; ++I) {
608 QualType Ty = Proto->getExceptionType(I);
609 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
John McCall9dffe6f2010-04-30 01:15:21 +0000610 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
John McCallf1549f62010-07-06 01:34:17 +0000611 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000612 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000613}
614
615void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000616 if (!Exceptions)
617 return;
618
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000619 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
620 if (FD == 0)
621 return;
622 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
623 if (Proto == 0)
624 return;
625
626 if (!Proto->hasExceptionSpec())
627 return;
628
John McCallf1549f62010-07-06 01:34:17 +0000629 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000630}
631
Mike Stump2bf701e2009-11-20 23:44:51 +0000632void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000633 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000634 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000635 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000636}
637
John McCall59a70002010-07-07 06:56:46 +0000638void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000639 unsigned NumHandlers = S.getNumHandlers();
640 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000641
John McCallf1549f62010-07-06 01:34:17 +0000642 for (unsigned I = 0; I != NumHandlers; ++I) {
643 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000644
John McCallf1549f62010-07-06 01:34:17 +0000645 llvm::BasicBlock *Handler = createBasicBlock("catch");
646 if (C->getExceptionDecl()) {
647 // FIXME: Dropping the reference type on the type into makes it
648 // impossible to correctly implement catch-by-reference
649 // semantics for pointers. Unfortunately, this is what all
650 // existing compilers do, and it's not clear that the standard
651 // personality routine is capable of doing this right. See C++ DR 388:
652 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
653 QualType CaughtType = C->getCaughtType();
654 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
655 llvm::Value *TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, true);
656 CatchScope->setHandler(I, TypeInfo, Handler);
657 } else {
658 // No exception decl indicates '...', a catch-all.
659 CatchScope->setCatchAllHandler(I, Handler);
660 }
661 }
John McCallf1549f62010-07-06 01:34:17 +0000662}
663
664/// Check whether this is a non-EH scope, i.e. a scope which doesn't
665/// affect exception handling. Currently, the only non-EH scopes are
666/// normal-only cleanup scopes.
667static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000668 switch (S.getKind()) {
669 case EHScope::Cleanup:
670 return !cast<EHCleanupScope>(S).isEHCleanup();
671 case EHScope::LazyCleanup:
672 return !cast<EHLazyCleanupScope>(S).isEHCleanup();
673 case EHScope::Filter:
674 case EHScope::Catch:
675 case EHScope::Terminate:
676 return false;
677 }
678
679 // Suppress warning.
680 return false;
John McCallf1549f62010-07-06 01:34:17 +0000681}
682
683llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
684 assert(EHStack.requiresLandingPad());
685 assert(!EHStack.empty());
686
John McCallda65ea82010-07-13 20:32:21 +0000687 if (!Exceptions)
688 return 0;
689
John McCallf1549f62010-07-06 01:34:17 +0000690 // Check the innermost scope for a cached landing pad. If this is
691 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
692 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
693 if (LP) return LP;
694
695 // Build the landing pad for this scope.
696 LP = EmitLandingPad();
697 assert(LP);
698
699 // Cache the landing pad on the innermost scope. If this is a
700 // non-EH scope, cache the landing pad on the enclosing scope, too.
701 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
702 ir->setCachedLandingPad(LP);
703 if (!isNonEHScope(*ir)) break;
704 }
705
706 return LP;
707}
708
709llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
710 assert(EHStack.requiresLandingPad());
711
712 // This function contains a hack to work around a design flaw in
713 // LLVM's EH IR which breaks semantics after inlining. This same
714 // hack is implemented in llvm-gcc.
715 //
716 // The LLVM EH abstraction is basically a thin veneer over the
717 // traditional GCC zero-cost design: for each range of instructions
718 // in the function, there is (at most) one "landing pad" with an
719 // associated chain of EH actions. A language-specific personality
720 // function interprets this chain of actions and (1) decides whether
721 // or not to resume execution at the landing pad and (2) if so,
722 // provides an integer indicating why it's stopping. In LLVM IR,
723 // the association of a landing pad with a range of instructions is
724 // achieved via an invoke instruction, the chain of actions becomes
725 // the arguments to the @llvm.eh.selector call, and the selector
726 // call returns the integer indicator. Other than the required
727 // presence of two intrinsic function calls in the landing pad,
728 // the IR exactly describes the layout of the output code.
729 //
730 // A principal advantage of this design is that it is completely
731 // language-agnostic; in theory, the LLVM optimizers can treat
732 // landing pads neutrally, and targets need only know how to lower
733 // the intrinsics to have a functioning exceptions system (assuming
734 // that platform exceptions follow something approximately like the
735 // GCC design). Unfortunately, landing pads cannot be combined in a
736 // language-agnostic way: given selectors A and B, there is no way
737 // to make a single landing pad which faithfully represents the
738 // semantics of propagating an exception first through A, then
739 // through B, without knowing how the personality will interpret the
740 // (lowered form of the) selectors. This means that inlining has no
741 // choice but to crudely chain invokes (i.e., to ignore invokes in
742 // the inlined function, but to turn all unwindable calls into
743 // invokes), which is only semantically valid if every unwind stops
744 // at every landing pad.
745 //
746 // Therefore, the invoke-inline hack is to guarantee that every
747 // landing pad has a catch-all.
748 const bool UseInvokeInlineHack = true;
749
750 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
751 assert(ir != EHStack.end() &&
752 "stack requiring landing pad is nothing but non-EH scopes?");
753
754 // If this is a terminate scope, just use the singleton terminate
755 // landing pad.
756 if (isa<EHTerminateScope>(*ir))
757 return getTerminateLandingPad();
758
759 // If this isn't an EH scope, iterate; otherwise break out.
760 if (!isNonEHScope(*ir)) break;
761 ++ir;
762
763 // We haven't checked this scope for a cached landing pad yet.
764 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
765 return LP;
766 }
767
768 // Save the current IR generation state.
769 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
770
John McCall8262b6a2010-07-17 00:43:08 +0000771 const EHPersonality &Personality =
772 EHPersonality::get(CGF.CGM.getLangOptions());
773
John McCallf1549f62010-07-06 01:34:17 +0000774 // Create and configure the landing pad.
775 llvm::BasicBlock *LP = createBasicBlock("lpad");
776 EmitBlock(LP);
777
778 // Save the exception pointer. It's safe to use a single exception
779 // pointer per function because EH cleanups can never have nested
780 // try/catches.
781 llvm::CallInst *Exn =
782 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
783 Exn->setDoesNotThrow();
784 Builder.CreateStore(Exn, getExceptionSlot());
785
786 // Build the selector arguments.
787 llvm::SmallVector<llvm::Value*, 8> EHSelector;
788 EHSelector.push_back(Exn);
John McCall8262b6a2010-07-17 00:43:08 +0000789 EHSelector.push_back(getPersonalityFn(*this, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000790
791 // Accumulate all the handlers in scope.
792 llvm::DenseMap<llvm::Value*, JumpDest> EHHandlers;
793 JumpDest CatchAll;
794 bool HasEHCleanup = false;
795 bool HasEHFilter = false;
796 llvm::SmallVector<llvm::Value*, 8> EHFilters;
797 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
798 I != E; ++I) {
799
800 switch (I->getKind()) {
John McCallda65ea82010-07-13 20:32:21 +0000801 case EHScope::LazyCleanup:
802 if (!HasEHCleanup)
803 HasEHCleanup = cast<EHLazyCleanupScope>(*I).isEHCleanup();
804 // We otherwise don't care about cleanups.
805 continue;
806
John McCallf1549f62010-07-06 01:34:17 +0000807 case EHScope::Cleanup:
808 if (!HasEHCleanup)
809 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
810 // We otherwise don't care about cleanups.
811 continue;
812
813 case EHScope::Filter: {
814 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
815 assert(!CatchAll.Block && "EH filter reached after catch-all");
816
817 // Filter scopes get added to the selector in wierd ways.
818 EHFilterScope &Filter = cast<EHFilterScope>(*I);
819 HasEHFilter = true;
820
821 // Add all the filter values which we aren't already explicitly
822 // catching.
823 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
824 llvm::Value *FV = Filter.getFilter(I);
825 if (!EHHandlers.count(FV))
826 EHFilters.push_back(FV);
827 }
828 goto done;
829 }
830
831 case EHScope::Terminate:
832 // Terminate scopes are basically catch-alls.
833 assert(!CatchAll.Block);
834 CatchAll.Block = getTerminateHandler();
835 CatchAll.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
836 goto done;
837
838 case EHScope::Catch:
839 break;
840 }
841
842 EHCatchScope &Catch = cast<EHCatchScope>(*I);
843 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
844 EHCatchScope::Handler Handler = Catch.getHandler(HI);
845
846 // Catch-all. We should only have one of these per catch.
847 if (!Handler.Type) {
848 assert(!CatchAll.Block);
849 CatchAll.Block = Handler.Block;
850 CatchAll.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
851 continue;
852 }
853
854 // Check whether we already have a handler for this type.
855 JumpDest &Dest = EHHandlers[Handler.Type];
856 if (Dest.Block) continue;
857
858 EHSelector.push_back(Handler.Type);
859 Dest.Block = Handler.Block;
860 Dest.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
861 }
862
863 // Stop if we found a catch-all.
864 if (CatchAll.Block) break;
865 }
866
867 done:
868 unsigned LastToEmitInLoop = EHSelector.size();
869
870 // If we have a catch-all, add null to the selector.
871 if (CatchAll.Block) {
872 EHSelector.push_back(getCatchAllValue(CGF));
873
874 // If we have an EH filter, we need to add those handlers in the
875 // right place in the selector, which is to say, at the end.
876 } else if (HasEHFilter) {
877 // Create a filter expression: an integer constant saying how many
878 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
879 // followed by the filter types. The personality routine only
880 // lands here if the filter doesn't match.
881 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
882 EHFilters.size() + 1));
883 EHSelector.append(EHFilters.begin(), EHFilters.end());
884
885 // Also check whether we need a cleanup.
886 if (UseInvokeInlineHack || HasEHCleanup)
887 EHSelector.push_back(UseInvokeInlineHack
888 ? getCatchAllValue(CGF)
889 : getCleanupValue(CGF));
890
891 // Otherwise, signal that we at least have cleanups.
892 } else if (UseInvokeInlineHack || HasEHCleanup) {
893 EHSelector.push_back(UseInvokeInlineHack
894 ? getCatchAllValue(CGF)
895 : getCleanupValue(CGF));
896 } else {
897 assert(LastToEmitInLoop > 2);
898 LastToEmitInLoop--;
899 }
900
901 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
902
903 // Tell the backend how to generate the landing pad.
904 llvm::CallInst *Selection =
905 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
906 EHSelector.begin(), EHSelector.end(), "eh.selector");
907 Selection->setDoesNotThrow();
908
909 // Select the right handler.
910 llvm::Value *llvm_eh_typeid_for =
911 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
912
913 // The results of llvm_eh_typeid_for aren't reliable --- at least
914 // not locally --- so we basically have to do this as an 'if' chain.
915 // We walk through the first N-1 catch clauses, testing and chaining,
916 // and then fall into the final clause (which is either a cleanup, a
917 // filter (possibly with a cleanup), a catch-all, or another catch).
918 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
919 llvm::Value *Type = EHSelector[I];
920 JumpDest Dest = EHHandlers[Type];
921 assert(Dest.Block && "no handler entry for value in selector?");
922
923 // Figure out where to branch on a match. As a debug code-size
924 // optimization, if the scope depth matches the innermost cleanup,
925 // we branch directly to the catch handler.
926 llvm::BasicBlock *Match = Dest.Block;
927 bool MatchNeedsCleanup = Dest.ScopeDepth != EHStack.getInnermostEHCleanup();
928 if (MatchNeedsCleanup)
929 Match = createBasicBlock("eh.match");
930
931 llvm::BasicBlock *Next = createBasicBlock("eh.next");
932
933 // Check whether the exception matches.
934 llvm::CallInst *Id
935 = Builder.CreateCall(llvm_eh_typeid_for,
936 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
937 Id->setDoesNotThrow();
938 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
939 Match, Next);
940
941 // Emit match code if necessary.
942 if (MatchNeedsCleanup) {
943 EmitBlock(Match);
944 EmitBranchThroughEHCleanup(Dest);
945 }
946
947 // Continue to the next match.
948 EmitBlock(Next);
949 }
950
951 // Emit the final case in the selector.
952 // This might be a catch-all....
953 if (CatchAll.Block) {
954 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
955 EmitBranchThroughEHCleanup(CatchAll);
956
957 // ...or an EH filter...
958 } else if (HasEHFilter) {
959 llvm::Value *SavedSelection = Selection;
960
961 // First, unwind out to the outermost scope if necessary.
962 if (EHStack.hasEHCleanups()) {
963 // The end here might not dominate the beginning, so we might need to
964 // save the selector if we need it.
965 llvm::AllocaInst *SelectorVar = 0;
966 if (HasEHCleanup) {
967 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
968 Builder.CreateStore(Selection, SelectorVar);
969 }
970
971 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
972 EmitBranchThroughEHCleanup(JumpDest(CleanupContBB, EHStack.stable_end()));
973 EmitBlock(CleanupContBB);
974
975 if (HasEHCleanup)
976 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
977 }
978
979 // If there was a cleanup, we'll need to actually check whether we
980 // landed here because the filter triggered.
981 if (UseInvokeInlineHack || HasEHCleanup) {
982 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
983 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
984
985 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
986 llvm::Value *FailsFilter =
987 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
988 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
989
990 // The rethrow block is where we land if this was a cleanup.
991 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
992 EmitBlock(RethrowBB);
993 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
994 Builder.CreateLoad(getExceptionSlot()))
995 ->setDoesNotReturn();
996 Builder.CreateUnreachable();
997
998 EmitBlock(UnexpectedBB);
999 }
1000
1001 // Call __cxa_call_unexpected. This doesn't need to be an invoke
1002 // because __cxa_call_unexpected magically filters exceptions
1003 // according to the last landing pad the exception was thrown
1004 // into. Seriously.
1005 Builder.CreateCall(getUnexpectedFn(*this),
1006 Builder.CreateLoad(getExceptionSlot()))
1007 ->setDoesNotReturn();
1008 Builder.CreateUnreachable();
1009
1010 // ...or a normal catch handler...
1011 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
1012 llvm::Value *Type = EHSelector.back();
1013 EmitBranchThroughEHCleanup(EHHandlers[Type]);
1014
1015 // ...or a cleanup.
1016 } else {
1017 // We emit a jump to a notional label at the outermost unwind state.
1018 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1019 JumpDest Dest(Unwind, EHStack.stable_end());
1020 EmitBranchThroughEHCleanup(Dest);
1021
1022 // The unwind block. We have to reload the exception here because
1023 // we might have unwound through arbitrary blocks, so the landing
1024 // pad might not dominate.
1025 EmitBlock(Unwind);
1026
1027 // This can always be a call because we necessarily didn't find
1028 // anything on the EH stack which needs our help.
John McCall8262b6a2010-07-17 00:43:08 +00001029 llvm::Constant *RethrowFn;
1030 if (const char *RethrowName = Personality.getCatchallRethrowFnName())
1031 RethrowFn = getCatchallRethrowFn(CGF, RethrowName);
1032 else
1033 RethrowFn = getUnwindResumeOrRethrowFn();
1034 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
John McCallf1549f62010-07-06 01:34:17 +00001035 ->setDoesNotReturn();
1036 Builder.CreateUnreachable();
1037 }
1038
1039 // Restore the old IR generation state.
1040 Builder.restoreIP(SavedIP);
1041
1042 return LP;
1043}
1044
John McCall8e3f8612010-07-13 22:12:14 +00001045namespace {
1046 /// A cleanup to call __cxa_end_catch. In many cases, the caught
1047 /// exception type lets us state definitively that the thrown exception
1048 /// type does not have a destructor. In particular:
1049 /// - Catch-alls tell us nothing, so we have to conservatively
1050 /// assume that the thrown exception might have a destructor.
1051 /// - Catches by reference behave according to their base types.
1052 /// - Catches of non-record types will only trigger for exceptions
1053 /// of non-record types, which never have destructors.
1054 /// - Catches of record types can trigger for arbitrary subclasses
1055 /// of the caught type, so we have to assume the actual thrown
1056 /// exception type might have a throwing destructor, even if the
1057 /// caught type's destructor is trivial or nothrow.
1058 struct CallEndCatch : EHScopeStack::LazyCleanup {
1059 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1060 bool MightThrow;
1061
1062 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1063 if (!MightThrow) {
1064 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1065 return;
1066 }
1067
1068 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1069 }
1070 };
1071}
1072
John McCallf1549f62010-07-06 01:34:17 +00001073/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1074/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001075///
1076/// \param EndMightThrow - true if __cxa_end_catch might throw
1077static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1078 llvm::Value *Exn,
1079 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +00001080 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1081 Call->setDoesNotThrow();
1082
John McCall8e3f8612010-07-13 22:12:14 +00001083 CGF.EHStack.pushLazyCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +00001084
1085 return Call;
1086}
1087
1088/// A "special initializer" callback for initializing a catch
1089/// parameter during catch initialization.
1090static void InitCatchParam(CodeGenFunction &CGF,
1091 const VarDecl &CatchParam,
1092 llvm::Value *ParamAddr) {
1093 // Load the exception from where the landing pad saved it.
1094 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1095
1096 CanQualType CatchType =
1097 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1098 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1099
1100 // If we're catching by reference, we can just cast the object
1101 // pointer to the appropriate pointer.
1102 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +00001103 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1104 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +00001105
John McCallf1549f62010-07-06 01:34:17 +00001106 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +00001107 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +00001108
1109 // We have no way to tell the personality function that we're
1110 // catching by reference, so if we're catching a pointer,
1111 // __cxa_begin_catch will actually return that pointer by value.
1112 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1113 QualType PointeeType = PT->getPointeeType();
1114
1115 // When catching by reference, generally we should just ignore
1116 // this by-value pointer and use the exception object instead.
1117 if (!PointeeType->isRecordType()) {
1118
1119 // Exn points to the struct _Unwind_Exception header, which
1120 // we have to skip past in order to reach the exception data.
1121 unsigned HeaderSize =
1122 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1123 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1124
1125 // However, if we're catching a pointer-to-record type that won't
1126 // work, because the personality function might have adjusted
1127 // the pointer. There's actually no way for us to fully satisfy
1128 // the language/ABI contract here: we can't use Exn because it
1129 // might have the wrong adjustment, but we can't use the by-value
1130 // pointer because it's off by a level of abstraction.
1131 //
1132 // The current solution is to dump the adjusted pointer into an
1133 // alloca, which breaks language semantics (because changing the
1134 // pointer doesn't change the exception) but at least works.
1135 // The better solution would be to filter out non-exact matches
1136 // and rethrow them, but this is tricky because the rethrow
1137 // really needs to be catchable by other sites at this landing
1138 // pad. The best solution is to fix the personality function.
1139 } else {
1140 // Pull the pointer for the reference type off.
1141 const llvm::Type *PtrTy =
1142 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1143
1144 // Create the temporary and write the adjusted pointer into it.
1145 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1146 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1147 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1148
1149 // Bind the reference to the temporary.
1150 AdjustedExn = ExnPtrTmp;
1151 }
1152 }
1153
John McCallf1549f62010-07-06 01:34:17 +00001154 llvm::Value *ExnCast =
1155 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1156 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1157 return;
1158 }
1159
1160 // Non-aggregates (plus complexes).
1161 bool IsComplex = false;
1162 if (!CGF.hasAggregateLLVMType(CatchType) ||
1163 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001164 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001165
1166 // If the catch type is a pointer type, __cxa_begin_catch returns
1167 // the pointer by value.
1168 if (CatchType->hasPointerRepresentation()) {
1169 llvm::Value *CastExn =
1170 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1171 CGF.Builder.CreateStore(CastExn, ParamAddr);
1172 return;
1173 }
1174
1175 // Otherwise, it returns a pointer into the exception object.
1176
1177 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1178 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1179
1180 if (IsComplex) {
1181 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1182 ParamAddr, /*volatile*/ false);
1183 } else {
1184 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1185 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, CatchType);
1186 }
1187 return;
1188 }
1189
1190 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1191 // initializer expression.
1192
1193 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1194 assert(RD && "aggregate catch type was not a record!");
1195
1196 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1197
1198 if (RD->hasTrivialCopyConstructor()) {
John McCall8e3f8612010-07-13 22:12:14 +00001199 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001200 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1201 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1202 return;
1203 }
1204
1205 // We have to call __cxa_get_exception_ptr to get the adjusted
1206 // pointer before copying.
1207 llvm::CallInst *AdjustedExn =
1208 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1209 AdjustedExn->setDoesNotThrow();
1210 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1211
1212 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1213 assert(CD && "record has no copy constructor!");
1214 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1215
1216 CallArgList CallArgs;
1217 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1218 CD->getThisType(CGF.getContext())));
1219 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1220 CD->getParamDecl(0)->getType()));
1221
1222 const FunctionProtoType *FPT
1223 = CD->getType()->getAs<FunctionProtoType>();
1224
1225 // Call the copy ctor in a terminate scope.
1226 CGF.EHStack.pushTerminate();
1227 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1228 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1229 CGF.EHStack.popTerminate();
1230
1231 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001232 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001233}
1234
1235/// Begins a catch statement by initializing the catch variable and
1236/// calling __cxa_begin_catch.
1237static void BeginCatch(CodeGenFunction &CGF,
1238 const CXXCatchStmt *S) {
1239 // We have to be very careful with the ordering of cleanups here:
1240 // C++ [except.throw]p4:
1241 // The destruction [of the exception temporary] occurs
1242 // immediately after the destruction of the object declared in
1243 // the exception-declaration in the handler.
1244 //
1245 // So the precise ordering is:
1246 // 1. Construct catch variable.
1247 // 2. __cxa_begin_catch
1248 // 3. Enter __cxa_end_catch cleanup
1249 // 4. Enter dtor cleanup
1250 //
1251 // We do this by initializing the exception variable with a
1252 // "special initializer", InitCatchParam. Delegation sequence:
1253 // - ExitCXXTryStmt opens a RunCleanupsScope
1254 // - EmitLocalBlockVarDecl creates the variable and debug info
1255 // - InitCatchParam initializes the variable from the exception
1256 // - CallBeginCatch calls __cxa_begin_catch
1257 // - CallBeginCatch enters the __cxa_end_catch cleanup
1258 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1259 // - EmitCXXTryStmt emits the code for the catch body
1260 // - EmitCXXTryStmt close the RunCleanupsScope
1261
1262 VarDecl *CatchParam = S->getExceptionDecl();
1263 if (!CatchParam) {
1264 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001265 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001266 return;
1267 }
1268
1269 // Emit the local.
1270 CGF.EmitLocalBlockVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001271}
1272
John McCallfcd5c0c2010-07-13 22:24:23 +00001273namespace {
1274 struct CallRethrow : EHScopeStack::LazyCleanup {
1275 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1276 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1277 }
1278 };
1279}
1280
John McCall59a70002010-07-07 06:56:46 +00001281void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001282 unsigned NumHandlers = S.getNumHandlers();
1283 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1284 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001285
John McCallf1549f62010-07-06 01:34:17 +00001286 // Copy the handler blocks off before we pop the EH stack. Emitting
1287 // the handlers might scribble on this memory.
1288 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1289 memcpy(Handlers.data(), CatchScope.begin(),
1290 NumHandlers * sizeof(EHCatchScope::Handler));
1291 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001292
John McCallf1549f62010-07-06 01:34:17 +00001293 // The fall-through block.
1294 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001295
John McCallf1549f62010-07-06 01:34:17 +00001296 // We just emitted the body of the try; jump to the continue block.
1297 if (HaveInsertPoint())
1298 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001299
John McCall59a70002010-07-07 06:56:46 +00001300 // Determine if we need an implicit rethrow for all these catch handlers.
1301 bool ImplicitRethrow = false;
1302 if (IsFnTryBlock)
1303 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1304 isa<CXXConstructorDecl>(CurCodeDecl);
1305
John McCallf1549f62010-07-06 01:34:17 +00001306 for (unsigned I = 0; I != NumHandlers; ++I) {
1307 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1308 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001309
John McCallf1549f62010-07-06 01:34:17 +00001310 // Catch the exception if this isn't a catch-all.
1311 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001312
John McCallf1549f62010-07-06 01:34:17 +00001313 // Enter a cleanup scope, including the catch variable and the
1314 // end-catch.
1315 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001316
John McCallf1549f62010-07-06 01:34:17 +00001317 // Initialize the catch variable and set up the cleanups.
1318 BeginCatch(*this, C);
1319
John McCall59a70002010-07-07 06:56:46 +00001320 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001321 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1322 // called, and so it is pushed after BeginCatch.
1323 if (ImplicitRethrow)
1324 EHStack.pushLazyCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001325
John McCallf1549f62010-07-06 01:34:17 +00001326 // Perform the body of the catch.
1327 EmitStmt(C->getHandlerBlock());
1328
1329 // Fall out through the catch cleanups.
1330 CatchScope.ForceCleanup();
1331
1332 // Branch out of the try.
1333 if (HaveInsertPoint())
1334 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001335 }
1336
John McCallf1549f62010-07-06 01:34:17 +00001337 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001338}
Mike Stumpd88ea562009-12-09 03:35:49 +00001339
John McCall55b20fc2010-07-21 00:52:03 +00001340namespace {
1341 struct CallEndCatchForFinally : EHScopeStack::LazyCleanup {
1342 llvm::Value *ForEHVar;
1343 llvm::Value *EndCatchFn;
1344 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1345 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1346
1347 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1348 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1349 llvm::BasicBlock *CleanupContBB =
1350 CGF.createBasicBlock("finally.cleanup.cont");
1351
1352 llvm::Value *ShouldEndCatch =
1353 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1354 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1355 CGF.EmitBlock(EndCatchBB);
1356 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1357 CGF.EmitBlock(CleanupContBB);
1358 }
1359 };
John McCall77199712010-07-21 05:47:49 +00001360
1361 struct PerformFinally : EHScopeStack::LazyCleanup {
1362 const Stmt *Body;
1363 llvm::Value *ForEHVar;
1364 llvm::Value *EndCatchFn;
1365 llvm::Value *RethrowFn;
1366 llvm::Value *SavedExnVar;
1367
1368 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1369 llvm::Value *EndCatchFn,
1370 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1371 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1372 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1373
1374 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1375 // Enter a cleanup to call the end-catch function if one was provided.
1376 if (EndCatchFn)
1377 CGF.EHStack.pushLazyCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1378 ForEHVar, EndCatchFn);
1379
1380 // Emit the finally block.
1381 CGF.EmitStmt(Body);
1382
1383 // If the end of the finally is reachable, check whether this was
1384 // for EH. If so, rethrow.
1385 if (CGF.HaveInsertPoint()) {
1386 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1387 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1388
1389 llvm::Value *ShouldRethrow =
1390 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1391 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1392
1393 CGF.EmitBlock(RethrowBB);
1394 if (SavedExnVar) {
1395 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1396 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1397 } else {
1398 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1399 }
1400 CGF.Builder.CreateUnreachable();
1401
1402 CGF.EmitBlock(ContBB);
1403 }
1404
1405 // Leave the end-catch cleanup. As an optimization, pretend that
1406 // the fallthrough path was inaccessible; we've dynamically proven
1407 // that we're not in the EH case along that path.
1408 if (EndCatchFn) {
1409 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1410 CGF.PopCleanupBlock();
1411 CGF.Builder.restoreIP(SavedIP);
1412 }
1413
1414 // Now make sure we actually have an insertion point or the
1415 // cleanup gods will hate us.
1416 CGF.EnsureInsertPoint();
1417 }
1418 };
John McCall55b20fc2010-07-21 00:52:03 +00001419}
1420
John McCallf1549f62010-07-06 01:34:17 +00001421/// Enters a finally block for an implementation using zero-cost
1422/// exceptions. This is mostly general, but hard-codes some
1423/// language/ABI-specific behavior in the catch-all sections.
1424CodeGenFunction::FinallyInfo
1425CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1426 llvm::Constant *BeginCatchFn,
1427 llvm::Constant *EndCatchFn,
1428 llvm::Constant *RethrowFn) {
1429 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1430 "begin/end catch functions not paired");
1431 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001432
John McCallf1549f62010-07-06 01:34:17 +00001433 // The rethrow function has one of the following two types:
1434 // void (*)()
1435 // void (*)(void*)
1436 // In the latter case we need to pass it the exception object.
1437 // But we can't use the exception slot because the @finally might
1438 // have a landing pad (which would overwrite the exception slot).
1439 const llvm::FunctionType *RethrowFnTy =
1440 cast<llvm::FunctionType>(
1441 cast<llvm::PointerType>(RethrowFn->getType())
1442 ->getElementType());
1443 llvm::Value *SavedExnVar = 0;
1444 if (RethrowFnTy->getNumParams())
1445 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001446
John McCallf1549f62010-07-06 01:34:17 +00001447 // A finally block is a statement which must be executed on any edge
1448 // out of a given scope. Unlike a cleanup, the finally block may
1449 // contain arbitrary control flow leading out of itself. In
1450 // addition, finally blocks should always be executed, even if there
1451 // are no catch handlers higher on the stack. Therefore, we
1452 // surround the protected scope with a combination of a normal
1453 // cleanup (to catch attempts to break out of the block via normal
1454 // control flow) and an EH catch-all (semantically "outside" any try
1455 // statement to which the finally block might have been attached).
1456 // The finally block itself is generated in the context of a cleanup
1457 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001458
John McCallf1549f62010-07-06 01:34:17 +00001459 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001460
John McCallf1549f62010-07-06 01:34:17 +00001461 // Jump destination for performing the finally block on an exception
1462 // edge. We'll never actually reach this block, so unreachable is
1463 // fine.
1464 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001465
John McCallf1549f62010-07-06 01:34:17 +00001466 // Whether the finally block is being executed for EH purposes.
1467 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1468 "finally.for-eh");
1469 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001470
John McCallf1549f62010-07-06 01:34:17 +00001471 // Enter a normal cleanup which will perform the @finally block.
John McCall77199712010-07-21 05:47:49 +00001472 EHStack.pushLazyCleanup<PerformFinally>(NormalCleanup, Body,
1473 ForEHVar, EndCatchFn,
1474 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001475
1476 // Enter a catch-all scope.
1477 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1478 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1479 Builder.SetInsertPoint(CatchAllBB);
1480
1481 // If there's a begin-catch function, call it.
1482 if (BeginCatchFn) {
1483 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1484 ->setDoesNotThrow();
1485 }
1486
1487 // If we need to remember the exception pointer to rethrow later, do so.
1488 if (SavedExnVar) {
1489 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1490 Builder.CreateStore(SavedExn, SavedExnVar);
1491 }
1492
1493 // Tell the finally block that we're in EH.
1494 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1495
1496 // Thread a jump through the finally cleanup.
1497 EmitBranchThroughCleanup(RethrowDest);
1498
1499 Builder.restoreIP(SavedIP);
1500
1501 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1502 CatchScope->setCatchAllHandler(0, CatchAllBB);
1503
1504 return Info;
1505}
1506
1507void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1508 // Leave the finally catch-all.
1509 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1510 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1511 EHStack.popCatch();
1512
1513 // And leave the normal cleanup.
1514 PopCleanupBlock();
1515
1516 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1517 EmitBlock(CatchAllBB, true);
1518
1519 Builder.restoreIP(SavedIP);
1520}
1521
1522llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1523 if (TerminateLandingPad)
1524 return TerminateLandingPad;
1525
1526 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1527
1528 // This will get inserted at the end of the function.
1529 TerminateLandingPad = createBasicBlock("terminate.lpad");
1530 Builder.SetInsertPoint(TerminateLandingPad);
1531
1532 // Tell the backend that this is a landing pad.
1533 llvm::CallInst *Exn =
1534 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1535 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001536
1537 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001538
1539 // Tell the backend what the exception table should be:
1540 // nothing but a catch-all.
John McCall8262b6a2010-07-17 00:43:08 +00001541 llvm::Value *Args[3] = { Exn, getPersonalityFn(*this, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001542 getCatchAllValue(*this) };
1543 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1544 Args, Args+3, "eh.selector")
1545 ->setDoesNotThrow();
1546
1547 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1548 TerminateCall->setDoesNotReturn();
1549 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001550 CGF.Builder.CreateUnreachable();
1551
John McCallf1549f62010-07-06 01:34:17 +00001552 // Restore the saved insertion state.
1553 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001554
John McCallf1549f62010-07-06 01:34:17 +00001555 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001556}
Mike Stump9b39c512009-12-09 22:59:31 +00001557
1558llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001559 if (TerminateHandler)
1560 return TerminateHandler;
1561
John McCallf1549f62010-07-06 01:34:17 +00001562 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001563
John McCallf1549f62010-07-06 01:34:17 +00001564 // Set up the terminate handler. This block is inserted at the very
1565 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001566 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001567 Builder.SetInsertPoint(TerminateHandler);
1568 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001569 TerminateCall->setDoesNotReturn();
1570 TerminateCall->setDoesNotThrow();
1571 Builder.CreateUnreachable();
1572
John McCall3d3ec1c2010-04-21 10:05:39 +00001573 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001574 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001575
Mike Stump9b39c512009-12-09 22:59:31 +00001576 return TerminateHandler;
1577}
John McCallf1549f62010-07-06 01:34:17 +00001578
John McCall3e29f962010-07-13 23:19:49 +00001579EHScopeStack::LazyCleanup::~LazyCleanup() {
1580 llvm_unreachable("LazyCleanup is indestructable");
1581}