blob: 71a078f929a5b230f9dc30421988573bbed0df8a [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 {
John McCallda65ea82010-07-13 20:32:21 +000061 if (isa<EHLazyCleanupScope>(*it)) {
62 if (cast<EHLazyCleanupScope>(*it).isEHCleanup())
63 return stabilize(it);
64 return cast<EHLazyCleanupScope>(*it).getEnclosingEHCleanup();
65 }
John McCallf1549f62010-07-06 01:34:17 +000066 ++it;
67 } while (it != end());
68 return stable_end();
69}
70
71
John McCallda65ea82010-07-13 20:32:21 +000072void *EHScopeStack::pushLazyCleanup(CleanupKind Kind, size_t Size) {
73 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
74 char *Buffer = allocate(EHLazyCleanupScope::getSizeForCleanupSize(Size));
75 bool IsNormalCleanup = Kind != EHCleanup;
76 bool IsEHCleanup = Kind != NormalCleanup;
77 EHLazyCleanupScope *Scope =
78 new (Buffer) EHLazyCleanupScope(IsNormalCleanup,
79 IsEHCleanup,
80 Size,
81 BranchFixups.size(),
82 InnermostNormalCleanup,
83 InnermostEHCleanup);
84 if (IsNormalCleanup)
85 InnermostNormalCleanup = stable_begin();
86 if (IsEHCleanup)
87 InnermostEHCleanup = stable_begin();
88
89 return Scope->getCleanupBuffer();
90}
91
John McCallf1549f62010-07-06 01:34:17 +000092void EHScopeStack::popCleanup() {
93 assert(!empty() && "popping exception stack when not empty");
94
John McCall7495f222010-07-21 07:11:21 +000095 assert(isa<EHLazyCleanupScope>(*begin()));
96 EHLazyCleanupScope &Cleanup = cast<EHLazyCleanupScope>(*begin());
97 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
98 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
99 StartOfData += Cleanup.getAllocatedSize();
John McCallf1549f62010-07-06 01:34:17 +0000100
101 // Check whether we can shrink the branch-fixups stack.
102 if (!BranchFixups.empty()) {
103 // If we no longer have any normal cleanups, all the fixups are
104 // complete.
105 if (!hasNormalCleanups())
106 BranchFixups.clear();
107
108 // Otherwise we can still trim out unnecessary nulls.
109 else
110 popNullFixups();
111 }
112}
113
114EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
115 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
116 CatchDepth++;
117 return new (Buffer) EHFilterScope(NumFilters);
118}
119
120void EHScopeStack::popFilter() {
121 assert(!empty() && "popping exception stack when not empty");
122
123 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
124 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
125
126 assert(CatchDepth > 0 && "mismatched filter push/pop");
127 CatchDepth--;
128}
129
130EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
131 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
132 CatchDepth++;
133 return new (Buffer) EHCatchScope(NumHandlers);
134}
135
136void EHScopeStack::pushTerminate() {
137 char *Buffer = allocate(EHTerminateScope::getSize());
138 CatchDepth++;
139 new (Buffer) EHTerminateScope();
140}
141
142/// Remove any 'null' fixups on the stack. However, we can't pop more
143/// fixups than the fixup depth on the innermost normal cleanup, or
144/// else fixups that we try to add to that cleanup will end up in the
145/// wrong place. We *could* try to shrink fixup depths, but that's
146/// actually a lot of work for little benefit.
147void EHScopeStack::popNullFixups() {
148 // We expect this to only be called when there's still an innermost
149 // normal cleanup; otherwise there really shouldn't be any fixups.
150 assert(hasNormalCleanups());
151
152 EHScopeStack::iterator it = find(InnermostNormalCleanup);
John McCall7495f222010-07-21 07:11:21 +0000153 unsigned MinSize = cast<EHLazyCleanupScope>(*it).getFixupDepth();
John McCallf1549f62010-07-06 01:34:17 +0000154 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
155
156 while (BranchFixups.size() > MinSize &&
157 BranchFixups.back().Destination == 0)
158 BranchFixups.pop_back();
159}
160
161void EHScopeStack::resolveBranchFixups(llvm::BasicBlock *Dest) {
162 assert(Dest && "null block passed to resolveBranchFixups");
163
164 if (BranchFixups.empty()) return;
165 assert(hasNormalCleanups() &&
166 "branch fixups exist with no normal cleanups on stack");
167
168 for (unsigned I = 0, E = BranchFixups.size(); I != E; ++I)
169 if (BranchFixups[I].Destination == Dest)
170 BranchFixups[I].Destination = 0;
171
172 popNullFixups();
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)
276 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
277 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,
291 const char *Name) {
292 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");
303const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
304const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
305const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
306const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
307 "objc_exception_throw");
308
309static const EHPersonality &getCPersonality(const LangOptions &L) {
310 return EHPersonality::GNU_C;
311}
312
313static const EHPersonality &getObjCPersonality(const LangOptions &L) {
314 if (L.NeXTRuntime) {
315 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
316 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000317 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000318 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000319 }
320}
321
John McCall8262b6a2010-07-17 00:43:08 +0000322static const EHPersonality &getCXXPersonality(const LangOptions &L) {
323 if (L.SjLjExceptions)
324 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000325 else
John McCall8262b6a2010-07-17 00:43:08 +0000326 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000327}
328
329/// Determines the personality function to use when both C++
330/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000331static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000332 // The ObjC personality defers to the C++ personality for non-ObjC
333 // handlers. Unlike the C++ case, we use the same personality
334 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000335 if (L.NeXTRuntime) {
336 if (L.ObjCNonFragileABI)
337 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000338
339 // In the fragile ABI, just use C++ exception handling and hope
340 // they're not doing crazy exception mixing.
341 else
John McCall8262b6a2010-07-17 00:43:08 +0000342 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000343 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000344
John McCall8262b6a2010-07-17 00:43:08 +0000345 // The GNU runtime's personality function inherently doesn't support
346 // mixed EH. Use the C++ personality just to avoid returning null.
347 return getCXXPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000348}
349
John McCall8262b6a2010-07-17 00:43:08 +0000350const EHPersonality &EHPersonality::get(const LangOptions &L) {
351 if (L.CPlusPlus && L.ObjC1)
352 return getObjCXXPersonality(L);
353 else if (L.CPlusPlus)
354 return getCXXPersonality(L);
355 else if (L.ObjC1)
356 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000357 else
John McCall8262b6a2010-07-17 00:43:08 +0000358 return getCPersonality(L);
359}
John McCallf1549f62010-07-06 01:34:17 +0000360
John McCall8262b6a2010-07-17 00:43:08 +0000361static llvm::Constant *getPersonalityFn(CodeGenFunction &CGF,
362 const EHPersonality &Personality) {
363 const char *Name = Personality.getPersonalityFnName();
364
365 llvm::Constant *Fn =
John McCallf1549f62010-07-06 01:34:17 +0000366 CGF.CGM.CreateRuntimeFunction(llvm::FunctionType::get(
367 llvm::Type::getInt32Ty(
368 CGF.CGM.getLLVMContext()),
369 true),
370 Name);
John McCall8262b6a2010-07-17 00:43:08 +0000371 return llvm::ConstantExpr::getBitCast(Fn, CGF.CGM.PtrToInt8Ty);
John McCallf1549f62010-07-06 01:34:17 +0000372}
373
374/// Returns the value to inject into a selector to indicate the
375/// presence of a catch-all.
376static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
377 // Possibly we should use @llvm.eh.catch.all.value here.
378 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
379}
380
381/// Returns the value to inject into a selector to indicate the
382/// presence of a cleanup.
383static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
384 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000385}
386
John McCall09faeab2010-07-13 21:17:51 +0000387namespace {
388 /// A cleanup to free the exception object if its initialization
389 /// throws.
390 struct FreeExceptionCleanup : EHScopeStack::LazyCleanup {
391 FreeExceptionCleanup(llvm::Value *ShouldFreeVar,
392 llvm::Value *ExnLocVar)
393 : ShouldFreeVar(ShouldFreeVar), ExnLocVar(ExnLocVar) {}
394
395 llvm::Value *ShouldFreeVar;
396 llvm::Value *ExnLocVar;
397
398 void Emit(CodeGenFunction &CGF, bool IsForEH) {
399 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
400 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
401
402 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
403 "should-free-exnobj");
404 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
405 CGF.EmitBlock(FreeBB);
406 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
407 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
408 ->setDoesNotThrow();
409 CGF.EmitBlock(DoneBB);
410 }
411 };
412}
413
John McCallac418162010-04-22 01:10:34 +0000414// Emits an exception expression into the given location. This
415// differs from EmitAnyExprToMem only in that, if a final copy-ctor
416// call is required, an exception within that copy ctor causes
417// std::terminate to be invoked.
418static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
419 llvm::Value *ExnLoc) {
420 // We want to release the allocated exception object if this
421 // expression throws. We do this by pushing an EH-only cleanup
422 // block which, furthermore, deactivates itself after the expression
423 // is complete.
424 llvm::AllocaInst *ShouldFreeVar =
425 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
426 "should-free-exnobj.var");
427 CGF.InitTempAlloca(ShouldFreeVar,
428 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump0f590be2009-12-01 03:41:18 +0000429
John McCallac418162010-04-22 01:10:34 +0000430 // A variable holding the exception pointer. This is necessary
431 // because the throw expression does not necessarily dominate the
432 // cleanup, for example if it appears in a conditional expression.
433 llvm::AllocaInst *ExnLocVar =
434 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump8755ec32009-12-10 00:06:18 +0000435
John McCallf1549f62010-07-06 01:34:17 +0000436 // Make sure the exception object is cleaned up if there's an
437 // exception during initialization.
John McCall09faeab2010-07-13 21:17:51 +0000438 // FIXME: stmt expressions might require this to be a normal
439 // cleanup, too.
440 CGF.EHStack.pushLazyCleanup<FreeExceptionCleanup>(EHCleanup,
441 ShouldFreeVar,
442 ExnLocVar);
John McCallf1549f62010-07-06 01:34:17 +0000443 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000444
445 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
446 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
447 ShouldFreeVar);
448
449 // __cxa_allocate_exception returns a void*; we need to cast this
450 // to the appropriate type for the object.
451 const llvm::Type *Ty = CGF.ConvertType(E->getType())->getPointerTo();
452 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
453
454 // FIXME: this isn't quite right! If there's a final unelided call
455 // to a copy constructor, then according to [except.terminate]p1 we
456 // must call std::terminate() if that constructor throws, because
457 // technically that copy occurs after the exception expression is
458 // evaluated but before the exception is caught. But the best way
459 // to handle that is to teach EmitAggExpr to do the final copy
460 // differently if it can't be elided.
461 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false);
462
463 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
464 ShouldFreeVar);
465
John McCallf1549f62010-07-06 01:34:17 +0000466 // Technically, the exception object is like a temporary; it has to
467 // be cleaned up when its full-expression is complete.
468 // Unfortunately, the AST represents full-expressions by creating a
469 // CXXExprWithTemporaries, which it only does when there are actually
470 // temporaries.
471 //
472 // If any cleanups have been added since we pushed ours, they must
473 // be from temporaries; this will get popped at the same time.
474 // Otherwise we need to pop ours off. FIXME: this is very brittle.
475 if (Cleanup == CGF.EHStack.stable_begin())
476 CGF.PopCleanupBlock();
Mike Stump0f590be2009-12-01 03:41:18 +0000477}
478
John McCallf1549f62010-07-06 01:34:17 +0000479llvm::Value *CodeGenFunction::getExceptionSlot() {
480 if (!ExceptionSlot) {
481 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
482 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000483 }
John McCallf1549f62010-07-06 01:34:17 +0000484 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000485}
486
Anders Carlsson756b5c42009-10-30 01:42:31 +0000487void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000488 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000489 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000490 Builder.CreateInvoke(getReThrowFn(*this),
491 getUnreachableBlock(),
492 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000493 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000494 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000495 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000496 Builder.CreateUnreachable();
497 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000498
499 // Clear the insertion point to indicate we are in unreachable code.
500 Builder.ClearInsertionPoint();
Anders Carlssond3379292009-10-30 02:27:02 +0000501 return;
502 }
Mike Stump8755ec32009-12-10 00:06:18 +0000503
Anders Carlssond3379292009-10-30 02:27:02 +0000504 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000505
Anders Carlssond3379292009-10-30 02:27:02 +0000506 // Now allocate the exception object.
507 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000508 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000509
Anders Carlssond3379292009-10-30 02:27:02 +0000510 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000511 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000512 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000513 llvm::ConstantInt::get(SizeTy, TypeSize),
514 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000515 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000516
John McCallac418162010-04-22 01:10:34 +0000517 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000518
Anders Carlssond3379292009-10-30 02:27:02 +0000519 // Now throw the exception.
520 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall9dffe6f2010-04-30 01:15:21 +0000521 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
John McCallac418162010-04-22 01:10:34 +0000522
523 // The address of the destructor. If the exception type has a
524 // trivial destructor (or isn't a record), we just pass null.
525 llvm::Constant *Dtor = 0;
526 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
527 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
528 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000529 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000530 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
531 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
532 }
533 }
534 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000535
Mike Stump0a3816e2009-12-04 01:51:45 +0000536 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000537 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000538 Builder.CreateInvoke3(getThrowFn(*this),
539 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000540 ExceptionPtr, TypeInfo, Dtor);
541 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000542 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000543 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000544 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
545 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000546 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000547 }
Mike Stump8755ec32009-12-10 00:06:18 +0000548
Anders Carlssond3379292009-10-30 02:27:02 +0000549 // Clear the insertion point to indicate we are in unreachable code.
550 Builder.ClearInsertionPoint();
Mike Stumpc2ab4862009-12-07 20:12:14 +0000551
552 // FIXME: For now, emit a dummy basic block because expr emitters in generally
553 // are not ready to handle emitting expressions at unreachable points.
554 EnsureInsertPoint();
Anders Carlsson756b5c42009-10-30 01:42:31 +0000555}
Mike Stump2bf701e2009-11-20 23:44:51 +0000556
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000557void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000558 if (!Exceptions)
559 return;
560
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000561 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
562 if (FD == 0)
563 return;
564 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
565 if (Proto == 0)
566 return;
567
568 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
569
570 if (!Proto->hasExceptionSpec())
571 return;
572
John McCallf1549f62010-07-06 01:34:17 +0000573 unsigned NumExceptions = Proto->getNumExceptions();
574 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000575
John McCallf1549f62010-07-06 01:34:17 +0000576 for (unsigned I = 0; I != NumExceptions; ++I) {
577 QualType Ty = Proto->getExceptionType(I);
578 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
John McCall9dffe6f2010-04-30 01:15:21 +0000579 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
John McCallf1549f62010-07-06 01:34:17 +0000580 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000581 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000582}
583
584void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000585 if (!Exceptions)
586 return;
587
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000588 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
589 if (FD == 0)
590 return;
591 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
592 if (Proto == 0)
593 return;
594
595 if (!Proto->hasExceptionSpec())
596 return;
597
John McCallf1549f62010-07-06 01:34:17 +0000598 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000599}
600
Mike Stump2bf701e2009-11-20 23:44:51 +0000601void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000602 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000603 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000604 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000605}
606
John McCall59a70002010-07-07 06:56:46 +0000607void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000608 unsigned NumHandlers = S.getNumHandlers();
609 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000610
John McCallf1549f62010-07-06 01:34:17 +0000611 for (unsigned I = 0; I != NumHandlers; ++I) {
612 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000613
John McCallf1549f62010-07-06 01:34:17 +0000614 llvm::BasicBlock *Handler = createBasicBlock("catch");
615 if (C->getExceptionDecl()) {
616 // FIXME: Dropping the reference type on the type into makes it
617 // impossible to correctly implement catch-by-reference
618 // semantics for pointers. Unfortunately, this is what all
619 // existing compilers do, and it's not clear that the standard
620 // personality routine is capable of doing this right. See C++ DR 388:
621 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
622 QualType CaughtType = C->getCaughtType();
623 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
624 llvm::Value *TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, true);
625 CatchScope->setHandler(I, TypeInfo, Handler);
626 } else {
627 // No exception decl indicates '...', a catch-all.
628 CatchScope->setCatchAllHandler(I, Handler);
629 }
630 }
John McCallf1549f62010-07-06 01:34:17 +0000631}
632
633/// Check whether this is a non-EH scope, i.e. a scope which doesn't
634/// affect exception handling. Currently, the only non-EH scopes are
635/// normal-only cleanup scopes.
636static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000637 switch (S.getKind()) {
John McCallda65ea82010-07-13 20:32:21 +0000638 case EHScope::LazyCleanup:
639 return !cast<EHLazyCleanupScope>(S).isEHCleanup();
640 case EHScope::Filter:
641 case EHScope::Catch:
642 case EHScope::Terminate:
643 return false;
644 }
645
646 // Suppress warning.
647 return false;
John McCallf1549f62010-07-06 01:34:17 +0000648}
649
650llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
651 assert(EHStack.requiresLandingPad());
652 assert(!EHStack.empty());
653
John McCallda65ea82010-07-13 20:32:21 +0000654 if (!Exceptions)
655 return 0;
656
John McCallf1549f62010-07-06 01:34:17 +0000657 // Check the innermost scope for a cached landing pad. If this is
658 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
659 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
660 if (LP) return LP;
661
662 // Build the landing pad for this scope.
663 LP = EmitLandingPad();
664 assert(LP);
665
666 // Cache the landing pad on the innermost scope. If this is a
667 // non-EH scope, cache the landing pad on the enclosing scope, too.
668 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
669 ir->setCachedLandingPad(LP);
670 if (!isNonEHScope(*ir)) break;
671 }
672
673 return LP;
674}
675
676llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
677 assert(EHStack.requiresLandingPad());
678
679 // This function contains a hack to work around a design flaw in
680 // LLVM's EH IR which breaks semantics after inlining. This same
681 // hack is implemented in llvm-gcc.
682 //
683 // The LLVM EH abstraction is basically a thin veneer over the
684 // traditional GCC zero-cost design: for each range of instructions
685 // in the function, there is (at most) one "landing pad" with an
686 // associated chain of EH actions. A language-specific personality
687 // function interprets this chain of actions and (1) decides whether
688 // or not to resume execution at the landing pad and (2) if so,
689 // provides an integer indicating why it's stopping. In LLVM IR,
690 // the association of a landing pad with a range of instructions is
691 // achieved via an invoke instruction, the chain of actions becomes
692 // the arguments to the @llvm.eh.selector call, and the selector
693 // call returns the integer indicator. Other than the required
694 // presence of two intrinsic function calls in the landing pad,
695 // the IR exactly describes the layout of the output code.
696 //
697 // A principal advantage of this design is that it is completely
698 // language-agnostic; in theory, the LLVM optimizers can treat
699 // landing pads neutrally, and targets need only know how to lower
700 // the intrinsics to have a functioning exceptions system (assuming
701 // that platform exceptions follow something approximately like the
702 // GCC design). Unfortunately, landing pads cannot be combined in a
703 // language-agnostic way: given selectors A and B, there is no way
704 // to make a single landing pad which faithfully represents the
705 // semantics of propagating an exception first through A, then
706 // through B, without knowing how the personality will interpret the
707 // (lowered form of the) selectors. This means that inlining has no
708 // choice but to crudely chain invokes (i.e., to ignore invokes in
709 // the inlined function, but to turn all unwindable calls into
710 // invokes), which is only semantically valid if every unwind stops
711 // at every landing pad.
712 //
713 // Therefore, the invoke-inline hack is to guarantee that every
714 // landing pad has a catch-all.
715 const bool UseInvokeInlineHack = true;
716
717 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
718 assert(ir != EHStack.end() &&
719 "stack requiring landing pad is nothing but non-EH scopes?");
720
721 // If this is a terminate scope, just use the singleton terminate
722 // landing pad.
723 if (isa<EHTerminateScope>(*ir))
724 return getTerminateLandingPad();
725
726 // If this isn't an EH scope, iterate; otherwise break out.
727 if (!isNonEHScope(*ir)) break;
728 ++ir;
729
730 // We haven't checked this scope for a cached landing pad yet.
731 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
732 return LP;
733 }
734
735 // Save the current IR generation state.
736 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
737
John McCall8262b6a2010-07-17 00:43:08 +0000738 const EHPersonality &Personality =
739 EHPersonality::get(CGF.CGM.getLangOptions());
740
John McCallf1549f62010-07-06 01:34:17 +0000741 // Create and configure the landing pad.
742 llvm::BasicBlock *LP = createBasicBlock("lpad");
743 EmitBlock(LP);
744
745 // Save the exception pointer. It's safe to use a single exception
746 // pointer per function because EH cleanups can never have nested
747 // try/catches.
748 llvm::CallInst *Exn =
749 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
750 Exn->setDoesNotThrow();
751 Builder.CreateStore(Exn, getExceptionSlot());
752
753 // Build the selector arguments.
754 llvm::SmallVector<llvm::Value*, 8> EHSelector;
755 EHSelector.push_back(Exn);
John McCall8262b6a2010-07-17 00:43:08 +0000756 EHSelector.push_back(getPersonalityFn(*this, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000757
758 // Accumulate all the handlers in scope.
759 llvm::DenseMap<llvm::Value*, JumpDest> EHHandlers;
760 JumpDest CatchAll;
761 bool HasEHCleanup = false;
762 bool HasEHFilter = false;
763 llvm::SmallVector<llvm::Value*, 8> EHFilters;
764 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
765 I != E; ++I) {
766
767 switch (I->getKind()) {
John McCallda65ea82010-07-13 20:32:21 +0000768 case EHScope::LazyCleanup:
769 if (!HasEHCleanup)
770 HasEHCleanup = cast<EHLazyCleanupScope>(*I).isEHCleanup();
771 // We otherwise don't care about cleanups.
772 continue;
773
John McCallf1549f62010-07-06 01:34:17 +0000774 case EHScope::Filter: {
775 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
776 assert(!CatchAll.Block && "EH filter reached after catch-all");
777
778 // Filter scopes get added to the selector in wierd ways.
779 EHFilterScope &Filter = cast<EHFilterScope>(*I);
780 HasEHFilter = true;
781
782 // Add all the filter values which we aren't already explicitly
783 // catching.
784 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
785 llvm::Value *FV = Filter.getFilter(I);
786 if (!EHHandlers.count(FV))
787 EHFilters.push_back(FV);
788 }
789 goto done;
790 }
791
792 case EHScope::Terminate:
793 // Terminate scopes are basically catch-alls.
794 assert(!CatchAll.Block);
795 CatchAll.Block = getTerminateHandler();
796 CatchAll.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
797 goto done;
798
799 case EHScope::Catch:
800 break;
801 }
802
803 EHCatchScope &Catch = cast<EHCatchScope>(*I);
804 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
805 EHCatchScope::Handler Handler = Catch.getHandler(HI);
806
807 // Catch-all. We should only have one of these per catch.
808 if (!Handler.Type) {
809 assert(!CatchAll.Block);
810 CatchAll.Block = Handler.Block;
811 CatchAll.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
812 continue;
813 }
814
815 // Check whether we already have a handler for this type.
816 JumpDest &Dest = EHHandlers[Handler.Type];
817 if (Dest.Block) continue;
818
819 EHSelector.push_back(Handler.Type);
820 Dest.Block = Handler.Block;
821 Dest.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
822 }
823
824 // Stop if we found a catch-all.
825 if (CatchAll.Block) break;
826 }
827
828 done:
829 unsigned LastToEmitInLoop = EHSelector.size();
830
831 // If we have a catch-all, add null to the selector.
832 if (CatchAll.Block) {
833 EHSelector.push_back(getCatchAllValue(CGF));
834
835 // If we have an EH filter, we need to add those handlers in the
836 // right place in the selector, which is to say, at the end.
837 } else if (HasEHFilter) {
838 // Create a filter expression: an integer constant saying how many
839 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
840 // followed by the filter types. The personality routine only
841 // lands here if the filter doesn't match.
842 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
843 EHFilters.size() + 1));
844 EHSelector.append(EHFilters.begin(), EHFilters.end());
845
846 // Also check whether we need a cleanup.
847 if (UseInvokeInlineHack || HasEHCleanup)
848 EHSelector.push_back(UseInvokeInlineHack
849 ? getCatchAllValue(CGF)
850 : getCleanupValue(CGF));
851
852 // Otherwise, signal that we at least have cleanups.
853 } else if (UseInvokeInlineHack || HasEHCleanup) {
854 EHSelector.push_back(UseInvokeInlineHack
855 ? getCatchAllValue(CGF)
856 : getCleanupValue(CGF));
857 } else {
858 assert(LastToEmitInLoop > 2);
859 LastToEmitInLoop--;
860 }
861
862 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
863
864 // Tell the backend how to generate the landing pad.
865 llvm::CallInst *Selection =
866 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
867 EHSelector.begin(), EHSelector.end(), "eh.selector");
868 Selection->setDoesNotThrow();
869
870 // Select the right handler.
871 llvm::Value *llvm_eh_typeid_for =
872 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
873
874 // The results of llvm_eh_typeid_for aren't reliable --- at least
875 // not locally --- so we basically have to do this as an 'if' chain.
876 // We walk through the first N-1 catch clauses, testing and chaining,
877 // and then fall into the final clause (which is either a cleanup, a
878 // filter (possibly with a cleanup), a catch-all, or another catch).
879 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
880 llvm::Value *Type = EHSelector[I];
881 JumpDest Dest = EHHandlers[Type];
882 assert(Dest.Block && "no handler entry for value in selector?");
883
884 // Figure out where to branch on a match. As a debug code-size
885 // optimization, if the scope depth matches the innermost cleanup,
886 // we branch directly to the catch handler.
887 llvm::BasicBlock *Match = Dest.Block;
888 bool MatchNeedsCleanup = Dest.ScopeDepth != EHStack.getInnermostEHCleanup();
889 if (MatchNeedsCleanup)
890 Match = createBasicBlock("eh.match");
891
892 llvm::BasicBlock *Next = createBasicBlock("eh.next");
893
894 // Check whether the exception matches.
895 llvm::CallInst *Id
896 = Builder.CreateCall(llvm_eh_typeid_for,
897 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
898 Id->setDoesNotThrow();
899 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
900 Match, Next);
901
902 // Emit match code if necessary.
903 if (MatchNeedsCleanup) {
904 EmitBlock(Match);
905 EmitBranchThroughEHCleanup(Dest);
906 }
907
908 // Continue to the next match.
909 EmitBlock(Next);
910 }
911
912 // Emit the final case in the selector.
913 // This might be a catch-all....
914 if (CatchAll.Block) {
915 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
916 EmitBranchThroughEHCleanup(CatchAll);
917
918 // ...or an EH filter...
919 } else if (HasEHFilter) {
920 llvm::Value *SavedSelection = Selection;
921
922 // First, unwind out to the outermost scope if necessary.
923 if (EHStack.hasEHCleanups()) {
924 // The end here might not dominate the beginning, so we might need to
925 // save the selector if we need it.
926 llvm::AllocaInst *SelectorVar = 0;
927 if (HasEHCleanup) {
928 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
929 Builder.CreateStore(Selection, SelectorVar);
930 }
931
932 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
933 EmitBranchThroughEHCleanup(JumpDest(CleanupContBB, EHStack.stable_end()));
934 EmitBlock(CleanupContBB);
935
936 if (HasEHCleanup)
937 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
938 }
939
940 // If there was a cleanup, we'll need to actually check whether we
941 // landed here because the filter triggered.
942 if (UseInvokeInlineHack || HasEHCleanup) {
943 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
944 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
945
946 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
947 llvm::Value *FailsFilter =
948 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
949 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
950
951 // The rethrow block is where we land if this was a cleanup.
952 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
953 EmitBlock(RethrowBB);
954 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
955 Builder.CreateLoad(getExceptionSlot()))
956 ->setDoesNotReturn();
957 Builder.CreateUnreachable();
958
959 EmitBlock(UnexpectedBB);
960 }
961
962 // Call __cxa_call_unexpected. This doesn't need to be an invoke
963 // because __cxa_call_unexpected magically filters exceptions
964 // according to the last landing pad the exception was thrown
965 // into. Seriously.
966 Builder.CreateCall(getUnexpectedFn(*this),
967 Builder.CreateLoad(getExceptionSlot()))
968 ->setDoesNotReturn();
969 Builder.CreateUnreachable();
970
971 // ...or a normal catch handler...
972 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
973 llvm::Value *Type = EHSelector.back();
974 EmitBranchThroughEHCleanup(EHHandlers[Type]);
975
976 // ...or a cleanup.
977 } else {
978 // We emit a jump to a notional label at the outermost unwind state.
979 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
980 JumpDest Dest(Unwind, EHStack.stable_end());
981 EmitBranchThroughEHCleanup(Dest);
982
983 // The unwind block. We have to reload the exception here because
984 // we might have unwound through arbitrary blocks, so the landing
985 // pad might not dominate.
986 EmitBlock(Unwind);
987
988 // This can always be a call because we necessarily didn't find
989 // anything on the EH stack which needs our help.
John McCall8262b6a2010-07-17 00:43:08 +0000990 llvm::Constant *RethrowFn;
991 if (const char *RethrowName = Personality.getCatchallRethrowFnName())
992 RethrowFn = getCatchallRethrowFn(CGF, RethrowName);
993 else
994 RethrowFn = getUnwindResumeOrRethrowFn();
995 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
John McCallf1549f62010-07-06 01:34:17 +0000996 ->setDoesNotReturn();
997 Builder.CreateUnreachable();
998 }
999
1000 // Restore the old IR generation state.
1001 Builder.restoreIP(SavedIP);
1002
1003 return LP;
1004}
1005
John McCall8e3f8612010-07-13 22:12:14 +00001006namespace {
1007 /// A cleanup to call __cxa_end_catch. In many cases, the caught
1008 /// exception type lets us state definitively that the thrown exception
1009 /// type does not have a destructor. In particular:
1010 /// - Catch-alls tell us nothing, so we have to conservatively
1011 /// assume that the thrown exception might have a destructor.
1012 /// - Catches by reference behave according to their base types.
1013 /// - Catches of non-record types will only trigger for exceptions
1014 /// of non-record types, which never have destructors.
1015 /// - Catches of record types can trigger for arbitrary subclasses
1016 /// of the caught type, so we have to assume the actual thrown
1017 /// exception type might have a throwing destructor, even if the
1018 /// caught type's destructor is trivial or nothrow.
1019 struct CallEndCatch : EHScopeStack::LazyCleanup {
1020 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
1021 bool MightThrow;
1022
1023 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1024 if (!MightThrow) {
1025 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
1026 return;
1027 }
1028
1029 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
1030 }
1031 };
1032}
1033
John McCallf1549f62010-07-06 01:34:17 +00001034/// Emits a call to __cxa_begin_catch and enters a cleanup to call
1035/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001036///
1037/// \param EndMightThrow - true if __cxa_end_catch might throw
1038static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
1039 llvm::Value *Exn,
1040 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +00001041 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
1042 Call->setDoesNotThrow();
1043
John McCall8e3f8612010-07-13 22:12:14 +00001044 CGF.EHStack.pushLazyCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +00001045
1046 return Call;
1047}
1048
1049/// A "special initializer" callback for initializing a catch
1050/// parameter during catch initialization.
1051static void InitCatchParam(CodeGenFunction &CGF,
1052 const VarDecl &CatchParam,
1053 llvm::Value *ParamAddr) {
1054 // Load the exception from where the landing pad saved it.
1055 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1056
1057 CanQualType CatchType =
1058 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
1059 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
1060
1061 // If we're catching by reference, we can just cast the object
1062 // pointer to the appropriate pointer.
1063 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +00001064 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
1065 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +00001066
John McCallf1549f62010-07-06 01:34:17 +00001067 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +00001068 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +00001069
1070 // We have no way to tell the personality function that we're
1071 // catching by reference, so if we're catching a pointer,
1072 // __cxa_begin_catch will actually return that pointer by value.
1073 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
1074 QualType PointeeType = PT->getPointeeType();
1075
1076 // When catching by reference, generally we should just ignore
1077 // this by-value pointer and use the exception object instead.
1078 if (!PointeeType->isRecordType()) {
1079
1080 // Exn points to the struct _Unwind_Exception header, which
1081 // we have to skip past in order to reach the exception data.
1082 unsigned HeaderSize =
1083 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
1084 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
1085
1086 // However, if we're catching a pointer-to-record type that won't
1087 // work, because the personality function might have adjusted
1088 // the pointer. There's actually no way for us to fully satisfy
1089 // the language/ABI contract here: we can't use Exn because it
1090 // might have the wrong adjustment, but we can't use the by-value
1091 // pointer because it's off by a level of abstraction.
1092 //
1093 // The current solution is to dump the adjusted pointer into an
1094 // alloca, which breaks language semantics (because changing the
1095 // pointer doesn't change the exception) but at least works.
1096 // The better solution would be to filter out non-exact matches
1097 // and rethrow them, but this is tricky because the rethrow
1098 // really needs to be catchable by other sites at this landing
1099 // pad. The best solution is to fix the personality function.
1100 } else {
1101 // Pull the pointer for the reference type off.
1102 const llvm::Type *PtrTy =
1103 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1104
1105 // Create the temporary and write the adjusted pointer into it.
1106 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1107 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1108 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1109
1110 // Bind the reference to the temporary.
1111 AdjustedExn = ExnPtrTmp;
1112 }
1113 }
1114
John McCallf1549f62010-07-06 01:34:17 +00001115 llvm::Value *ExnCast =
1116 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1117 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1118 return;
1119 }
1120
1121 // Non-aggregates (plus complexes).
1122 bool IsComplex = false;
1123 if (!CGF.hasAggregateLLVMType(CatchType) ||
1124 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001125 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001126
1127 // If the catch type is a pointer type, __cxa_begin_catch returns
1128 // the pointer by value.
1129 if (CatchType->hasPointerRepresentation()) {
1130 llvm::Value *CastExn =
1131 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1132 CGF.Builder.CreateStore(CastExn, ParamAddr);
1133 return;
1134 }
1135
1136 // Otherwise, it returns a pointer into the exception object.
1137
1138 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1139 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1140
1141 if (IsComplex) {
1142 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1143 ParamAddr, /*volatile*/ false);
1144 } else {
1145 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1146 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, CatchType);
1147 }
1148 return;
1149 }
1150
1151 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1152 // initializer expression.
1153
1154 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1155 assert(RD && "aggregate catch type was not a record!");
1156
1157 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1158
1159 if (RD->hasTrivialCopyConstructor()) {
John McCall8e3f8612010-07-13 22:12:14 +00001160 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001161 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1162 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1163 return;
1164 }
1165
1166 // We have to call __cxa_get_exception_ptr to get the adjusted
1167 // pointer before copying.
1168 llvm::CallInst *AdjustedExn =
1169 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1170 AdjustedExn->setDoesNotThrow();
1171 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1172
1173 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1174 assert(CD && "record has no copy constructor!");
1175 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1176
1177 CallArgList CallArgs;
1178 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1179 CD->getThisType(CGF.getContext())));
1180 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1181 CD->getParamDecl(0)->getType()));
1182
1183 const FunctionProtoType *FPT
1184 = CD->getType()->getAs<FunctionProtoType>();
1185
1186 // Call the copy ctor in a terminate scope.
1187 CGF.EHStack.pushTerminate();
1188 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1189 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1190 CGF.EHStack.popTerminate();
1191
1192 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001193 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001194}
1195
1196/// Begins a catch statement by initializing the catch variable and
1197/// calling __cxa_begin_catch.
1198static void BeginCatch(CodeGenFunction &CGF,
1199 const CXXCatchStmt *S) {
1200 // We have to be very careful with the ordering of cleanups here:
1201 // C++ [except.throw]p4:
1202 // The destruction [of the exception temporary] occurs
1203 // immediately after the destruction of the object declared in
1204 // the exception-declaration in the handler.
1205 //
1206 // So the precise ordering is:
1207 // 1. Construct catch variable.
1208 // 2. __cxa_begin_catch
1209 // 3. Enter __cxa_end_catch cleanup
1210 // 4. Enter dtor cleanup
1211 //
1212 // We do this by initializing the exception variable with a
1213 // "special initializer", InitCatchParam. Delegation sequence:
1214 // - ExitCXXTryStmt opens a RunCleanupsScope
1215 // - EmitLocalBlockVarDecl creates the variable and debug info
1216 // - InitCatchParam initializes the variable from the exception
1217 // - CallBeginCatch calls __cxa_begin_catch
1218 // - CallBeginCatch enters the __cxa_end_catch cleanup
1219 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1220 // - EmitCXXTryStmt emits the code for the catch body
1221 // - EmitCXXTryStmt close the RunCleanupsScope
1222
1223 VarDecl *CatchParam = S->getExceptionDecl();
1224 if (!CatchParam) {
1225 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001226 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001227 return;
1228 }
1229
1230 // Emit the local.
1231 CGF.EmitLocalBlockVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001232}
1233
John McCallfcd5c0c2010-07-13 22:24:23 +00001234namespace {
1235 struct CallRethrow : EHScopeStack::LazyCleanup {
1236 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1237 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1238 }
1239 };
1240}
1241
John McCall59a70002010-07-07 06:56:46 +00001242void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001243 unsigned NumHandlers = S.getNumHandlers();
1244 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1245 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001246
John McCallf1549f62010-07-06 01:34:17 +00001247 // Copy the handler blocks off before we pop the EH stack. Emitting
1248 // the handlers might scribble on this memory.
1249 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1250 memcpy(Handlers.data(), CatchScope.begin(),
1251 NumHandlers * sizeof(EHCatchScope::Handler));
1252 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001253
John McCallf1549f62010-07-06 01:34:17 +00001254 // The fall-through block.
1255 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001256
John McCallf1549f62010-07-06 01:34:17 +00001257 // We just emitted the body of the try; jump to the continue block.
1258 if (HaveInsertPoint())
1259 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001260
John McCall59a70002010-07-07 06:56:46 +00001261 // Determine if we need an implicit rethrow for all these catch handlers.
1262 bool ImplicitRethrow = false;
1263 if (IsFnTryBlock)
1264 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1265 isa<CXXConstructorDecl>(CurCodeDecl);
1266
John McCallf1549f62010-07-06 01:34:17 +00001267 for (unsigned I = 0; I != NumHandlers; ++I) {
1268 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1269 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001270
John McCallf1549f62010-07-06 01:34:17 +00001271 // Catch the exception if this isn't a catch-all.
1272 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001273
John McCallf1549f62010-07-06 01:34:17 +00001274 // Enter a cleanup scope, including the catch variable and the
1275 // end-catch.
1276 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001277
John McCallf1549f62010-07-06 01:34:17 +00001278 // Initialize the catch variable and set up the cleanups.
1279 BeginCatch(*this, C);
1280
John McCall59a70002010-07-07 06:56:46 +00001281 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001282 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1283 // called, and so it is pushed after BeginCatch.
1284 if (ImplicitRethrow)
1285 EHStack.pushLazyCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001286
John McCallf1549f62010-07-06 01:34:17 +00001287 // Perform the body of the catch.
1288 EmitStmt(C->getHandlerBlock());
1289
1290 // Fall out through the catch cleanups.
1291 CatchScope.ForceCleanup();
1292
1293 // Branch out of the try.
1294 if (HaveInsertPoint())
1295 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001296 }
1297
John McCallf1549f62010-07-06 01:34:17 +00001298 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001299}
Mike Stumpd88ea562009-12-09 03:35:49 +00001300
John McCall55b20fc2010-07-21 00:52:03 +00001301namespace {
1302 struct CallEndCatchForFinally : EHScopeStack::LazyCleanup {
1303 llvm::Value *ForEHVar;
1304 llvm::Value *EndCatchFn;
1305 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1306 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1307
1308 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1309 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1310 llvm::BasicBlock *CleanupContBB =
1311 CGF.createBasicBlock("finally.cleanup.cont");
1312
1313 llvm::Value *ShouldEndCatch =
1314 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1315 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1316 CGF.EmitBlock(EndCatchBB);
1317 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1318 CGF.EmitBlock(CleanupContBB);
1319 }
1320 };
John McCall77199712010-07-21 05:47:49 +00001321
1322 struct PerformFinally : EHScopeStack::LazyCleanup {
1323 const Stmt *Body;
1324 llvm::Value *ForEHVar;
1325 llvm::Value *EndCatchFn;
1326 llvm::Value *RethrowFn;
1327 llvm::Value *SavedExnVar;
1328
1329 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1330 llvm::Value *EndCatchFn,
1331 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1332 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1333 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1334
1335 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1336 // Enter a cleanup to call the end-catch function if one was provided.
1337 if (EndCatchFn)
1338 CGF.EHStack.pushLazyCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1339 ForEHVar, EndCatchFn);
1340
1341 // Emit the finally block.
1342 CGF.EmitStmt(Body);
1343
1344 // If the end of the finally is reachable, check whether this was
1345 // for EH. If so, rethrow.
1346 if (CGF.HaveInsertPoint()) {
1347 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1348 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1349
1350 llvm::Value *ShouldRethrow =
1351 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1352 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1353
1354 CGF.EmitBlock(RethrowBB);
1355 if (SavedExnVar) {
1356 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1357 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1358 } else {
1359 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1360 }
1361 CGF.Builder.CreateUnreachable();
1362
1363 CGF.EmitBlock(ContBB);
1364 }
1365
1366 // Leave the end-catch cleanup. As an optimization, pretend that
1367 // the fallthrough path was inaccessible; we've dynamically proven
1368 // that we're not in the EH case along that path.
1369 if (EndCatchFn) {
1370 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1371 CGF.PopCleanupBlock();
1372 CGF.Builder.restoreIP(SavedIP);
1373 }
1374
1375 // Now make sure we actually have an insertion point or the
1376 // cleanup gods will hate us.
1377 CGF.EnsureInsertPoint();
1378 }
1379 };
John McCall55b20fc2010-07-21 00:52:03 +00001380}
1381
John McCallf1549f62010-07-06 01:34:17 +00001382/// Enters a finally block for an implementation using zero-cost
1383/// exceptions. This is mostly general, but hard-codes some
1384/// language/ABI-specific behavior in the catch-all sections.
1385CodeGenFunction::FinallyInfo
1386CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1387 llvm::Constant *BeginCatchFn,
1388 llvm::Constant *EndCatchFn,
1389 llvm::Constant *RethrowFn) {
1390 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1391 "begin/end catch functions not paired");
1392 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001393
John McCallf1549f62010-07-06 01:34:17 +00001394 // The rethrow function has one of the following two types:
1395 // void (*)()
1396 // void (*)(void*)
1397 // In the latter case we need to pass it the exception object.
1398 // But we can't use the exception slot because the @finally might
1399 // have a landing pad (which would overwrite the exception slot).
1400 const llvm::FunctionType *RethrowFnTy =
1401 cast<llvm::FunctionType>(
1402 cast<llvm::PointerType>(RethrowFn->getType())
1403 ->getElementType());
1404 llvm::Value *SavedExnVar = 0;
1405 if (RethrowFnTy->getNumParams())
1406 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001407
John McCallf1549f62010-07-06 01:34:17 +00001408 // A finally block is a statement which must be executed on any edge
1409 // out of a given scope. Unlike a cleanup, the finally block may
1410 // contain arbitrary control flow leading out of itself. In
1411 // addition, finally blocks should always be executed, even if there
1412 // are no catch handlers higher on the stack. Therefore, we
1413 // surround the protected scope with a combination of a normal
1414 // cleanup (to catch attempts to break out of the block via normal
1415 // control flow) and an EH catch-all (semantically "outside" any try
1416 // statement to which the finally block might have been attached).
1417 // The finally block itself is generated in the context of a cleanup
1418 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001419
John McCallf1549f62010-07-06 01:34:17 +00001420 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001421
John McCallf1549f62010-07-06 01:34:17 +00001422 // Jump destination for performing the finally block on an exception
1423 // edge. We'll never actually reach this block, so unreachable is
1424 // fine.
1425 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001426
John McCallf1549f62010-07-06 01:34:17 +00001427 // Whether the finally block is being executed for EH purposes.
1428 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1429 "finally.for-eh");
1430 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001431
John McCallf1549f62010-07-06 01:34:17 +00001432 // Enter a normal cleanup which will perform the @finally block.
John McCall77199712010-07-21 05:47:49 +00001433 EHStack.pushLazyCleanup<PerformFinally>(NormalCleanup, Body,
1434 ForEHVar, EndCatchFn,
1435 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001436
1437 // Enter a catch-all scope.
1438 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1439 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1440 Builder.SetInsertPoint(CatchAllBB);
1441
1442 // If there's a begin-catch function, call it.
1443 if (BeginCatchFn) {
1444 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1445 ->setDoesNotThrow();
1446 }
1447
1448 // If we need to remember the exception pointer to rethrow later, do so.
1449 if (SavedExnVar) {
1450 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1451 Builder.CreateStore(SavedExn, SavedExnVar);
1452 }
1453
1454 // Tell the finally block that we're in EH.
1455 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1456
1457 // Thread a jump through the finally cleanup.
1458 EmitBranchThroughCleanup(RethrowDest);
1459
1460 Builder.restoreIP(SavedIP);
1461
1462 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1463 CatchScope->setCatchAllHandler(0, CatchAllBB);
1464
1465 return Info;
1466}
1467
1468void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1469 // Leave the finally catch-all.
1470 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1471 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1472 EHStack.popCatch();
1473
1474 // And leave the normal cleanup.
1475 PopCleanupBlock();
1476
1477 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1478 EmitBlock(CatchAllBB, true);
1479
1480 Builder.restoreIP(SavedIP);
1481}
1482
1483llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1484 if (TerminateLandingPad)
1485 return TerminateLandingPad;
1486
1487 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1488
1489 // This will get inserted at the end of the function.
1490 TerminateLandingPad = createBasicBlock("terminate.lpad");
1491 Builder.SetInsertPoint(TerminateLandingPad);
1492
1493 // Tell the backend that this is a landing pad.
1494 llvm::CallInst *Exn =
1495 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1496 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001497
1498 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001499
1500 // Tell the backend what the exception table should be:
1501 // nothing but a catch-all.
John McCall8262b6a2010-07-17 00:43:08 +00001502 llvm::Value *Args[3] = { Exn, getPersonalityFn(*this, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001503 getCatchAllValue(*this) };
1504 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1505 Args, Args+3, "eh.selector")
1506 ->setDoesNotThrow();
1507
1508 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1509 TerminateCall->setDoesNotReturn();
1510 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001511 CGF.Builder.CreateUnreachable();
1512
John McCallf1549f62010-07-06 01:34:17 +00001513 // Restore the saved insertion state.
1514 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001515
John McCallf1549f62010-07-06 01:34:17 +00001516 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001517}
Mike Stump9b39c512009-12-09 22:59:31 +00001518
1519llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001520 if (TerminateHandler)
1521 return TerminateHandler;
1522
John McCallf1549f62010-07-06 01:34:17 +00001523 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001524
John McCallf1549f62010-07-06 01:34:17 +00001525 // Set up the terminate handler. This block is inserted at the very
1526 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001527 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001528 Builder.SetInsertPoint(TerminateHandler);
1529 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001530 TerminateCall->setDoesNotReturn();
1531 TerminateCall->setDoesNotThrow();
1532 Builder.CreateUnreachable();
1533
John McCall3d3ec1c2010-04-21 10:05:39 +00001534 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001535 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001536
Mike Stump9b39c512009-12-09 22:59:31 +00001537 return TerminateHandler;
1538}
John McCallf1549f62010-07-06 01:34:17 +00001539
John McCall3e29f962010-07-13 23:19:49 +00001540EHScopeStack::LazyCleanup::~LazyCleanup() {
1541 llvm_unreachable("LazyCleanup is indestructable");
1542}