blob: 085dddd95d4f5d70ba278423e90c12757b78fd7f [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"
21
Anders Carlsson756b5c42009-10-30 01:42:31 +000022using namespace clang;
23using namespace CodeGen;
24
John McCallf1549f62010-07-06 01:34:17 +000025/// Push an entry of the given size onto this protected-scope stack.
26char *EHScopeStack::allocate(size_t Size) {
27 if (!StartOfBuffer) {
28 unsigned Capacity = 1024;
29 while (Capacity < Size) Capacity *= 2;
30 StartOfBuffer = new char[Capacity];
31 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
32 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
33 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
34 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
35
36 unsigned NewCapacity = CurrentCapacity;
37 do {
38 NewCapacity *= 2;
39 } while (NewCapacity < UsedCapacity + Size);
40
41 char *NewStartOfBuffer = new char[NewCapacity];
42 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
43 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
44 memcpy(NewStartOfData, StartOfData, UsedCapacity);
45 delete [] StartOfBuffer;
46 StartOfBuffer = NewStartOfBuffer;
47 EndOfBuffer = NewEndOfBuffer;
48 StartOfData = NewStartOfData;
49 }
50
51 assert(StartOfBuffer + Size <= StartOfData);
52 StartOfData -= Size;
53 return StartOfData;
54}
55
56EHScopeStack::stable_iterator
57EHScopeStack::getEnclosingEHCleanup(iterator it) const {
58 assert(it != end());
59 do {
60 if (isa<EHCleanupScope>(*it)) {
61 if (cast<EHCleanupScope>(*it).isEHCleanup())
62 return stabilize(it);
63 return cast<EHCleanupScope>(*it).getEnclosingEHCleanup();
64 }
65 ++it;
66 } while (it != end());
67 return stable_end();
68}
69
70
71void EHScopeStack::pushCleanup(llvm::BasicBlock *NormalEntry,
72 llvm::BasicBlock *NormalExit,
73 llvm::BasicBlock *EHEntry,
74 llvm::BasicBlock *EHExit) {
75 char *Buffer = allocate(EHCleanupScope::getSize());
76 new (Buffer) EHCleanupScope(BranchFixups.size(),
77 InnermostNormalCleanup,
78 InnermostEHCleanup,
79 NormalEntry, NormalExit, EHEntry, EHExit);
80 if (NormalEntry)
81 InnermostNormalCleanup = stable_begin();
82 if (EHEntry)
83 InnermostEHCleanup = stable_begin();
84}
85
86void EHScopeStack::popCleanup() {
87 assert(!empty() && "popping exception stack when not empty");
88
89 assert(isa<EHCleanupScope>(*begin()));
90 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
91 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
92 InnermostEHCleanup = Cleanup.getEnclosingEHCleanup();
93 StartOfData += EHCleanupScope::getSize();
94
95 // Check whether we can shrink the branch-fixups stack.
96 if (!BranchFixups.empty()) {
97 // If we no longer have any normal cleanups, all the fixups are
98 // complete.
99 if (!hasNormalCleanups())
100 BranchFixups.clear();
101
102 // Otherwise we can still trim out unnecessary nulls.
103 else
104 popNullFixups();
105 }
106}
107
108EHFilterScope *EHScopeStack::pushFilter(unsigned NumFilters) {
109 char *Buffer = allocate(EHFilterScope::getSizeForNumFilters(NumFilters));
110 CatchDepth++;
111 return new (Buffer) EHFilterScope(NumFilters);
112}
113
114void EHScopeStack::popFilter() {
115 assert(!empty() && "popping exception stack when not empty");
116
117 EHFilterScope &Filter = cast<EHFilterScope>(*begin());
118 StartOfData += EHFilterScope::getSizeForNumFilters(Filter.getNumFilters());
119
120 assert(CatchDepth > 0 && "mismatched filter push/pop");
121 CatchDepth--;
122}
123
124EHCatchScope *EHScopeStack::pushCatch(unsigned NumHandlers) {
125 char *Buffer = allocate(EHCatchScope::getSizeForNumHandlers(NumHandlers));
126 CatchDepth++;
127 return new (Buffer) EHCatchScope(NumHandlers);
128}
129
130void EHScopeStack::pushTerminate() {
131 char *Buffer = allocate(EHTerminateScope::getSize());
132 CatchDepth++;
133 new (Buffer) EHTerminateScope();
134}
135
136/// Remove any 'null' fixups on the stack. However, we can't pop more
137/// fixups than the fixup depth on the innermost normal cleanup, or
138/// else fixups that we try to add to that cleanup will end up in the
139/// wrong place. We *could* try to shrink fixup depths, but that's
140/// actually a lot of work for little benefit.
141void EHScopeStack::popNullFixups() {
142 // We expect this to only be called when there's still an innermost
143 // normal cleanup; otherwise there really shouldn't be any fixups.
144 assert(hasNormalCleanups());
145
146 EHScopeStack::iterator it = find(InnermostNormalCleanup);
147 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
148 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
149
150 while (BranchFixups.size() > MinSize &&
151 BranchFixups.back().Destination == 0)
152 BranchFixups.pop_back();
153}
154
155void EHScopeStack::resolveBranchFixups(llvm::BasicBlock *Dest) {
156 assert(Dest && "null block passed to resolveBranchFixups");
157
158 if (BranchFixups.empty()) return;
159 assert(hasNormalCleanups() &&
160 "branch fixups exist with no normal cleanups on stack");
161
162 for (unsigned I = 0, E = BranchFixups.size(); I != E; ++I)
163 if (BranchFixups[I].Destination == Dest)
164 BranchFixups[I].Destination = 0;
165
166 popNullFixups();
167}
168
Anders Carlssond3379292009-10-30 02:27:02 +0000169static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
170 // void *__cxa_allocate_exception(size_t thrown_size);
171 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
172 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000173
174 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +0000175 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
176 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000177
Anders Carlssond3379292009-10-30 02:27:02 +0000178 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
179}
180
Mike Stump99533832009-12-02 07:41:41 +0000181static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
182 // void __cxa_free_exception(void *thrown_exception);
183 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
184 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000185
186 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000187 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
188 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000189
Mike Stump99533832009-12-02 07:41:41 +0000190 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
191}
192
Anders Carlssond3379292009-10-30 02:27:02 +0000193static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +0000194 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +0000195 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +0000196
197 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
198 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000199
200 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000201 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
202 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000203
Anders Carlssond3379292009-10-30 02:27:02 +0000204 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
205}
206
Mike Stumpb4eea692009-11-20 00:56:31 +0000207static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000208 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +0000209
Mike Stump8755ec32009-12-10 00:06:18 +0000210 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +0000211 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000212
Mike Stumpb4eea692009-11-20 00:56:31 +0000213 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
214}
215
John McCallf1549f62010-07-06 01:34:17 +0000216static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
217 // void *__cxa_get_exception_ptr(void*);
218 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
219 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
220
221 const llvm::FunctionType *FTy =
222 llvm::FunctionType::get(Int8PtrTy, Args, false);
223
224 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
225}
226
Mike Stump2bf701e2009-11-20 23:44:51 +0000227static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +0000228 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +0000229
230 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
231 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000232
233 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +0000234 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000235
Mike Stump2bf701e2009-11-20 23:44:51 +0000236 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
237}
238
239static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000240 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000241
Mike Stump8755ec32009-12-10 00:06:18 +0000242 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000243 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000244
Mike Stump2bf701e2009-11-20 23:44:51 +0000245 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
246}
247
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000248static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
249 // void __cxa_call_unexepcted(void *thrown_exception);
250
251 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
252 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000253
254 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000255 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
256 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000257
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000258 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
259}
260
Douglas Gregor86a3a032010-05-16 01:24:12 +0000261llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
262 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000263 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000264
265 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000266 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000267 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000268
Douglas Gregor86a3a032010-05-16 01:24:12 +0000269 if (CGM.getLangOptions().SjLjExceptions)
270 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
271 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000272}
273
Mike Stump99533832009-12-02 07:41:41 +0000274static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
275 // void __terminate();
276
Mike Stump8755ec32009-12-10 00:06:18 +0000277 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000278 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000279
David Chisnall79a9ad82010-05-17 13:49:20 +0000280 return CGF.CGM.CreateRuntimeFunction(FTy,
281 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
282}
283
John McCallf1549f62010-07-06 01:34:17 +0000284static const char *getCPersonalityFn(CodeGenFunction &CGF) {
285 return "__gcc_personality_v0";
286}
287
288static const char *getObjCPersonalityFn(CodeGenFunction &CGF) {
289 if (CGF.CGM.getLangOptions().NeXTRuntime) {
290 if (CGF.CGM.getLangOptions().ObjCNonFragileABI)
291 return "__objc_personality_v0";
Daniel Dunbar8019c452010-05-28 19:43:36 +0000292 else
John McCallf1549f62010-07-06 01:34:17 +0000293 return getCPersonalityFn(CGF);
294 } else {
295 return "__gnu_objc_personality_v0";
296 }
297}
298
299static const char *getCXXPersonalityFn(CodeGenFunction &CGF) {
300 if (CGF.CGM.getLangOptions().SjLjExceptions)
301 return "__gxx_personality_sj0";
302 else
303 return "__gxx_personality_v0";
304}
305
306/// Determines the personality function to use when both C++
307/// and Objective-C exceptions are being caught.
308static const char *getObjCXXPersonalityFn(CodeGenFunction &CGF) {
309 // The ObjC personality defers to the C++ personality for non-ObjC
310 // handlers. Unlike the C++ case, we use the same personality
311 // function on targets using (backend-driven) SJLJ EH.
312 if (CGF.CGM.getLangOptions().NeXTRuntime) {
313 if (CGF.CGM.getLangOptions().ObjCNonFragileABI)
314 return "__objc_personality_v0";
315
316 // In the fragile ABI, just use C++ exception handling and hope
317 // they're not doing crazy exception mixing.
318 else
319 return getCXXPersonalityFn(CGF);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000320 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000321
John McCallf1549f62010-07-06 01:34:17 +0000322 // I'm pretty sure the GNU runtime doesn't support mixed EH.
323 // TODO: we don't necessarily need mixed EH here; remember what
324 // kind of exceptions we actually try to catch in this function.
325 CGF.CGM.ErrorUnsupported(CGF.CurCodeDecl,
326 "the GNU Objective C runtime does not support "
327 "catching C++ and Objective C exceptions in the "
328 "same function");
329 // Use the C++ personality just to avoid returning null.
330 return getCXXPersonalityFn(CGF);
331}
332
333static llvm::Constant *getPersonalityFn(CodeGenFunction &CGF) {
334 const char *Name;
335 const LangOptions &Opts = CGF.CGM.getLangOptions();
336 if (Opts.CPlusPlus && Opts.ObjC1)
337 Name = getObjCXXPersonalityFn(CGF);
338 else if (Opts.CPlusPlus)
339 Name = getCXXPersonalityFn(CGF);
340 else if (Opts.ObjC1)
341 Name = getObjCPersonalityFn(CGF);
342 else
343 Name = getCPersonalityFn(CGF);
344
David Chisnall79a9ad82010-05-17 13:49:20 +0000345 llvm::Constant *Personality =
John McCallf1549f62010-07-06 01:34:17 +0000346 CGF.CGM.CreateRuntimeFunction(llvm::FunctionType::get(
347 llvm::Type::getInt32Ty(
348 CGF.CGM.getLLVMContext()),
349 true),
350 Name);
351 return llvm::ConstantExpr::getBitCast(Personality, CGF.CGM.PtrToInt8Ty);
352}
353
354/// Returns the value to inject into a selector to indicate the
355/// presence of a catch-all.
356static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
357 // Possibly we should use @llvm.eh.catch.all.value here.
358 return llvm::ConstantPointerNull::get(CGF.CGM.PtrToInt8Ty);
359}
360
361/// Returns the value to inject into a selector to indicate the
362/// presence of a cleanup.
363static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
364 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000365}
366
John McCallac418162010-04-22 01:10:34 +0000367// Emits an exception expression into the given location. This
368// differs from EmitAnyExprToMem only in that, if a final copy-ctor
369// call is required, an exception within that copy ctor causes
370// std::terminate to be invoked.
371static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *E,
372 llvm::Value *ExnLoc) {
373 // We want to release the allocated exception object if this
374 // expression throws. We do this by pushing an EH-only cleanup
375 // block which, furthermore, deactivates itself after the expression
376 // is complete.
377 llvm::AllocaInst *ShouldFreeVar =
378 CGF.CreateTempAlloca(llvm::Type::getInt1Ty(CGF.getLLVMContext()),
379 "should-free-exnobj.var");
380 CGF.InitTempAlloca(ShouldFreeVar,
381 llvm::ConstantInt::getFalse(CGF.getLLVMContext()));
Mike Stump0f590be2009-12-01 03:41:18 +0000382
John McCallac418162010-04-22 01:10:34 +0000383 // A variable holding the exception pointer. This is necessary
384 // because the throw expression does not necessarily dominate the
385 // cleanup, for example if it appears in a conditional expression.
386 llvm::AllocaInst *ExnLocVar =
387 CGF.CreateTempAlloca(ExnLoc->getType(), "exnobj.var");
Mike Stump8755ec32009-12-10 00:06:18 +0000388
John McCallf1549f62010-07-06 01:34:17 +0000389 // Make sure the exception object is cleaned up if there's an
390 // exception during initialization.
391 // FIXME: StmtExprs probably force this to include a non-EH
392 // handler.
John McCallac418162010-04-22 01:10:34 +0000393 {
John McCallf1549f62010-07-06 01:34:17 +0000394 CodeGenFunction::CleanupBlock Cleanup(CGF, CodeGenFunction::EHCleanup);
John McCallac418162010-04-22 01:10:34 +0000395 llvm::BasicBlock *FreeBB = CGF.createBasicBlock("free-exnobj");
396 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("free-exnobj.done");
Mike Stumpf2945c02009-12-17 06:08:47 +0000397
John McCallac418162010-04-22 01:10:34 +0000398 llvm::Value *ShouldFree = CGF.Builder.CreateLoad(ShouldFreeVar,
399 "should-free-exnobj");
400 CGF.Builder.CreateCondBr(ShouldFree, FreeBB, DoneBB);
401 CGF.EmitBlock(FreeBB);
402 llvm::Value *ExnLocLocal = CGF.Builder.CreateLoad(ExnLocVar, "exnobj");
John McCallf1549f62010-07-06 01:34:17 +0000403 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), ExnLocLocal)
404 ->setDoesNotThrow();
John McCallac418162010-04-22 01:10:34 +0000405 CGF.EmitBlock(DoneBB);
Mike Stump0f590be2009-12-01 03:41:18 +0000406 }
John McCallf1549f62010-07-06 01:34:17 +0000407 EHScopeStack::stable_iterator Cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000408
409 CGF.Builder.CreateStore(ExnLoc, ExnLocVar);
410 CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(CGF.getLLVMContext()),
411 ShouldFreeVar);
412
413 // __cxa_allocate_exception returns a void*; we need to cast this
414 // to the appropriate type for the object.
415 const llvm::Type *Ty = CGF.ConvertType(E->getType())->getPointerTo();
416 llvm::Value *TypedExnLoc = CGF.Builder.CreateBitCast(ExnLoc, Ty);
417
418 // FIXME: this isn't quite right! If there's a final unelided call
419 // to a copy constructor, then according to [except.terminate]p1 we
420 // must call std::terminate() if that constructor throws, because
421 // technically that copy occurs after the exception expression is
422 // evaluated but before the exception is caught. But the best way
423 // to handle that is to teach EmitAggExpr to do the final copy
424 // differently if it can't be elided.
425 CGF.EmitAnyExprToMem(E, TypedExnLoc, /*Volatile*/ false);
426
427 CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(CGF.getLLVMContext()),
428 ShouldFreeVar);
429
John McCallf1549f62010-07-06 01:34:17 +0000430 // Technically, the exception object is like a temporary; it has to
431 // be cleaned up when its full-expression is complete.
432 // Unfortunately, the AST represents full-expressions by creating a
433 // CXXExprWithTemporaries, which it only does when there are actually
434 // temporaries.
435 //
436 // If any cleanups have been added since we pushed ours, they must
437 // be from temporaries; this will get popped at the same time.
438 // Otherwise we need to pop ours off. FIXME: this is very brittle.
439 if (Cleanup == CGF.EHStack.stable_begin())
440 CGF.PopCleanupBlock();
Mike Stump0f590be2009-12-01 03:41:18 +0000441}
442
John McCallf1549f62010-07-06 01:34:17 +0000443llvm::Value *CodeGenFunction::getExceptionSlot() {
444 if (!ExceptionSlot) {
445 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
446 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000447 }
John McCallf1549f62010-07-06 01:34:17 +0000448 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000449}
450
Anders Carlsson756b5c42009-10-30 01:42:31 +0000451void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000452 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000453 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000454 Builder.CreateInvoke(getReThrowFn(*this),
455 getUnreachableBlock(),
456 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000457 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000458 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000459 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000460 Builder.CreateUnreachable();
461 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000462
463 // Clear the insertion point to indicate we are in unreachable code.
464 Builder.ClearInsertionPoint();
Anders Carlssond3379292009-10-30 02:27:02 +0000465 return;
466 }
Mike Stump8755ec32009-12-10 00:06:18 +0000467
Anders Carlssond3379292009-10-30 02:27:02 +0000468 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000469
Anders Carlssond3379292009-10-30 02:27:02 +0000470 // Now allocate the exception object.
471 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000472 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000473
Anders Carlssond3379292009-10-30 02:27:02 +0000474 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000475 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000476 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000477 llvm::ConstantInt::get(SizeTy, TypeSize),
478 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000479 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000480
John McCallac418162010-04-22 01:10:34 +0000481 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000482
Anders Carlssond3379292009-10-30 02:27:02 +0000483 // Now throw the exception.
484 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall9dffe6f2010-04-30 01:15:21 +0000485 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType, true);
John McCallac418162010-04-22 01:10:34 +0000486
487 // The address of the destructor. If the exception type has a
488 // trivial destructor (or isn't a record), we just pass null.
489 llvm::Constant *Dtor = 0;
490 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
491 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
492 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000493 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000494 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
495 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
496 }
497 }
498 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000499
Mike Stump0a3816e2009-12-04 01:51:45 +0000500 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000501 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000502 Builder.CreateInvoke3(getThrowFn(*this),
503 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000504 ExceptionPtr, TypeInfo, Dtor);
505 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000506 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000507 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000508 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
509 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000510 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000511 }
Mike Stump8755ec32009-12-10 00:06:18 +0000512
Anders Carlssond3379292009-10-30 02:27:02 +0000513 // Clear the insertion point to indicate we are in unreachable code.
514 Builder.ClearInsertionPoint();
Mike Stumpc2ab4862009-12-07 20:12:14 +0000515
516 // FIXME: For now, emit a dummy basic block because expr emitters in generally
517 // are not ready to handle emitting expressions at unreachable points.
518 EnsureInsertPoint();
Anders Carlsson756b5c42009-10-30 01:42:31 +0000519}
Mike Stump2bf701e2009-11-20 23:44:51 +0000520
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000521void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000522 if (!Exceptions)
523 return;
524
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000525 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
526 if (FD == 0)
527 return;
528 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
529 if (Proto == 0)
530 return;
531
532 assert(!Proto->hasAnyExceptionSpec() && "function with parameter pack");
533
534 if (!Proto->hasExceptionSpec())
535 return;
536
John McCallf1549f62010-07-06 01:34:17 +0000537 unsigned NumExceptions = Proto->getNumExceptions();
538 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000539
John McCallf1549f62010-07-06 01:34:17 +0000540 for (unsigned I = 0; I != NumExceptions; ++I) {
541 QualType Ty = Proto->getExceptionType(I);
542 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
John McCall9dffe6f2010-04-30 01:15:21 +0000543 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType, true);
John McCallf1549f62010-07-06 01:34:17 +0000544 Filter->setFilter(I, EHType);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000545 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000546}
547
548void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlssona994ee42010-02-06 23:59:05 +0000549 if (!Exceptions)
550 return;
551
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000552 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
553 if (FD == 0)
554 return;
555 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
556 if (Proto == 0)
557 return;
558
559 if (!Proto->hasExceptionSpec())
560 return;
561
John McCallf1549f62010-07-06 01:34:17 +0000562 EHStack.popFilter();
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000563}
564
Mike Stump2bf701e2009-11-20 23:44:51 +0000565void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000566 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000567 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000568 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000569}
570
John McCall59a70002010-07-07 06:56:46 +0000571void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000572 unsigned NumHandlers = S.getNumHandlers();
573 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000574
John McCallf1549f62010-07-06 01:34:17 +0000575 for (unsigned I = 0; I != NumHandlers; ++I) {
576 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000577
John McCallf1549f62010-07-06 01:34:17 +0000578 llvm::BasicBlock *Handler = createBasicBlock("catch");
579 if (C->getExceptionDecl()) {
580 // FIXME: Dropping the reference type on the type into makes it
581 // impossible to correctly implement catch-by-reference
582 // semantics for pointers. Unfortunately, this is what all
583 // existing compilers do, and it's not clear that the standard
584 // personality routine is capable of doing this right. See C++ DR 388:
585 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
586 QualType CaughtType = C->getCaughtType();
587 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
588 llvm::Value *TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, true);
589 CatchScope->setHandler(I, TypeInfo, Handler);
590 } else {
591 // No exception decl indicates '...', a catch-all.
592 CatchScope->setCatchAllHandler(I, Handler);
593 }
594 }
John McCallf1549f62010-07-06 01:34:17 +0000595}
596
597/// Check whether this is a non-EH scope, i.e. a scope which doesn't
598/// affect exception handling. Currently, the only non-EH scopes are
599/// normal-only cleanup scopes.
600static bool isNonEHScope(const EHScope &S) {
601 return isa<EHCleanupScope>(S) && !cast<EHCleanupScope>(S).isEHCleanup();
602}
603
604llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
605 assert(EHStack.requiresLandingPad());
606 assert(!EHStack.empty());
607
608 // Check the innermost scope for a cached landing pad. If this is
609 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
610 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
611 if (LP) return LP;
612
613 // Build the landing pad for this scope.
614 LP = EmitLandingPad();
615 assert(LP);
616
617 // Cache the landing pad on the innermost scope. If this is a
618 // non-EH scope, cache the landing pad on the enclosing scope, too.
619 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
620 ir->setCachedLandingPad(LP);
621 if (!isNonEHScope(*ir)) break;
622 }
623
624 return LP;
625}
626
627llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
628 assert(EHStack.requiresLandingPad());
629
630 // This function contains a hack to work around a design flaw in
631 // LLVM's EH IR which breaks semantics after inlining. This same
632 // hack is implemented in llvm-gcc.
633 //
634 // The LLVM EH abstraction is basically a thin veneer over the
635 // traditional GCC zero-cost design: for each range of instructions
636 // in the function, there is (at most) one "landing pad" with an
637 // associated chain of EH actions. A language-specific personality
638 // function interprets this chain of actions and (1) decides whether
639 // or not to resume execution at the landing pad and (2) if so,
640 // provides an integer indicating why it's stopping. In LLVM IR,
641 // the association of a landing pad with a range of instructions is
642 // achieved via an invoke instruction, the chain of actions becomes
643 // the arguments to the @llvm.eh.selector call, and the selector
644 // call returns the integer indicator. Other than the required
645 // presence of two intrinsic function calls in the landing pad,
646 // the IR exactly describes the layout of the output code.
647 //
648 // A principal advantage of this design is that it is completely
649 // language-agnostic; in theory, the LLVM optimizers can treat
650 // landing pads neutrally, and targets need only know how to lower
651 // the intrinsics to have a functioning exceptions system (assuming
652 // that platform exceptions follow something approximately like the
653 // GCC design). Unfortunately, landing pads cannot be combined in a
654 // language-agnostic way: given selectors A and B, there is no way
655 // to make a single landing pad which faithfully represents the
656 // semantics of propagating an exception first through A, then
657 // through B, without knowing how the personality will interpret the
658 // (lowered form of the) selectors. This means that inlining has no
659 // choice but to crudely chain invokes (i.e., to ignore invokes in
660 // the inlined function, but to turn all unwindable calls into
661 // invokes), which is only semantically valid if every unwind stops
662 // at every landing pad.
663 //
664 // Therefore, the invoke-inline hack is to guarantee that every
665 // landing pad has a catch-all.
666 const bool UseInvokeInlineHack = true;
667
668 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
669 assert(ir != EHStack.end() &&
670 "stack requiring landing pad is nothing but non-EH scopes?");
671
672 // If this is a terminate scope, just use the singleton terminate
673 // landing pad.
674 if (isa<EHTerminateScope>(*ir))
675 return getTerminateLandingPad();
676
677 // If this isn't an EH scope, iterate; otherwise break out.
678 if (!isNonEHScope(*ir)) break;
679 ++ir;
680
681 // We haven't checked this scope for a cached landing pad yet.
682 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
683 return LP;
684 }
685
686 // Save the current IR generation state.
687 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
688
689 // Create and configure the landing pad.
690 llvm::BasicBlock *LP = createBasicBlock("lpad");
691 EmitBlock(LP);
692
693 // Save the exception pointer. It's safe to use a single exception
694 // pointer per function because EH cleanups can never have nested
695 // try/catches.
696 llvm::CallInst *Exn =
697 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
698 Exn->setDoesNotThrow();
699 Builder.CreateStore(Exn, getExceptionSlot());
700
701 // Build the selector arguments.
702 llvm::SmallVector<llvm::Value*, 8> EHSelector;
703 EHSelector.push_back(Exn);
704 EHSelector.push_back(getPersonalityFn(*this));
705
706 // Accumulate all the handlers in scope.
707 llvm::DenseMap<llvm::Value*, JumpDest> EHHandlers;
708 JumpDest CatchAll;
709 bool HasEHCleanup = false;
710 bool HasEHFilter = false;
711 llvm::SmallVector<llvm::Value*, 8> EHFilters;
712 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
713 I != E; ++I) {
714
715 switch (I->getKind()) {
716 case EHScope::Cleanup:
717 if (!HasEHCleanup)
718 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
719 // We otherwise don't care about cleanups.
720 continue;
721
722 case EHScope::Filter: {
723 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
724 assert(!CatchAll.Block && "EH filter reached after catch-all");
725
726 // Filter scopes get added to the selector in wierd ways.
727 EHFilterScope &Filter = cast<EHFilterScope>(*I);
728 HasEHFilter = true;
729
730 // Add all the filter values which we aren't already explicitly
731 // catching.
732 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
733 llvm::Value *FV = Filter.getFilter(I);
734 if (!EHHandlers.count(FV))
735 EHFilters.push_back(FV);
736 }
737 goto done;
738 }
739
740 case EHScope::Terminate:
741 // Terminate scopes are basically catch-alls.
742 assert(!CatchAll.Block);
743 CatchAll.Block = getTerminateHandler();
744 CatchAll.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
745 goto done;
746
747 case EHScope::Catch:
748 break;
749 }
750
751 EHCatchScope &Catch = cast<EHCatchScope>(*I);
752 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
753 EHCatchScope::Handler Handler = Catch.getHandler(HI);
754
755 // Catch-all. We should only have one of these per catch.
756 if (!Handler.Type) {
757 assert(!CatchAll.Block);
758 CatchAll.Block = Handler.Block;
759 CatchAll.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
760 continue;
761 }
762
763 // Check whether we already have a handler for this type.
764 JumpDest &Dest = EHHandlers[Handler.Type];
765 if (Dest.Block) continue;
766
767 EHSelector.push_back(Handler.Type);
768 Dest.Block = Handler.Block;
769 Dest.ScopeDepth = EHStack.getEnclosingEHCleanup(I);
770 }
771
772 // Stop if we found a catch-all.
773 if (CatchAll.Block) break;
774 }
775
776 done:
777 unsigned LastToEmitInLoop = EHSelector.size();
778
779 // If we have a catch-all, add null to the selector.
780 if (CatchAll.Block) {
781 EHSelector.push_back(getCatchAllValue(CGF));
782
783 // If we have an EH filter, we need to add those handlers in the
784 // right place in the selector, which is to say, at the end.
785 } else if (HasEHFilter) {
786 // Create a filter expression: an integer constant saying how many
787 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
788 // followed by the filter types. The personality routine only
789 // lands here if the filter doesn't match.
790 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
791 EHFilters.size() + 1));
792 EHSelector.append(EHFilters.begin(), EHFilters.end());
793
794 // Also check whether we need a cleanup.
795 if (UseInvokeInlineHack || HasEHCleanup)
796 EHSelector.push_back(UseInvokeInlineHack
797 ? getCatchAllValue(CGF)
798 : getCleanupValue(CGF));
799
800 // Otherwise, signal that we at least have cleanups.
801 } else if (UseInvokeInlineHack || HasEHCleanup) {
802 EHSelector.push_back(UseInvokeInlineHack
803 ? getCatchAllValue(CGF)
804 : getCleanupValue(CGF));
805 } else {
806 assert(LastToEmitInLoop > 2);
807 LastToEmitInLoop--;
808 }
809
810 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
811
812 // Tell the backend how to generate the landing pad.
813 llvm::CallInst *Selection =
814 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
815 EHSelector.begin(), EHSelector.end(), "eh.selector");
816 Selection->setDoesNotThrow();
817
818 // Select the right handler.
819 llvm::Value *llvm_eh_typeid_for =
820 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
821
822 // The results of llvm_eh_typeid_for aren't reliable --- at least
823 // not locally --- so we basically have to do this as an 'if' chain.
824 // We walk through the first N-1 catch clauses, testing and chaining,
825 // and then fall into the final clause (which is either a cleanup, a
826 // filter (possibly with a cleanup), a catch-all, or another catch).
827 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
828 llvm::Value *Type = EHSelector[I];
829 JumpDest Dest = EHHandlers[Type];
830 assert(Dest.Block && "no handler entry for value in selector?");
831
832 // Figure out where to branch on a match. As a debug code-size
833 // optimization, if the scope depth matches the innermost cleanup,
834 // we branch directly to the catch handler.
835 llvm::BasicBlock *Match = Dest.Block;
836 bool MatchNeedsCleanup = Dest.ScopeDepth != EHStack.getInnermostEHCleanup();
837 if (MatchNeedsCleanup)
838 Match = createBasicBlock("eh.match");
839
840 llvm::BasicBlock *Next = createBasicBlock("eh.next");
841
842 // Check whether the exception matches.
843 llvm::CallInst *Id
844 = Builder.CreateCall(llvm_eh_typeid_for,
845 Builder.CreateBitCast(Type, CGM.PtrToInt8Ty));
846 Id->setDoesNotThrow();
847 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
848 Match, Next);
849
850 // Emit match code if necessary.
851 if (MatchNeedsCleanup) {
852 EmitBlock(Match);
853 EmitBranchThroughEHCleanup(Dest);
854 }
855
856 // Continue to the next match.
857 EmitBlock(Next);
858 }
859
860 // Emit the final case in the selector.
861 // This might be a catch-all....
862 if (CatchAll.Block) {
863 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
864 EmitBranchThroughEHCleanup(CatchAll);
865
866 // ...or an EH filter...
867 } else if (HasEHFilter) {
868 llvm::Value *SavedSelection = Selection;
869
870 // First, unwind out to the outermost scope if necessary.
871 if (EHStack.hasEHCleanups()) {
872 // The end here might not dominate the beginning, so we might need to
873 // save the selector if we need it.
874 llvm::AllocaInst *SelectorVar = 0;
875 if (HasEHCleanup) {
876 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
877 Builder.CreateStore(Selection, SelectorVar);
878 }
879
880 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
881 EmitBranchThroughEHCleanup(JumpDest(CleanupContBB, EHStack.stable_end()));
882 EmitBlock(CleanupContBB);
883
884 if (HasEHCleanup)
885 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
886 }
887
888 // If there was a cleanup, we'll need to actually check whether we
889 // landed here because the filter triggered.
890 if (UseInvokeInlineHack || HasEHCleanup) {
891 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
892 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
893
894 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
895 llvm::Value *FailsFilter =
896 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
897 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
898
899 // The rethrow block is where we land if this was a cleanup.
900 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
901 EmitBlock(RethrowBB);
902 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
903 Builder.CreateLoad(getExceptionSlot()))
904 ->setDoesNotReturn();
905 Builder.CreateUnreachable();
906
907 EmitBlock(UnexpectedBB);
908 }
909
910 // Call __cxa_call_unexpected. This doesn't need to be an invoke
911 // because __cxa_call_unexpected magically filters exceptions
912 // according to the last landing pad the exception was thrown
913 // into. Seriously.
914 Builder.CreateCall(getUnexpectedFn(*this),
915 Builder.CreateLoad(getExceptionSlot()))
916 ->setDoesNotReturn();
917 Builder.CreateUnreachable();
918
919 // ...or a normal catch handler...
920 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
921 llvm::Value *Type = EHSelector.back();
922 EmitBranchThroughEHCleanup(EHHandlers[Type]);
923
924 // ...or a cleanup.
925 } else {
926 // We emit a jump to a notional label at the outermost unwind state.
927 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
928 JumpDest Dest(Unwind, EHStack.stable_end());
929 EmitBranchThroughEHCleanup(Dest);
930
931 // The unwind block. We have to reload the exception here because
932 // we might have unwound through arbitrary blocks, so the landing
933 // pad might not dominate.
934 EmitBlock(Unwind);
935
936 // This can always be a call because we necessarily didn't find
937 // anything on the EH stack which needs our help.
938 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
939 Builder.CreateLoad(getExceptionSlot()))
940 ->setDoesNotReturn();
941 Builder.CreateUnreachable();
942 }
943
944 // Restore the old IR generation state.
945 Builder.restoreIP(SavedIP);
946
947 return LP;
948}
949
950/// Emits a call to __cxa_begin_catch and enters a cleanup to call
951/// __cxa_end_catch.
952static llvm::Value *CallBeginCatch(CodeGenFunction &CGF, llvm::Value *Exn) {
953 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
954 Call->setDoesNotThrow();
955
956 {
957 CodeGenFunction::CleanupBlock EndCatchCleanup(CGF,
958 CodeGenFunction::NormalAndEHCleanup);
959
960 // __cxa_end_catch never throws, so this can just be a call.
961 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
962 }
963
964 return Call;
965}
966
967/// A "special initializer" callback for initializing a catch
968/// parameter during catch initialization.
969static void InitCatchParam(CodeGenFunction &CGF,
970 const VarDecl &CatchParam,
971 llvm::Value *ParamAddr) {
972 // Load the exception from where the landing pad saved it.
973 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
974
975 CanQualType CatchType =
976 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
977 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
978
979 // If we're catching by reference, we can just cast the object
980 // pointer to the appropriate pointer.
981 if (isa<ReferenceType>(CatchType)) {
982 // __cxa_begin_catch returns the adjusted object pointer.
983 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn);
984 llvm::Value *ExnCast =
985 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
986 CGF.Builder.CreateStore(ExnCast, ParamAddr);
987 return;
988 }
989
990 // Non-aggregates (plus complexes).
991 bool IsComplex = false;
992 if (!CGF.hasAggregateLLVMType(CatchType) ||
993 (IsComplex = CatchType->isAnyComplexType())) {
994 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn);
995
996 // If the catch type is a pointer type, __cxa_begin_catch returns
997 // the pointer by value.
998 if (CatchType->hasPointerRepresentation()) {
999 llvm::Value *CastExn =
1000 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1001 CGF.Builder.CreateStore(CastExn, ParamAddr);
1002 return;
1003 }
1004
1005 // Otherwise, it returns a pointer into the exception object.
1006
1007 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1008 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1009
1010 if (IsComplex) {
1011 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1012 ParamAddr, /*volatile*/ false);
1013 } else {
1014 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
1015 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, CatchType);
1016 }
1017 return;
1018 }
1019
1020 // FIXME: this *really* needs to be done via a proper, Sema-emitted
1021 // initializer expression.
1022
1023 CXXRecordDecl *RD = CatchType.getTypePtr()->getAsCXXRecordDecl();
1024 assert(RD && "aggregate catch type was not a record!");
1025
1026 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1027
1028 if (RD->hasTrivialCopyConstructor()) {
1029 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn);
1030 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1031 CGF.EmitAggregateCopy(ParamAddr, Cast, CatchType);
1032 return;
1033 }
1034
1035 // We have to call __cxa_get_exception_ptr to get the adjusted
1036 // pointer before copying.
1037 llvm::CallInst *AdjustedExn =
1038 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
1039 AdjustedExn->setDoesNotThrow();
1040 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1041
1042 CXXConstructorDecl *CD = RD->getCopyConstructor(CGF.getContext(), 0);
1043 assert(CD && "record has no copy constructor!");
1044 llvm::Value *CopyCtor = CGF.CGM.GetAddrOfCXXConstructor(CD, Ctor_Complete);
1045
1046 CallArgList CallArgs;
1047 CallArgs.push_back(std::make_pair(RValue::get(ParamAddr),
1048 CD->getThisType(CGF.getContext())));
1049 CallArgs.push_back(std::make_pair(RValue::get(Cast),
1050 CD->getParamDecl(0)->getType()));
1051
1052 const FunctionProtoType *FPT
1053 = CD->getType()->getAs<FunctionProtoType>();
1054
1055 // Call the copy ctor in a terminate scope.
1056 CGF.EHStack.pushTerminate();
1057 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
1058 CopyCtor, ReturnValueSlot(), CallArgs, CD);
1059 CGF.EHStack.popTerminate();
1060
1061 // Finally we can call __cxa_begin_catch.
1062 CallBeginCatch(CGF, Exn);
1063}
1064
1065/// Begins a catch statement by initializing the catch variable and
1066/// calling __cxa_begin_catch.
1067static void BeginCatch(CodeGenFunction &CGF,
1068 const CXXCatchStmt *S) {
1069 // We have to be very careful with the ordering of cleanups here:
1070 // C++ [except.throw]p4:
1071 // The destruction [of the exception temporary] occurs
1072 // immediately after the destruction of the object declared in
1073 // the exception-declaration in the handler.
1074 //
1075 // So the precise ordering is:
1076 // 1. Construct catch variable.
1077 // 2. __cxa_begin_catch
1078 // 3. Enter __cxa_end_catch cleanup
1079 // 4. Enter dtor cleanup
1080 //
1081 // We do this by initializing the exception variable with a
1082 // "special initializer", InitCatchParam. Delegation sequence:
1083 // - ExitCXXTryStmt opens a RunCleanupsScope
1084 // - EmitLocalBlockVarDecl creates the variable and debug info
1085 // - InitCatchParam initializes the variable from the exception
1086 // - CallBeginCatch calls __cxa_begin_catch
1087 // - CallBeginCatch enters the __cxa_end_catch cleanup
1088 // - EmitLocalBlockVarDecl enters the variable destructor cleanup
1089 // - EmitCXXTryStmt emits the code for the catch body
1090 // - EmitCXXTryStmt close the RunCleanupsScope
1091
1092 VarDecl *CatchParam = S->getExceptionDecl();
1093 if (!CatchParam) {
1094 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
1095 CallBeginCatch(CGF, Exn);
1096 return;
1097 }
1098
1099 // Emit the local.
1100 CGF.EmitLocalBlockVarDecl(*CatchParam, &InitCatchParam);
John McCall9fc6a772010-02-19 09:25:03 +00001101}
1102
John McCall59a70002010-07-07 06:56:46 +00001103void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001104 unsigned NumHandlers = S.getNumHandlers();
1105 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1106 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001107
John McCallf1549f62010-07-06 01:34:17 +00001108 // Copy the handler blocks off before we pop the EH stack. Emitting
1109 // the handlers might scribble on this memory.
1110 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1111 memcpy(Handlers.data(), CatchScope.begin(),
1112 NumHandlers * sizeof(EHCatchScope::Handler));
1113 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001114
John McCallf1549f62010-07-06 01:34:17 +00001115 // The fall-through block.
1116 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001117
John McCallf1549f62010-07-06 01:34:17 +00001118 // We just emitted the body of the try; jump to the continue block.
1119 if (HaveInsertPoint())
1120 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001121
John McCall59a70002010-07-07 06:56:46 +00001122 // Determine if we need an implicit rethrow for all these catch handlers.
1123 bool ImplicitRethrow = false;
1124 if (IsFnTryBlock)
1125 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1126 isa<CXXConstructorDecl>(CurCodeDecl);
1127
John McCallf1549f62010-07-06 01:34:17 +00001128 for (unsigned I = 0; I != NumHandlers; ++I) {
1129 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1130 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001131
John McCallf1549f62010-07-06 01:34:17 +00001132 // Catch the exception if this isn't a catch-all.
1133 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001134
John McCallf1549f62010-07-06 01:34:17 +00001135 // Enter a cleanup scope, including the catch variable and the
1136 // end-catch.
1137 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001138
John McCallf1549f62010-07-06 01:34:17 +00001139 // Initialize the catch variable and set up the cleanups.
1140 BeginCatch(*this, C);
1141
John McCall59a70002010-07-07 06:56:46 +00001142 // If there's an implicit rethrow, push a normal "cleanup" to call
1143 // _cxa_rethrow. This needs to happen before _cxa_end_catch is
1144 // called.
1145 if (ImplicitRethrow) {
1146 CleanupBlock Rethrow(*this, NormalCleanup);
1147 EmitCallOrInvoke(getReThrowFn(*this), 0, 0);
1148 }
1149
John McCallf1549f62010-07-06 01:34:17 +00001150 // Perform the body of the catch.
1151 EmitStmt(C->getHandlerBlock());
1152
1153 // Fall out through the catch cleanups.
1154 CatchScope.ForceCleanup();
1155
1156 // Branch out of the try.
1157 if (HaveInsertPoint())
1158 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001159 }
1160
John McCallf1549f62010-07-06 01:34:17 +00001161 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001162}
Mike Stumpd88ea562009-12-09 03:35:49 +00001163
John McCallf1549f62010-07-06 01:34:17 +00001164/// Enters a finally block for an implementation using zero-cost
1165/// exceptions. This is mostly general, but hard-codes some
1166/// language/ABI-specific behavior in the catch-all sections.
1167CodeGenFunction::FinallyInfo
1168CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1169 llvm::Constant *BeginCatchFn,
1170 llvm::Constant *EndCatchFn,
1171 llvm::Constant *RethrowFn) {
1172 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1173 "begin/end catch functions not paired");
1174 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001175
John McCallf1549f62010-07-06 01:34:17 +00001176 // The rethrow function has one of the following two types:
1177 // void (*)()
1178 // void (*)(void*)
1179 // In the latter case we need to pass it the exception object.
1180 // But we can't use the exception slot because the @finally might
1181 // have a landing pad (which would overwrite the exception slot).
1182 const llvm::FunctionType *RethrowFnTy =
1183 cast<llvm::FunctionType>(
1184 cast<llvm::PointerType>(RethrowFn->getType())
1185 ->getElementType());
1186 llvm::Value *SavedExnVar = 0;
1187 if (RethrowFnTy->getNumParams())
1188 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001189
John McCallf1549f62010-07-06 01:34:17 +00001190 // A finally block is a statement which must be executed on any edge
1191 // out of a given scope. Unlike a cleanup, the finally block may
1192 // contain arbitrary control flow leading out of itself. In
1193 // addition, finally blocks should always be executed, even if there
1194 // are no catch handlers higher on the stack. Therefore, we
1195 // surround the protected scope with a combination of a normal
1196 // cleanup (to catch attempts to break out of the block via normal
1197 // control flow) and an EH catch-all (semantically "outside" any try
1198 // statement to which the finally block might have been attached).
1199 // The finally block itself is generated in the context of a cleanup
1200 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001201
John McCallf1549f62010-07-06 01:34:17 +00001202 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001203
John McCallf1549f62010-07-06 01:34:17 +00001204 // Jump destination for performing the finally block on an exception
1205 // edge. We'll never actually reach this block, so unreachable is
1206 // fine.
1207 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001208
John McCallf1549f62010-07-06 01:34:17 +00001209 // Whether the finally block is being executed for EH purposes.
1210 llvm::AllocaInst *ForEHVar = CreateTempAlloca(CGF.Builder.getInt1Ty(),
1211 "finally.for-eh");
1212 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001213
John McCallf1549f62010-07-06 01:34:17 +00001214 // Enter a normal cleanup which will perform the @finally block.
1215 {
1216 CodeGenFunction::CleanupBlock
1217 NormalCleanup(*this, CodeGenFunction::NormalCleanup);
Mike Stumpd88ea562009-12-09 03:35:49 +00001218
John McCallf1549f62010-07-06 01:34:17 +00001219 // Enter a cleanup to call the end-catch function if one was provided.
1220 if (EndCatchFn) {
1221 CodeGenFunction::CleanupBlock
1222 FinallyExitCleanup(CGF, CodeGenFunction::NormalAndEHCleanup);
1223
1224 llvm::BasicBlock *EndCatchBB = createBasicBlock("finally.endcatch");
1225 llvm::BasicBlock *CleanupContBB = createBasicBlock("finally.cleanup.cont");
1226
1227 llvm::Value *ShouldEndCatch =
1228 Builder.CreateLoad(ForEHVar, "finally.endcatch");
1229 Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1230 EmitBlock(EndCatchBB);
1231 Builder.CreateCall(EndCatchFn)->setDoesNotThrow();
1232 EmitBlock(CleanupContBB);
1233 }
1234
1235 // Emit the finally block.
1236 EmitStmt(Body);
1237
1238 // If the end of the finally is reachable, check whether this was
1239 // for EH. If so, rethrow.
1240 if (HaveInsertPoint()) {
1241 llvm::BasicBlock *RethrowBB = createBasicBlock("finally.rethrow");
1242 llvm::BasicBlock *ContBB = createBasicBlock("finally.cont");
1243
1244 llvm::Value *ShouldRethrow =
1245 Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1246 Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1247
1248 EmitBlock(RethrowBB);
1249 if (SavedExnVar) {
1250 llvm::Value *Args[] = { Builder.CreateLoad(SavedExnVar) };
1251 EmitCallOrInvoke(RethrowFn, Args, Args+1);
1252 } else {
1253 EmitCallOrInvoke(RethrowFn, 0, 0);
1254 }
1255 Builder.CreateUnreachable();
1256
1257 EmitBlock(ContBB);
1258 }
1259
1260 // Leave the end-catch cleanup. As an optimization, pretend that
1261 // the fallthrough path was inaccessible; we've dynamically proven
1262 // that we're not in the EH case along that path.
1263 if (EndCatchFn) {
1264 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1265 PopCleanupBlock();
1266 Builder.restoreIP(SavedIP);
1267 }
1268
1269 // Now make sure we actually have an insertion point or the
1270 // cleanup gods will hate us.
1271 EnsureInsertPoint();
1272 }
1273
1274 // Enter a catch-all scope.
1275 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1276 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1277 Builder.SetInsertPoint(CatchAllBB);
1278
1279 // If there's a begin-catch function, call it.
1280 if (BeginCatchFn) {
1281 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1282 ->setDoesNotThrow();
1283 }
1284
1285 // If we need to remember the exception pointer to rethrow later, do so.
1286 if (SavedExnVar) {
1287 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1288 Builder.CreateStore(SavedExn, SavedExnVar);
1289 }
1290
1291 // Tell the finally block that we're in EH.
1292 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1293
1294 // Thread a jump through the finally cleanup.
1295 EmitBranchThroughCleanup(RethrowDest);
1296
1297 Builder.restoreIP(SavedIP);
1298
1299 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1300 CatchScope->setCatchAllHandler(0, CatchAllBB);
1301
1302 return Info;
1303}
1304
1305void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1306 // Leave the finally catch-all.
1307 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1308 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1309 EHStack.popCatch();
1310
1311 // And leave the normal cleanup.
1312 PopCleanupBlock();
1313
1314 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1315 EmitBlock(CatchAllBB, true);
1316
1317 Builder.restoreIP(SavedIP);
1318}
1319
1320llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1321 if (TerminateLandingPad)
1322 return TerminateLandingPad;
1323
1324 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1325
1326 // This will get inserted at the end of the function.
1327 TerminateLandingPad = createBasicBlock("terminate.lpad");
1328 Builder.SetInsertPoint(TerminateLandingPad);
1329
1330 // Tell the backend that this is a landing pad.
1331 llvm::CallInst *Exn =
1332 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1333 Exn->setDoesNotThrow();
1334
1335 // Tell the backend what the exception table should be:
1336 // nothing but a catch-all.
1337 llvm::Value *Args[3] = { Exn, getPersonalityFn(*this),
1338 getCatchAllValue(*this) };
1339 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1340 Args, Args+3, "eh.selector")
1341 ->setDoesNotThrow();
1342
1343 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1344 TerminateCall->setDoesNotReturn();
1345 TerminateCall->setDoesNotThrow();
Mike Stumpd88ea562009-12-09 03:35:49 +00001346 CGF.Builder.CreateUnreachable();
1347
John McCallf1549f62010-07-06 01:34:17 +00001348 // Restore the saved insertion state.
1349 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001350
John McCallf1549f62010-07-06 01:34:17 +00001351 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001352}
Mike Stump9b39c512009-12-09 22:59:31 +00001353
1354llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001355 if (TerminateHandler)
1356 return TerminateHandler;
1357
John McCallf1549f62010-07-06 01:34:17 +00001358 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001359
John McCallf1549f62010-07-06 01:34:17 +00001360 // Set up the terminate handler. This block is inserted at the very
1361 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001362 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001363 Builder.SetInsertPoint(TerminateHandler);
1364 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001365 TerminateCall->setDoesNotReturn();
1366 TerminateCall->setDoesNotThrow();
1367 Builder.CreateUnreachable();
1368
John McCall3d3ec1c2010-04-21 10:05:39 +00001369 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001370 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001371
Mike Stump9b39c512009-12-09 22:59:31 +00001372 return TerminateHandler;
1373}
John McCallf1549f62010-07-06 01:34:17 +00001374
1375CodeGenFunction::CleanupBlock::CleanupBlock(CodeGenFunction &CGF,
1376 CleanupKind Kind)
1377 : CGF(CGF), SavedIP(CGF.Builder.saveIP()), NormalCleanupExitBB(0) {
1378 llvm::BasicBlock *EntryBB = CGF.createBasicBlock("cleanup");
1379 CGF.Builder.SetInsertPoint(EntryBB);
1380
1381 switch (Kind) {
1382 case NormalAndEHCleanup:
1383 NormalCleanupEntryBB = EHCleanupEntryBB = EntryBB;
1384 break;
1385
1386 case NormalCleanup:
1387 NormalCleanupEntryBB = EntryBB;
1388 EHCleanupEntryBB = 0;
1389 break;
1390
1391 case EHCleanup:
1392 NormalCleanupEntryBB = 0;
1393 EHCleanupEntryBB = EntryBB;
1394 CGF.EHStack.pushTerminate();
1395 break;
1396 }
1397}
1398
1399void CodeGenFunction::CleanupBlock::beginEHCleanup() {
1400 assert(EHCleanupEntryBB == 0 && "already started an EH cleanup");
1401 NormalCleanupExitBB = CGF.Builder.GetInsertBlock();
1402 assert(NormalCleanupExitBB && "end of normal cleanup is unreachable");
1403
1404 EHCleanupEntryBB = CGF.createBasicBlock("eh.cleanup");
1405 CGF.Builder.SetInsertPoint(EHCleanupEntryBB);
1406 CGF.EHStack.pushTerminate();
1407}
1408
1409CodeGenFunction::CleanupBlock::~CleanupBlock() {
1410 llvm::BasicBlock *EHCleanupExitBB = 0;
1411
1412 // If we're currently writing the EH cleanup...
1413 if (EHCleanupEntryBB) {
1414 // Set the EH cleanup exit block.
1415 EHCleanupExitBB = CGF.Builder.GetInsertBlock();
1416 assert(EHCleanupExitBB && "end of EH cleanup is unreachable");
1417
1418 // If we're actually writing both at once, set the normal exit, too.
1419 if (EHCleanupEntryBB == NormalCleanupEntryBB)
1420 NormalCleanupExitBB = EHCleanupExitBB;
1421
1422 // Otherwise, we must have pushed a terminate handler.
1423 else
1424 CGF.EHStack.popTerminate();
1425
1426 // Otherwise, just set the normal cleanup exit block.
1427 } else {
1428 NormalCleanupExitBB = CGF.Builder.GetInsertBlock();
1429 assert(NormalCleanupExitBB && "end of normal cleanup is unreachable");
1430 }
1431
1432 CGF.EHStack.pushCleanup(NormalCleanupEntryBB, NormalCleanupExitBB,
1433 EHCleanupEntryBB, EHCleanupExitBB);
1434
1435 CGF.Builder.restoreIP(SavedIP);
1436}
1437