blob: 252e547b5d1171e71d07573ab799af768b7db592 [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 McCallb2593832010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallf1549f62010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump2bf701e2009-11-20 23:44:51 +000019
John McCall5a180392010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson756b5c42009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000022#include "CGException.h"
John McCall204b0752010-07-20 22:17:55 +000023#include "TargetInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000024
Anders Carlsson756b5c42009-10-30 01:42:31 +000025using namespace clang;
26using namespace CodeGen;
27
John McCallf1549f62010-07-06 01:34:17 +000028/// Push an entry of the given size onto this protected-scope stack.
29char *EHScopeStack::allocate(size_t Size) {
30 if (!StartOfBuffer) {
31 unsigned Capacity = 1024;
32 while (Capacity < Size) Capacity *= 2;
33 StartOfBuffer = new char[Capacity];
34 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
35 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
36 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
37 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
38
39 unsigned NewCapacity = CurrentCapacity;
40 do {
41 NewCapacity *= 2;
42 } while (NewCapacity < UsedCapacity + Size);
43
44 char *NewStartOfBuffer = new char[NewCapacity];
45 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
46 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
47 memcpy(NewStartOfData, StartOfData, UsedCapacity);
48 delete [] StartOfBuffer;
49 StartOfBuffer = NewStartOfBuffer;
50 EndOfBuffer = NewEndOfBuffer;
51 StartOfData = NewStartOfData;
52 }
53
54 assert(StartOfBuffer + Size <= StartOfData);
55 StartOfData -= Size;
56 return StartOfData;
57}
58
59EHScopeStack::stable_iterator
60EHScopeStack::getEnclosingEHCleanup(iterator it) const {
61 assert(it != end());
62 do {
John McCall1f0fca52010-07-21 07:22:38 +000063 if (isa<EHCleanupScope>(*it)) {
64 if (cast<EHCleanupScope>(*it).isEHCleanup())
John McCallda65ea82010-07-13 20:32:21 +000065 return stabilize(it);
John McCall1f0fca52010-07-21 07:22:38 +000066 return cast<EHCleanupScope>(*it).getEnclosingEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +000067 }
John McCallf1549f62010-07-06 01:34:17 +000068 ++it;
69 } while (it != end());
70 return stable_end();
71}
72
73
John McCall1f0fca52010-07-21 07:22:38 +000074void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCallda65ea82010-07-13 20:32:21 +000075 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
John McCall1f0fca52010-07-21 07:22:38 +000076 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
John McCallcd2d2b72010-08-13 21:20:51 +000077 bool IsNormalCleanup = Kind & NormalCleanup;
78 bool IsEHCleanup = Kind & EHCleanup;
79 bool IsActive = !(Kind & InactiveCleanup);
John McCall1f0fca52010-07-21 07:22:38 +000080 EHCleanupScope *Scope =
81 new (Buffer) EHCleanupScope(IsNormalCleanup,
82 IsEHCleanup,
John McCallcd2d2b72010-08-13 21:20:51 +000083 IsActive,
John McCall1f0fca52010-07-21 07:22:38 +000084 Size,
85 BranchFixups.size(),
86 InnermostNormalCleanup,
87 InnermostEHCleanup);
John McCallda65ea82010-07-13 20:32:21 +000088 if (IsNormalCleanup)
89 InnermostNormalCleanup = stable_begin();
90 if (IsEHCleanup)
91 InnermostEHCleanup = stable_begin();
92
93 return Scope->getCleanupBuffer();
94}
95
John McCallf1549f62010-07-06 01:34:17 +000096void EHScopeStack::popCleanup() {
97 assert(!empty() && "popping exception stack when not empty");
98
John McCall1f0fca52010-07-21 07:22:38 +000099 assert(isa<EHCleanupScope>(*begin()));
100 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
John McCall7495f222010-07-21 07:11:21 +0000101 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
102 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
103 StartOfData += Cleanup.getAllocatedSize();
John McCallf1549f62010-07-06 01:34:17 +0000104
John McCallff8e1152010-07-23 21:56:41 +0000105 if (empty()) NextEHDestIndex = FirstEHDestIndex;
106
107 // Destroy the cleanup.
108 Cleanup.~EHCleanupScope();
109
John McCallf1549f62010-07-06 01:34:17 +0000110 // Check whether we can shrink the branch-fixups stack.
111 if (!BranchFixups.empty()) {
112 // If we no longer have any normal cleanups, all the fixups are
113 // complete.
114 if (!hasNormalCleanups())
115 BranchFixups.clear();
116
117 // Otherwise we can still trim out unnecessary nulls.
118 else
119 popNullFixups();
120 }
121}
122
123EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
124 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
125 CatchDepth++;
126 return new (Buffer) EHFilterScope(NumFilters);
127}
128
129void EHScopeStack::popFilter() {
130 assert(!empty() && "popping exception stack when not empty");
131
132 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
133 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
134
John McCallff8e1152010-07-23 21:56:41 +0000135 if (empty()) NextEHDestIndex = FirstEHDestIndex;
136
John McCallf1549f62010-07-06 01:34:17 +0000137 assert(CatchDepth > 0 && "mismatched filter push/pop");
138 CatchDepth--;
139}
140
141EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
142 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
143 CatchDepth++;
John McCallff8e1152010-07-23 21:56:41 +0000144 EHCatchScope *Scope = new (Buffer) EHCatchScope(NumHandlers);
145 for (unsigned I = 0; I != NumHandlers; ++I)
146 Scope->getHandlers()[I].Index = getNextEHDestIndex();
147 return Scope;
John McCallf1549f62010-07-06 01:34:17 +0000148}
149
150void EHScopeStack::pushTerminate() {
151 char *Buffer = allocate(EHTerminateScope::getSize());
152 CatchDepth++;
John McCallff8e1152010-07-23 21:56:41 +0000153 new (Buffer) EHTerminateScope(getNextEHDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000154}
155
156/// Remove any 'null' fixups on the stack. However, we can't pop more
157/// fixups than the fixup depth on the innermost normal cleanup, or
158/// else fixups that we try to add to that cleanup will end up in the
159/// wrong place. We *could* try to shrink fixup depths, but that's
160/// actually a lot of work for little benefit.
161void EHScopeStack::popNullFixups() {
162 // We expect this to only be called when there's still an innermost
163 // normal cleanup; otherwise there really shouldn't be any fixups.
164 assert(hasNormalCleanups());
165
166 EHScopeStack::iterator it = find(InnermostNormalCleanup);
John McCall1f0fca52010-07-21 07:22:38 +0000167 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
John McCallf1549f62010-07-06 01:34:17 +0000168 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
169
170 while (BranchFixups.size() > MinSize &&
171 BranchFixups.back().Destination == 0)
172 BranchFixups.pop_back();
173}
174
Anders Carlssond3379292009-10-30 02:27:02 +0000175static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
176 // void *__cxa_allocate_exception(size_t thrown_size);
177 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
178 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000179
180 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +0000181 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
182 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000183
Anders Carlssond3379292009-10-30 02:27:02 +0000184 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
185}
186
Mike Stump99533832009-12-02 07:41:41 +0000187static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
188 // void __cxa_free_exception(void *thrown_exception);
189 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
190 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000191
192 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000193 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
194 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000195
Mike Stump99533832009-12-02 07:41:41 +0000196 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
197}
198
Anders Carlssond3379292009-10-30 02:27:02 +0000199static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +0000200 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +0000201 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +0000202
203 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
204 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000205
206 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000207 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
208 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000209
Anders Carlssond3379292009-10-30 02:27:02 +0000210 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
211}
212
Mike Stumpb4eea692009-11-20 00:56:31 +0000213static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000214 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +0000215
Mike Stump8755ec32009-12-10 00:06:18 +0000216 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000217 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000218
Mike Stumpb4eea692009-11-20 00:56:31 +0000219 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
220}
221
John McCallf1549f62010-07-06 01:34:17 +0000222static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
223 // void *__cxa_get_exception_ptr(void*);
224 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
225 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
226
227 const llvm::FunctionType *FTy =
228 llvm::FunctionType::get(Int8PtrTy, Args, false);
229
230 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
231}
232
Mike Stump2bf701e2009-11-20 23:44:51 +0000233static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +0000234 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +0000235
236 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
237 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000238
239 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +0000240 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000241
Mike Stump2bf701e2009-11-20 23:44:51 +0000242 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
243}
244
245static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000246 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000247
Mike Stump8755ec32009-12-10 00:06:18 +0000248 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000249 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000250
Mike Stump2bf701e2009-11-20 23:44:51 +0000251 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
252}
253
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000254static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
255 // void __cxa_call_unexepcted(void *thrown_exception);
256
257 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
258 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000259
260 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000261 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
262 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000263
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000264 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
265}
266
Douglas Gregor86a3a032010-05-16 01:24:12 +0000267llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
268 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000269 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000270
271 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000272 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000273 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000274
Douglas Gregor86a3a032010-05-16 01:24:12 +0000275 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000276 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000277 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000278}
279
Mike Stump99533832009-12-02 07:41:41 +0000280static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
281 // void __terminate();
282
Mike Stump8755ec32009-12-10 00:06:18 +0000283 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000284 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000285
David Chisnall79a9ad82010-05-17 13:49:20 +0000286 return CGF.CGM.CreateRuntimeFunction(FTy,
287 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
288}
289
John McCall8262b6a2010-07-17 00:43:08 +0000290static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000291 llvm::StringRef Name) {
John McCall8262b6a2010-07-17 00:43:08 +0000292 const llvm::Type *Int8PtrTy =
293 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
294 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
295
296 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
297 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
298
299 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000300}
301
John McCall8262b6a2010-07-17 00:43:08 +0000302const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000303const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000304const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
305const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
306const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
307const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
308 "objc_exception_throw");
309
310static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000311 if (L.SjLjExceptions)
312 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000313 return EHPersonality::GNU_C;
314}
315
316static const EHPersonality &getObjCPersonality(const LangOptions &L) {
317 if (L.NeXTRuntime) {
318 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
319 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000320 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000321 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000322 }
323}
324
John McCall8262b6a2010-07-17 00:43:08 +0000325static const EHPersonality &getCXXPersonality(const LangOptions &L) {
326 if (L.SjLjExceptions)
327 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000328 else
John McCall8262b6a2010-07-17 00:43:08 +0000329 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000330}
331
332/// Determines the personality function to use when both C++
333/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000334static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000335 // The ObjC personality defers to the C++ personality for non-ObjC
336 // handlers. Unlike the C++ case, we use the same personality
337 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000338 if (L.NeXTRuntime) {
339 if (L.ObjCNonFragileABI)
340 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000341
342 // In the fragile ABI, just use C++ exception handling and hope
343 // they're not doing crazy exception mixing.
344 else
John McCall8262b6a2010-07-17 00:43:08 +0000345 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000346 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000347
John McCall8262b6a2010-07-17 00:43:08 +0000348 // The GNU runtime's personality function inherently doesn't support
349 // mixed EH. Use the C++ personality just to avoid returning null.
350 return getCXXPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000351}
352
John McCall8262b6a2010-07-17 00:43:08 +0000353const EHPersonality &EHPersonality::get(const LangOptions &L) {
354 if (L.CPlusPlus && L.ObjC1)
355 return getObjCXXPersonality(L);
356 else if (L.CPlusPlus)
357 return getCXXPersonality(L);
358 else if (L.ObjC1)
359 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000360 else
John McCall8262b6a2010-07-17 00:43:08 +0000361 return getCPersonality(L);
362}
John McCallf1549f62010-07-06 01:34:17 +0000363
John McCallb2593832010-09-16 06:16:50 +0000364static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000365 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000366 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000367 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
368 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
369 true),
370 Personality.getPersonalityFnName());
371 return Fn;
372}
373
374static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
375 const EHPersonality &Personality) {
376 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
377 return llvm::ConstantExpr::getBitCast(Fn, CGM.PtrToInt8Ty);
378}
379
380/// Check whether a personality function could reasonably be swapped
381/// for a C++ personality function.
382static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
383 for (llvm::Constant::use_iterator
384 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
385 llvm::User *User = *I;
386
387 // Conditionally white-list bitcasts.
388 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
389 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
390 if (!PersonalityHasOnlyCXXUses(CE))
391 return false;
392 continue;
393 }
394
395 // Otherwise, it has to be a selector call.
396 if (!isa<llvm::EHSelectorInst>(User)) return false;
397
398 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
399 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
400 // Look for something that would've been returned by the ObjC
401 // runtime's GetEHType() method.
402 llvm::GlobalVariable *GV
403 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
404 if (!GV) continue;
405
406 // ObjC EH selector entries are always global variables with
407 // names starting like this.
408 if (GV->getName().startswith("OBJC_EHTYPE"))
409 return false;
410 }
411 }
412
413 return true;
414}
415
416/// Try to use the C++ personality function in ObjC++. Not doing this
417/// can cause some incompatibilities with gcc, which is more
418/// aggressive about only using the ObjC++ personality in a function
419/// when it really needs it.
420void CodeGenModule::SimplifyPersonality() {
421 // For now, this is really a Darwin-specific operation.
422 if (Context.Target.getTriple().getOS() != llvm::Triple::Darwin)
423 return;
424
425 // If we're not in ObjC++ -fexceptions, there's nothing to do.
426 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
427 return;
428
429 const EHPersonality &ObjCXX = EHPersonality::get(Features);
430 const EHPersonality &CXX = getCXXPersonality(Features);
431 if (&ObjCXX == &CXX ||
432 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
433 return;
434
435 llvm::Function *Fn =
436 getModule().getFunction(ObjCXX.getPersonalityFnName());
437
438 // Nothing to do if it's unused.
439 if (!Fn || Fn->use_empty()) return;
440
441 // Can't do the optimization if it has non-C++ uses.
442 if (!PersonalityHasOnlyCXXUses(Fn)) return;
443
444 // Create the C++ personality function and kill off the old
445 // function.
446 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
447
448 // This can happen if the user is screwing with us.
449 if (Fn->getType() != CXXFn->getType()) return;
450
451 Fn->replaceAllUsesWith(CXXFn);
452 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000453}
454
455/// Returns the value to inject into a selector to indicate the
456/// presence of a catch-all.
457static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
458 // Possibly we should use @llvm.eh.catch.all.value here.
459 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
460}
461
462/// Returns the value to inject into a selector to indicate the
463/// presence of a cleanup.
464static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
465 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000466}
467
John McCall09faeab2010-07-13 21:17:51 +0000468namespace {
469 /// A cleanup to free the exception object if its initialization
470 /// throws.
John McCall1f0fca52010-07-21 07:22:38 +0000471 struct FreeExceptionCleanup : EHScopeStack::Cleanup {
John McCall09faeab2010-07-13 21:17:51 +0000472 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
473 llvm::Value *ExnLocVar)
474 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
475
476 llvm::Value *ShouldFreeVar;
477 llvm::Value *ExnLocVar;
478
479 void Emit(CodeGenFunction &CGF, bool IsForEH) {
480 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
481 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
482
483 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
484 "should-free-exnobj");
485 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
486 CGF.EmitBlock(FreeBB);
487 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
488 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
489 ->setDoesNotThrow();
490 CGF.EmitBlock(DoneBB);
491 }
492 };
493}
494
John McCallac418162010-04-22 01:10:34 +0000495// Emits an exception expression into the given location. This
496// differs from EmitAnyExprToMem only in that, if a final copy-ctor
497// call is required, an exception within that copy ctor causes
498// std::terminate to be invoked.
499static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
500 llvm::Value *ExnLoc) {
501 // We want to release the allocated exception object if this
502 // expression throws. We do this by pushing an EH-only cleanup
503 // block which, furthermore, deactivates itself after the expression
504 // is complete.
505 llvm::AllocaInst *ShouldFreeVar =
506 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
507 "should-free-exnobj.var");
508 CGF.InitTempAlloca(ShouldFreeVar,
509 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump0f590be2009-12-01 03:41:18 +0000510
John McCallac418162010-04-22 01:10:34 +0000511 // A variable holding the exception pointer. This is necessary
512 // because the throw expression does not necessarily dominate the
513 // cleanup, for example if it appears in a conditional expression.
514 llvm::AllocaInst *ExnLocVar =
515 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump8755ec32009-12-10 00:06:18 +0000516
John McCallf1549f62010-07-06 01:34:17 +0000517 // Make sure the exception object is cleaned up if there's an
518 // exception during initialization.
John McCall09faeab2010-07-13 21:17:51 +0000519 // FIXME: stmt expressions might require this to be a normal
520 // cleanup, too.
John McCall1f0fca52010-07-21 07:22:38 +0000521 CGF.EHStack.pushCleanup<FreeExceptionCleanup>(EHCleanup,
522 ShouldFreeVar,
523 ExnLocVar);
John McCallf1549f62010-07-06 01:34:17 +0000524 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000525
526 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
527 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
528 ShouldFreeVar);
529
530 // __cxa_allocate_exception returns a void*; we need to cast this
531 // to the appropriate type for the object.
John McCall14e1bc92010-10-29 08:14:02 +0000532 const llvm::Type *Ty = CGF.ConvertTypeForMem(E->getType())->getPointerTo();
John McCallac418162010-04-22 01:10:34 +0000533 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
534
535 // FIXME: this isn't quite right! If there's a final unelided call
536 // to a copy constructor, then according to [except.terminate]p1 we
537 // must call std::terminate() if that constructor throws, because
538 // technically that copy occurs after the exception expression is
539 // evaluated but before the exception is caught. But the best way
540 // to handle that is to teach EmitAggExpr to do the final copy
541 // differently if it can't be elided.
John McCall558d2ab2010-09-15 10:14:12 +0000542 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false, /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000543
544 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
545 ShouldFreeVar);
546
John McCallf1549f62010-07-06 01:34:17 +0000547 // Technically, the exception object is like a temporary; it has to
548 // be cleaned up when its full-expression is complete.
549 // Unfortunately, the AST represents full-expressions by creating a
John McCall4765fa02010-12-06 08:20:24 +0000550 // ExprWithCleanups, which it only does when there are actually
John McCallf1549f62010-07-06 01:34:17 +0000551 // temporaries.
552 //
553 // If any cleanups have been added since we pushed ours, they must
554 // be from temporaries; this will get popped at the same time.
555 // Otherwise we need to pop ours off. FIXME: this is very brittle.
556 if (Cleanup == CGF.EHStack.stable_begin())
557 CGF.PopCleanupBlock();
Mike Stump0f590be2009-12-01 03:41:18 +0000558}
559
John McCallf1549f62010-07-06 01:34:17 +0000560llvm::Value *CodeGenFunction::getExceptionSlot() {
561 if (!ExceptionSlot) {
562 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
563 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000564 }
John McCallf1549f62010-07-06 01:34:17 +0000565 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000566}
567
Anders Carlsson756b5c42009-10-30 01:42:31 +0000568void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000569 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000570 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000571 Builder.CreateInvoke(getReThrowFn(*this),
572 getUnreachableBlock(),
573 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000574 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000575 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000576 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000577 Builder.CreateUnreachable();
578 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000579
John McCallcd5b22e2011-01-12 03:41:02 +0000580 // throw is an expression, and the expression emitters expect us
581 // to leave ourselves at a valid insertion point.
582 EmitBlock(createBasicBlock("throw.cont"));
583
Anders Carlssond3379292009-10-30 02:27:02 +0000584 return;
585 }
Mike Stump8755ec32009-12-10 00:06:18 +0000586
Anders Carlssond3379292009-10-30 02:27:02 +0000587 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000588
Anders Carlssond3379292009-10-30 02:27:02 +0000589 // Now allocate the exception object.
590 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000591 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000592
Anders Carlssond3379292009-10-30 02:27:02 +0000593 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000594 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000595 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000596 llvm::ConstantInt::get(SizeTy, TypeSize),
597 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000598 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000599
John McCallac418162010-04-22 01:10:34 +0000600 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000601
Anders Carlssond3379292009-10-30 02:27:02 +0000602 // Now throw the exception.
603 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall9dffe6f2010-04-30 01:15:21 +0000604 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
John McCallac418162010-04-22 01:10:34 +0000605
606 // The address of the destructor. If the exception type has a
607 // trivial destructor (or isn't a record), we just pass null.
608 llvm::Constant *Dtor = 0;
609 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
610 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
611 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000612 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000613 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
614 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
615 }
616 }
617 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000618
Mike Stump0a3816e2009-12-04 01:51:45 +0000619 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000620 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000621 Builder.CreateInvoke3(getThrowFn(*this),
622 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000623 ExceptionPtr, TypeInfo, Dtor);
624 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000625 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000626 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000627 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
628 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000629 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000630 }
Mike Stump8755ec32009-12-10 00:06:18 +0000631
John McCallcd5b22e2011-01-12 03:41:02 +0000632 // throw is an expression, and the expression emitters expect us
633 // to leave ourselves at a valid insertion point.
634 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000635}
Mike Stump2bf701e2009-11-20 23:44:51 +0000636
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000637void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000638 if (!Exceptions)
639 return;
640
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000641 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
642 if (FD == 0)
643 return;
644 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
645 if (Proto == 0)
646 return;
647
648 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
649
650 if (!Proto->hasExceptionSpec())
651 return;
652
John McCallf1549f62010-07-06 01:34:17 +0000653 unsigned NumExceptions = Proto->getNumExceptions();
654 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000655
John McCallf1549f62010-07-06 01:34:17 +0000656 for (unsigned I = 0; I != NumExceptions; ++I) {
657 QualType Ty = Proto->getExceptionType(I);
658 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
John McCall9dffe6f2010-04-30 01:15:21 +0000659 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
John McCallf1549f62010-07-06 01:34:17 +0000660 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000661 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000662}
663
664void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000665 if (!Exceptions)
666 return;
667
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000668 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
669 if (FD == 0)
670 return;
671 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
672 if (Proto == 0)
673 return;
674
675 if (!Proto->hasExceptionSpec())
676 return;
677
John McCallf1549f62010-07-06 01:34:17 +0000678 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000679}
680
Mike Stump2bf701e2009-11-20 23:44:51 +0000681void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000682 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000683 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000684 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000685}
686
John McCall59a70002010-07-07 06:56:46 +0000687void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000688 unsigned NumHandlers = S.getNumHandlers();
689 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000690
John McCallf1549f62010-07-06 01:34:17 +0000691 for (unsigned I = 0; I != NumHandlers; ++I) {
692 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000693
John McCallf1549f62010-07-06 01:34:17 +0000694 llvm::BasicBlock *Handler = createBasicBlock("catch");
695 if (C->getExceptionDecl()) {
696 // FIXME: Dropping the reference type on the type into makes it
697 // impossible to correctly implement catch-by-reference
698 // semantics for pointers. Unfortunately, this is what all
699 // existing compilers do, and it's not clear that the standard
700 // personality routine is capable of doing this right. See C++ DR 388:
701 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
702 QualType CaughtType = C->getCaughtType();
703 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000704
705 llvm::Value *TypeInfo = 0;
706 if (CaughtType->isObjCObjectPointerType())
707 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
708 else
709 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, true);
John McCallf1549f62010-07-06 01:34:17 +0000710 CatchScope->setHandler(I, TypeInfo, Handler);
711 } else {
712 // No exception decl indicates '...', a catch-all.
713 CatchScope->setCatchAllHandler(I, Handler);
714 }
715 }
John McCallf1549f62010-07-06 01:34:17 +0000716}
717
718/// Check whether this is a non-EH scope, i.e. a scope which doesn't
719/// affect exception handling. Currently, the only non-EH scopes are
720/// normal-only cleanup scopes.
721static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000722 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000723 case EHScope::Cleanup:
724 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000725 case EHScope::Filter:
726 case EHScope::Catch:
727 case EHScope::Terminate:
728 return false;
729 }
730
731 // Suppress warning.
732 return false;
John McCallf1549f62010-07-06 01:34:17 +0000733}
734
735llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
736 assert(EHStack.requiresLandingPad());
737 assert(!EHStack.empty());
738
John McCallda65ea82010-07-13 20:32:21 +0000739 if (!Exceptions)
740 return 0;
741
John McCallf1549f62010-07-06 01:34:17 +0000742 // Check the innermost scope for a cached landing pad. If this is
743 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
744 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
745 if (LP) return LP;
746
747 // Build the landing pad for this scope.
748 LP = EmitLandingPad();
749 assert(LP);
750
751 // Cache the landing pad on the innermost scope. If this is a
752 // non-EH scope, cache the landing pad on the enclosing scope, too.
753 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
754 ir->setCachedLandingPad(LP);
755 if (!isNonEHScope(*ir)) break;
756 }
757
758 return LP;
759}
760
761llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
762 assert(EHStack.requiresLandingPad());
763
764 // This function contains a hack to work around a design flaw in
765 // LLVM's EH IR which breaks semantics after inlining. This same
766 // hack is implemented in llvm-gcc.
767 //
768 // The LLVM EH abstraction is basically a thin veneer over the
769 // traditional GCC zero-cost design: for each range of instructions
770 // in the function, there is (at most) one "landing pad" with an
771 // associated chain of EH actions. A language-specific personality
772 // function interprets this chain of actions and (1) decides whether
773 // or not to resume execution at the landing pad and (2) if so,
774 // provides an integer indicating why it's stopping. In LLVM IR,
775 // the association of a landing pad with a range of instructions is
776 // achieved via an invoke instruction, the chain of actions becomes
777 // the arguments to the @llvm.eh.selector call, and the selector
778 // call returns the integer indicator. Other than the required
779 // presence of two intrinsic function calls in the landing pad,
780 // the IR exactly describes the layout of the output code.
781 //
782 // A principal advantage of this design is that it is completely
783 // language-agnostic; in theory, the LLVM optimizers can treat
784 // landing pads neutrally, and targets need only know how to lower
785 // the intrinsics to have a functioning exceptions system (assuming
786 // that platform exceptions follow something approximately like the
787 // GCC design). Unfortunately, landing pads cannot be combined in a
788 // language-agnostic way: given selectors A and B, there is no way
789 // to make a single landing pad which faithfully represents the
790 // semantics of propagating an exception first through A, then
791 // through B, without knowing how the personality will interpret the
792 // (lowered form of the) selectors. This means that inlining has no
793 // choice but to crudely chain invokes (i.e., to ignore invokes in
794 // the inlined function, but to turn all unwindable calls into
795 // invokes), which is only semantically valid if every unwind stops
796 // at every landing pad.
797 //
798 // Therefore, the invoke-inline hack is to guarantee that every
799 // landing pad has a catch-all.
800 const bool UseInvokeInlineHack = true;
801
802 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
803 assert(ir != EHStack.end() &&
804 "stack requiring landing pad is nothing but non-EH scopes?");
805
806 // If this is a terminate scope, just use the singleton terminate
807 // landing pad.
808 if (isa<EHTerminateScope>(*ir))
809 return getTerminateLandingPad();
810
811 // If this isn't an EH scope, iterate; otherwise break out.
812 if (!isNonEHScope(*ir)) break;
813 ++ir;
814
815 // We haven't checked this scope for a cached landing pad yet.
816 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
817 return LP;
818 }
819
820 // Save the current IR generation state.
821 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
822
John McCall8262b6a2010-07-17 00:43:08 +0000823 const EHPersonality &Personality =
824 EHPersonality::get(CGF.CGM.getLangOptions());
825
John McCallf1549f62010-07-06 01:34:17 +0000826 // Create and configure the landing pad.
827 llvm::BasicBlock *LP = createBasicBlock("lpad");
828 EmitBlock(LP);
829
830 // Save the exception pointer. It's safe to use a single exception
831 // pointer per function because EH cleanups can never have nested
832 // try/catches.
833 llvm::CallInst *Exn =
834 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
835 Exn->setDoesNotThrow();
836 Builder.CreateStore(Exn, getExceptionSlot());
837
838 // Build the selector arguments.
839 llvm::SmallVector<llvm::Value*, 8> EHSelector;
840 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000841 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000842
843 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000844 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
845 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000846 bool HasEHCleanup = false;
847 bool HasEHFilter = false;
848 llvm::SmallVector<llvm::Value*, 8> EHFilters;
849 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
850 I != E; ++I) {
851
852 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000853 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000854 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000855 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000856 // We otherwise don't care about cleanups.
857 continue;
858
John McCallf1549f62010-07-06 01:34:17 +0000859 case EHScope::Filter: {
860 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000861 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000862
863 // Filter scopes get added to the selector in wierd ways.
864 EHFilterScope &Filter = cast<EHFilterScope>(*I);
865 HasEHFilter = true;
866
867 // Add all the filter values which we aren't already explicitly
868 // catching.
869 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
870 llvm::Value *FV = Filter.getFilter(I);
871 if (!EHHandlers.count(FV))
872 EHFilters.push_back(FV);
873 }
874 goto done;
875 }
876
877 case EHScope::Terminate:
878 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000879 assert(!CatchAll.isValid());
880 CatchAll = UnwindDest(getTerminateHandler(),
881 EHStack.getEnclosingEHCleanup(I),
882 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000883 goto done;
884
885 case EHScope::Catch:
886 break;
887 }
888
889 EHCatchScope &Catch = cast<EHCatchScope>(*I);
890 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
891 EHCatchScope::Handler Handler = Catch.getHandler(HI);
892
893 // Catch-all. We should only have one of these per catch.
894 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000895 assert(!CatchAll.isValid());
896 CatchAll = UnwindDest(Handler.Block,
897 EHStack.getEnclosingEHCleanup(I),
898 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000899 continue;
900 }
901
902 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000903 UnwindDest &Dest = EHHandlers[Handler.Type];
904 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000905
906 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000907 Dest = UnwindDest(Handler.Block,
908 EHStack.getEnclosingEHCleanup(I),
909 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000910 }
911
912 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000913 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000914 }
915
916 done:
917 unsigned LastToEmitInLoop = EHSelector.size();
918
919 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000920 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000921 EHSelector.push_back(getCatchAllValue(CGF));
922
923 // If we have an EH filter, we need to add those handlers in the
924 // right place in the selector, which is to say, at the end.
925 } else if (HasEHFilter) {
926 // Create a filter expression: an integer constant saying how many
927 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
928 // followed by the filter types. The personality routine only
929 // lands here if the filter doesn't match.
930 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
931 EHFilters.size() + 1));
932 EHSelector.append(EHFilters.begin(), EHFilters.end());
933
934 // Also check whether we need a cleanup.
935 if (UseInvokeInlineHack || HasEHCleanup)
936 EHSelector.push_back(UseInvokeInlineHack
937 ? getCatchAllValue(CGF)
938 : getCleanupValue(CGF));
939
940 // Otherwise, signal that we at least have cleanups.
941 } else if (UseInvokeInlineHack || HasEHCleanup) {
942 EHSelector.push_back(UseInvokeInlineHack
943 ? getCatchAllValue(CGF)
944 : getCleanupValue(CGF));
945 } else {
946 assert(LastToEmitInLoop > 2);
947 LastToEmitInLoop--;
948 }
949
950 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
951
952 // Tell the backend how to generate the landing pad.
953 llvm::CallInst *Selection =
954 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
955 EHSelector.begin(), EHSelector.end(), "eh.selector");
956 Selection->setDoesNotThrow();
957
958 // Select the right handler.
959 llvm::Value *llvm_eh_typeid_for =
960 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
961
962 // The results of llvm_eh_typeid_for aren't reliable --- at least
963 // not locally --- so we basically have to do this as an 'if' chain.
964 // We walk through the first N-1 catch clauses, testing and chaining,
965 // and then fall into the final clause (which is either a cleanup, a
966 // filter (possibly with a cleanup), a catch-all, or another catch).
967 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
968 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000969 UnwindDest Dest = EHHandlers[Type];
970 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000971
972 // Figure out where to branch on a match. As a debug code-size
973 // optimization, if the scope depth matches the innermost cleanup,
974 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000975 llvm::BasicBlock *Match = Dest.getBlock();
976 bool MatchNeedsCleanup =
977 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000978 if (MatchNeedsCleanup)
979 Match = createBasicBlock("eh.match");
980
981 llvm::BasicBlock *Next = createBasicBlock("eh.next");
982
983 // Check whether the exception matches.
984 llvm::CallInst *Id
985 = Builder.CreateCall(llvm_eh_typeid_for,
986 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
987 Id->setDoesNotThrow();
988 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
989 Match, Next);
990
991 // Emit match code if necessary.
992 if (MatchNeedsCleanup) {
993 EmitBlock(Match);
994 EmitBranchThroughEHCleanup(Dest);
995 }
996
997 // Continue to the next match.
998 EmitBlock(Next);
999 }
1000
1001 // Emit the final case in the selector.
1002 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +00001003 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +00001004 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
1005 EmitBranchThroughEHCleanup(CatchAll);
1006
1007 // ...or an EH filter...
1008 } else if (HasEHFilter) {
1009 llvm::Value *SavedSelection = Selection;
1010
1011 // First, unwind out to the outermost scope if necessary.
1012 if (EHStack.hasEHCleanups()) {
1013 // The end here might not dominate the beginning, so we might need to
1014 // save the selector if we need it.
1015 llvm::AllocaInst *SelectorVar = 0;
1016 if (HasEHCleanup) {
1017 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
1018 Builder.CreateStore(Selection, SelectorVar);
1019 }
1020
1021 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +00001022 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
1023 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +00001024 EmitBlock(CleanupContBB);
1025
1026 if (HasEHCleanup)
1027 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
1028 }
1029
1030 // If there was a cleanup, we'll need to actually check whether we
1031 // landed here because the filter triggered.
1032 if (UseInvokeInlineHack || HasEHCleanup) {
1033 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
1034 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
1035
1036 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
1037 llvm::Value *FailsFilter =
1038 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
1039 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
1040
1041 // The rethrow block is where we land if this was a cleanup.
1042 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
1043 EmitBlock(RethrowBB);
1044 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
1045 Builder.CreateLoad(getExceptionSlot()))
1046 ->setDoesNotReturn();
1047 Builder.CreateUnreachable();
1048
1049 EmitBlock(UnexpectedBB);
1050 }
1051
1052 // Call __cxa_call_unexpected. This doesn't need to be an invoke
1053 // because __cxa_call_unexpected magically filters exceptions
1054 // according to the last landing pad the exception was thrown
1055 // into. Seriously.
1056 Builder.CreateCall(getUnexpectedFn(*this),
1057 Builder.CreateLoad(getExceptionSlot()))
1058 ->setDoesNotReturn();
1059 Builder.CreateUnreachable();
1060
1061 // ...or a normal catch handler...
1062 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
1063 llvm::Value *Type = EHSelector.back();
1064 EmitBranchThroughEHCleanup(EHHandlers[Type]);
1065
1066 // ...or a cleanup.
1067 } else {
John McCallff8e1152010-07-23 21:56:41 +00001068 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +00001069 }
1070
1071 // Restore the old IR generation state.
1072 Builder.restoreIP(SavedIP);
1073
1074 return LP;
1075}
1076
John McCall8e3f8612010-07-13 22:12:14 +00001077namespace {
1078 /// A cleanup to call __cxa_end_catch. In many cases, the caught
1079 /// exception type lets us state definitively that the thrown exception
1080 /// type does not have a destructor. In particular:
1081 /// - Catch-alls tell us nothing, so we have to conservatively
1082 /// assume that the thrown exception might have a destructor.
1083 /// - Catches by reference behave according to their base types.
1084 /// - Catches of non-record types will only trigger for exceptions
1085 /// of non-record types, which never have destructors.
1086 /// - Catches of record types can trigger for arbitrary subclasses
1087 /// of the caught type, so we have to assume the actual thrown
1088 /// exception type might have a throwing destructor, even if the
1089 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +00001090 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +00001091 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1092 bool MightThrow;
1093
1094 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1095 if (!MightThrow) {
1096 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1097 return;
1098 }
1099
1100 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1101 }
1102 };
1103}
1104
John McCallf1549f62010-07-06 01:34:17 +00001105/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1106/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001107///
1108/// \param EndMightThrow - true if __cxa_end_catch might throw
1109static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1110 llvm::Value *Exn,
1111 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +00001112 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1113 Call->setDoesNotThrow();
1114
John McCall1f0fca52010-07-21 07:22:38 +00001115 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +00001116
1117 return Call;
1118}
1119
1120/// A "special initializer" callback for initializing a catch
1121/// parameter during catch initialization.
1122static void InitCatchParam(CodeGenFunction &CGF,
1123 const VarDecl &CatchParam,
1124 llvm::Value *ParamAddr) {
1125 // Load the exception from where the landing pad saved it.
1126 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1127
1128 CanQualType CatchType =
1129 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1130 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1131
1132 // If we're catching by reference, we can just cast the object
1133 // pointer to the appropriate pointer.
1134 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +00001135 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1136 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +00001137
John McCallf1549f62010-07-06 01:34:17 +00001138 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +00001139 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +00001140
1141 // We have no way to tell the personality function that we're
1142 // catching by reference, so if we're catching a pointer,
1143 // __cxa_begin_catch will actually return that pointer by value.
1144 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1145 QualType PointeeType = PT->getPointeeType();
1146
1147 // When catching by reference, generally we should just ignore
1148 // this by-value pointer and use the exception object instead.
1149 if (!PointeeType->isRecordType()) {
1150
1151 // Exn points to the struct _Unwind_Exception header, which
1152 // we have to skip past in order to reach the exception data.
1153 unsigned HeaderSize =
1154 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1155 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1156
1157 // However, if we're catching a pointer-to-record type that won't
1158 // work, because the personality function might have adjusted
1159 // the pointer. There's actually no way for us to fully satisfy
1160 // the language/ABI contract here: we can't use Exn because it
1161 // might have the wrong adjustment, but we can't use the by-value
1162 // pointer because it's off by a level of abstraction.
1163 //
1164 // The current solution is to dump the adjusted pointer into an
1165 // alloca, which breaks language semantics (because changing the
1166 // pointer doesn't change the exception) but at least works.
1167 // The better solution would be to filter out non-exact matches
1168 // and rethrow them, but this is tricky because the rethrow
1169 // really needs to be catchable by other sites at this landing
1170 // pad. The best solution is to fix the personality function.
1171 } else {
1172 // Pull the pointer for the reference type off.
1173 const llvm::Type *PtrTy =
1174 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1175
1176 // Create the temporary and write the adjusted pointer into it.
1177 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1178 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1179 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1180
1181 // Bind the reference to the temporary.
1182 AdjustedExn = ExnPtrTmp;
1183 }
1184 }
1185
John McCallf1549f62010-07-06 01:34:17 +00001186 llvm::Value *ExnCast =
1187 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1188 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1189 return;
1190 }
1191
1192 // Non-aggregates (plus complexes).
1193 bool IsComplex = false;
1194 if (!CGF.hasAggregateLLVMType(CatchType) ||
1195 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001196 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001197
1198 // If the catch type is a pointer type, __cxa_begin_catch returns
1199 // the pointer by value.
1200 if (CatchType->hasPointerRepresentation()) {
1201 llvm::Value *CastExn =
1202 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1203 CGF.Builder.CreateStore(CastExn, ParamAddr);
1204 return;
1205 }
1206
1207 // Otherwise, it returns a pointer into the exception object.
1208
1209 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1210 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1211
1212 if (IsComplex) {
1213 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1214 ParamAddr, /*volatile*/ false);
1215 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001216 unsigned Alignment =
1217 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001218 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001219 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1220 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001221 }
1222 return;
1223 }
1224
1225 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1226 // initializer expression.
1227
1228 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1229 assert(RD && "aggregate catch type was not a record!");
1230
1231 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1232
1233 if (RD->hasTrivialCopyConstructor()) {
John McCall8e3f8612010-07-13 22:12:14 +00001234 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001235 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1236 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1237 return;
1238 }
1239
1240 // We have to call __cxa_get_exception_ptr to get the adjusted
1241 // pointer before copying.
1242 llvm::CallInst *AdjustedExn =
1243 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1244 AdjustedExn->setDoesNotThrow();
1245 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1246
1247 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1248 assert(CD && "record has no copy constructor!");
1249 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1250
1251 CallArgList CallArgs;
1252 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1253 CD->getThisType(CGF.getContext())));
1254 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1255 CD->getParamDecl(0)->getType()));
1256
1257 const FunctionProtoType *FPT
1258 = CD->getType()->getAs<FunctionProtoType>();
1259
1260 // Call the copy ctor in a terminate scope.
1261 CGF.EHStack.pushTerminate();
1262 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1263 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1264 CGF.EHStack.popTerminate();
1265
1266 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001267 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001268}
1269
1270/// Begins a catch statement by initializing the catch variable and
1271/// calling __cxa_begin_catch.
1272static void BeginCatch(CodeGenFunction &CGF,
1273 const CXXCatchStmt *S) {
1274 // We have to be very careful with the ordering of cleanups here:
1275 // C++ [except.throw]p4:
1276 // The destruction [of the exception temporary] occurs
1277 // immediately after the destruction of the object declared in
1278 // the exception-declaration in the handler.
1279 //
1280 // So the precise ordering is:
1281 // 1. Construct catch variable.
1282 // 2. __cxa_begin_catch
1283 // 3. Enter __cxa_end_catch cleanup
1284 // 4. Enter dtor cleanup
1285 //
1286 // We do this by initializing the exception variable with a
1287 // "special initializer", InitCatchParam. Delegation sequence:
1288 // - ExitCXXTryStmt opens a RunCleanupsScope
1289 // - EmitLocalBlockVarDecl creates the variable and debug info
1290 // - InitCatchParam initializes the variable from the exception
1291 // - CallBeginCatch calls __cxa_begin_catch
1292 // - CallBeginCatch enters the __cxa_end_catch cleanup
1293 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1294 // - EmitCXXTryStmt emits the code for the catch body
1295 // - EmitCXXTryStmt close the RunCleanupsScope
1296
1297 VarDecl *CatchParam = S->getExceptionDecl();
1298 if (!CatchParam) {
1299 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001300 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001301 return;
1302 }
1303
1304 // Emit the local.
John McCallb6bbcc92010-10-15 04:57:14 +00001305 CGF.EmitAutoVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001306}
1307
John McCallfcd5c0c2010-07-13 22:24:23 +00001308namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001309 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001310 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1311 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1312 }
1313 };
1314}
1315
John McCall59a70002010-07-07 06:56:46 +00001316void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001317 unsigned NumHandlers = S.getNumHandlers();
1318 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1319 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001320
John McCallf1549f62010-07-06 01:34:17 +00001321 // Copy the handler blocks off before we pop the EH stack. Emitting
1322 // the handlers might scribble on this memory.
1323 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1324 memcpy(Handlers.data(), CatchScope.begin(),
1325 NumHandlers * sizeof(EHCatchScope::Handler));
1326 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001327
John McCallf1549f62010-07-06 01:34:17 +00001328 // The fall-through block.
1329 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001330
John McCallf1549f62010-07-06 01:34:17 +00001331 // We just emitted the body of the try; jump to the continue block.
1332 if (HaveInsertPoint())
1333 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001334
John McCall59a70002010-07-07 06:56:46 +00001335 // Determine if we need an implicit rethrow for all these catch handlers.
1336 bool ImplicitRethrow = false;
1337 if (IsFnTryBlock)
1338 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1339 isa<CXXConstructorDecl>(CurCodeDecl);
1340
John McCallf1549f62010-07-06 01:34:17 +00001341 for (unsigned I = 0; I != NumHandlers; ++I) {
1342 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1343 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001344
John McCallf1549f62010-07-06 01:34:17 +00001345 // Catch the exception if this isn't a catch-all.
1346 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001347
John McCallf1549f62010-07-06 01:34:17 +00001348 // Enter a cleanup scope, including the catch variable and the
1349 // end-catch.
1350 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001351
John McCallf1549f62010-07-06 01:34:17 +00001352 // Initialize the catch variable and set up the cleanups.
1353 BeginCatch(*this, C);
1354
John McCall59a70002010-07-07 06:56:46 +00001355 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001356 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1357 // called, and so it is pushed after BeginCatch.
1358 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001359 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001360
John McCallf1549f62010-07-06 01:34:17 +00001361 // Perform the body of the catch.
1362 EmitStmt(C->getHandlerBlock());
1363
1364 // Fall out through the catch cleanups.
1365 CatchScope.ForceCleanup();
1366
1367 // Branch out of the try.
1368 if (HaveInsertPoint())
1369 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001370 }
1371
John McCallf1549f62010-07-06 01:34:17 +00001372 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001373}
Mike Stumpd88ea562009-12-09 03:35:49 +00001374
John McCall55b20fc2010-07-21 00:52:03 +00001375namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001376 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001377 llvm::Value *ForEHVar;
1378 llvm::Value *EndCatchFn;
1379 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1380 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1381
1382 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1383 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1384 llvm::BasicBlock *CleanupContBB =
1385 CGF.createBasicBlock("finally.cleanup.cont");
1386
1387 llvm::Value *ShouldEndCatch =
1388 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1389 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1390 CGF.EmitBlock(EndCatchBB);
1391 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1392 CGF.EmitBlock(CleanupContBB);
1393 }
1394 };
John McCall77199712010-07-21 05:47:49 +00001395
John McCall1f0fca52010-07-21 07:22:38 +00001396 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001397 const Stmt *Body;
1398 llvm::Value *ForEHVar;
1399 llvm::Value *EndCatchFn;
1400 llvm::Value *RethrowFn;
1401 llvm::Value *SavedExnVar;
1402
1403 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1404 llvm::Value *EndCatchFn,
1405 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1406 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1407 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1408
1409 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1410 // Enter a cleanup to call the end-catch function if one was provided.
1411 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001412 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1413 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001414
John McCalld96a8e72010-08-11 00:16:14 +00001415 // Save the current cleanup destination in case there are
1416 // cleanups in the finally block.
1417 llvm::Value *SavedCleanupDest =
1418 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1419 "cleanup.dest.saved");
1420
John McCall77199712010-07-21 05:47:49 +00001421 // Emit the finally block.
1422 CGF.EmitStmt(Body);
1423
1424 // If the end of the finally is reachable, check whether this was
1425 // for EH. If so, rethrow.
1426 if (CGF.HaveInsertPoint()) {
1427 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1428 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1429
1430 llvm::Value *ShouldRethrow =
1431 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1432 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1433
1434 CGF.EmitBlock(RethrowBB);
1435 if (SavedExnVar) {
1436 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1437 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1438 } else {
1439 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1440 }
1441 CGF.Builder.CreateUnreachable();
1442
1443 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001444
1445 // Restore the cleanup destination.
1446 CGF.Builder.CreateStore(SavedCleanupDest,
1447 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001448 }
1449
1450 // Leave the end-catch cleanup. As an optimization, pretend that
1451 // the fallthrough path was inaccessible; we've dynamically proven
1452 // that we're not in the EH case along that path.
1453 if (EndCatchFn) {
1454 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1455 CGF.PopCleanupBlock();
1456 CGF.Builder.restoreIP(SavedIP);
1457 }
1458
1459 // Now make sure we actually have an insertion point or the
1460 // cleanup gods will hate us.
1461 CGF.EnsureInsertPoint();
1462 }
1463 };
John McCall55b20fc2010-07-21 00:52:03 +00001464}
1465
John McCallf1549f62010-07-06 01:34:17 +00001466/// Enters a finally block for an implementation using zero-cost
1467/// exceptions. This is mostly general, but hard-codes some
1468/// language/ABI-specific behavior in the catch-all sections.
1469CodeGenFunction::FinallyInfo
1470CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1471 llvm::Constant *BeginCatchFn,
1472 llvm::Constant *EndCatchFn,
1473 llvm::Constant *RethrowFn) {
1474 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1475 "begin/end catch functions not paired");
1476 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001477
John McCallf1549f62010-07-06 01:34:17 +00001478 // The rethrow function has one of the following two types:
1479 // void (*)()
1480 // void (*)(void*)
1481 // In the latter case we need to pass it the exception object.
1482 // But we can't use the exception slot because the @finally might
1483 // have a landing pad (which would overwrite the exception slot).
1484 const llvm::FunctionType *RethrowFnTy =
1485 cast<llvm::FunctionType>(
1486 cast<llvm::PointerType>(RethrowFn->getType())
1487 ->getElementType());
1488 llvm::Value *SavedExnVar = 0;
1489 if (RethrowFnTy->getNumParams())
1490 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001491
John McCallf1549f62010-07-06 01:34:17 +00001492 // A finally block is a statement which must be executed on any edge
1493 // out of a given scope. Unlike a cleanup, the finally block may
1494 // contain arbitrary control flow leading out of itself. In
1495 // addition, finally blocks should always be executed, even if there
1496 // are no catch handlers higher on the stack. Therefore, we
1497 // surround the protected scope with a combination of a normal
1498 // cleanup (to catch attempts to break out of the block via normal
1499 // control flow) and an EH catch-all (semantically "outside" any try
1500 // statement to which the finally block might have been attached).
1501 // The finally block itself is generated in the context of a cleanup
1502 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001503
John McCallf1549f62010-07-06 01:34:17 +00001504 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001505
John McCallf1549f62010-07-06 01:34:17 +00001506 // Jump destination for performing the finally block on an exception
1507 // edge. We'll never actually reach this block, so unreachable is
1508 // fine.
1509 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001510
John McCallf1549f62010-07-06 01:34:17 +00001511 // Whether the finally block is being executed for EH purposes.
1512 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1513 "finally.for-eh");
1514 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001515
John McCallf1549f62010-07-06 01:34:17 +00001516 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001517 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1518 ForEHVar, EndCatchFn,
1519 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001520
1521 // Enter a catch-all scope.
1522 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1523 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1524 Builder.SetInsertPoint(CatchAllBB);
1525
1526 // If there's a begin-catch function, call it.
1527 if (BeginCatchFn) {
1528 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1529 ->setDoesNotThrow();
1530 }
1531
1532 // If we need to remember the exception pointer to rethrow later, do so.
1533 if (SavedExnVar) {
1534 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1535 Builder.CreateStore(SavedExn, SavedExnVar);
1536 }
1537
1538 // Tell the finally block that we're in EH.
1539 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1540
1541 // Thread a jump through the finally cleanup.
1542 EmitBranchThroughCleanup(RethrowDest);
1543
1544 Builder.restoreIP(SavedIP);
1545
1546 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1547 CatchScope->setCatchAllHandler(0, CatchAllBB);
1548
1549 return Info;
1550}
1551
1552void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1553 // Leave the finally catch-all.
1554 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1555 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1556 EHStack.popCatch();
1557
1558 // And leave the normal cleanup.
1559 PopCleanupBlock();
1560
1561 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1562 EmitBlock(CatchAllBB, true);
1563
1564 Builder.restoreIP(SavedIP);
1565}
1566
1567llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1568 if (TerminateLandingPad)
1569 return TerminateLandingPad;
1570
1571 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1572
1573 // This will get inserted at the end of the function.
1574 TerminateLandingPad = createBasicBlock("terminate.lpad");
1575 Builder.SetInsertPoint(TerminateLandingPad);
1576
1577 // Tell the backend that this is a landing pad.
1578 llvm::CallInst *Exn =
1579 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1580 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001581
1582 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001583
1584 // Tell the backend what the exception table should be:
1585 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001586 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001587 getCatchAllValue(*this) };
1588 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1589 Args, Args+3, "eh.selector")
1590 ->setDoesNotThrow();
1591
1592 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1593 TerminateCall->setDoesNotReturn();
1594 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001595 CGF.Builder.CreateUnreachable();
1596
John McCallf1549f62010-07-06 01:34:17 +00001597 // Restore the saved insertion state.
1598 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001599
John McCallf1549f62010-07-06 01:34:17 +00001600 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001601}
Mike Stump9b39c512009-12-09 22:59:31 +00001602
1603llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001604 if (TerminateHandler)
1605 return TerminateHandler;
1606
John McCallf1549f62010-07-06 01:34:17 +00001607 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001608
John McCallf1549f62010-07-06 01:34:17 +00001609 // Set up the terminate handler. This block is inserted at the very
1610 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001611 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001612 Builder.SetInsertPoint(TerminateHandler);
1613 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001614 TerminateCall->setDoesNotReturn();
1615 TerminateCall->setDoesNotThrow();
1616 Builder.CreateUnreachable();
1617
John McCall3d3ec1c2010-04-21 10:05:39 +00001618 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001619 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001620
Mike Stump9b39c512009-12-09 22:59:31 +00001621 return TerminateHandler;
1622}
John McCallf1549f62010-07-06 01:34:17 +00001623
John McCallff8e1152010-07-23 21:56:41 +00001624CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1625 if (RethrowBlock.isValid()) return RethrowBlock;
1626
1627 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1628
1629 // We emit a jump to a notional label at the outermost unwind state.
1630 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1631 Builder.SetInsertPoint(Unwind);
1632
1633 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1634
1635 // This can always be a call because we necessarily didn't find
1636 // anything on the EH stack which needs our help.
John McCallb2593832010-09-16 06:16:50 +00001637 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCallff8e1152010-07-23 21:56:41 +00001638 llvm::Constant *RethrowFn;
John McCallb2593832010-09-16 06:16:50 +00001639 if (!RethrowName.empty())
John McCallff8e1152010-07-23 21:56:41 +00001640 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1641 else
1642 RethrowFn = getUnwindResumeOrRethrowFn();
1643
1644 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1645 ->setDoesNotReturn();
1646 Builder.CreateUnreachable();
1647
1648 Builder.restoreIP(SavedIP);
1649
1650 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1651 return RethrowBlock;
1652}
1653
John McCall1f0fca52010-07-21 07:22:38 +00001654EHScopeStack::Cleanup::~Cleanup() {
1655 llvm_unreachable("Cleanup is indestructable");
John McCall3e29f962010-07-13 23:19:49 +00001656}