blob: cc4446fcf0154d192343802383718f51fea3d6e6 [file] [log] [blame]
Anders Carlsson756b5c42009-10-30 01:42:31 +00001//===--- CGException.cpp - Emit LLVM Code for C++ exceptions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ exception related code generation.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stump2bf701e2009-11-20 23:44:51 +000014#include "clang/AST/StmtCXX.h"
15
16#include "llvm/Intrinsics.h"
John McCallb2593832010-09-16 06:16:50 +000017#include "llvm/IntrinsicInst.h"
John McCallf1549f62010-07-06 01:34:17 +000018#include "llvm/Support/CallSite.h"
Mike Stump2bf701e2009-11-20 23:44:51 +000019
John McCall5a180392010-07-24 00:37:23 +000020#include "CGObjCRuntime.h"
Anders Carlsson756b5c42009-10-30 01:42:31 +000021#include "CodeGenFunction.h"
John McCallf1549f62010-07-06 01:34:17 +000022#include "CGException.h"
John McCall36f893c2011-01-28 11:13:47 +000023#include "CGCleanup.h"
John McCall204b0752010-07-20 22:17:55 +000024#include "TargetInfo.h"
John McCallf1549f62010-07-06 01:34:17 +000025
Anders Carlsson756b5c42009-10-30 01:42:31 +000026using namespace clang;
27using namespace CodeGen;
28
Anders Carlssond3379292009-10-30 02:27:02 +000029static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
30 // void *__cxa_allocate_exception(size_t thrown_size);
31 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
32 std::vector<const llvm::Type*> Args(1, SizeTy);
Mike Stump8755ec32009-12-10 00:06:18 +000033
34 const llvm::FunctionType *FTy =
Anders Carlssond3379292009-10-30 02:27:02 +000035 llvm::FunctionType::get(llvm::Type::getInt8PtrTy(CGF.getLLVMContext()),
36 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +000037
Anders Carlssond3379292009-10-30 02:27:02 +000038 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
39}
40
Mike Stump99533832009-12-02 07:41:41 +000041static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
42 // void __cxa_free_exception(void *thrown_exception);
43 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
44 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +000045
46 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +000047 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
48 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +000049
Mike Stump99533832009-12-02 07:41:41 +000050 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
51}
52
Anders Carlssond3379292009-10-30 02:27:02 +000053static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
Mike Stump8755ec32009-12-10 00:06:18 +000054 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump99533832009-12-02 07:41:41 +000055 // void (*dest) (void *));
Anders Carlssond3379292009-10-30 02:27:02 +000056
57 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
58 std::vector<const llvm::Type*> Args(3, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +000059
60 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +000061 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
62 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +000063
Anders Carlssond3379292009-10-30 02:27:02 +000064 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
65}
66
Mike Stumpb4eea692009-11-20 00:56:31 +000067static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +000068 // void __cxa_rethrow();
Mike Stumpb4eea692009-11-20 00:56:31 +000069
Mike Stump8755ec32009-12-10 00:06:18 +000070 const llvm::FunctionType *FTy =
Mike Stumpb4eea692009-11-20 00:56:31 +000071 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +000072
Mike Stumpb4eea692009-11-20 00:56:31 +000073 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
74}
75
John McCallf1549f62010-07-06 01:34:17 +000076static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
77 // void *__cxa_get_exception_ptr(void*);
78 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
79 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
80
81 const llvm::FunctionType *FTy =
82 llvm::FunctionType::get(Int8PtrTy, Args, false);
83
84 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
85}
86
Mike Stump2bf701e2009-11-20 23:44:51 +000087static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
John McCallf1549f62010-07-06 01:34:17 +000088 // void *__cxa_begin_catch(void*);
Mike Stump2bf701e2009-11-20 23:44:51 +000089
90 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
91 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +000092
93 const llvm::FunctionType *FTy =
Mike Stump0f590be2009-12-01 03:41:18 +000094 llvm::FunctionType::get(Int8PtrTy, Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +000095
Mike Stump2bf701e2009-11-20 23:44:51 +000096 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
97}
98
99static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
Mike Stump99533832009-12-02 07:41:41 +0000100 // void __cxa_end_catch();
Mike Stump2bf701e2009-11-20 23:44:51 +0000101
Mike Stump8755ec32009-12-10 00:06:18 +0000102 const llvm::FunctionType *FTy =
Mike Stump2bf701e2009-11-20 23:44:51 +0000103 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000104
Mike Stump2bf701e2009-11-20 23:44:51 +0000105 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
106}
107
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000108static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
109 // void __cxa_call_unexepcted(void *thrown_exception);
110
111 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
112 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000113
114 const llvm::FunctionType *FTy =
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000115 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()),
116 Args, false);
Mike Stump8755ec32009-12-10 00:06:18 +0000117
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000118 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
119}
120
Douglas Gregor86a3a032010-05-16 01:24:12 +0000121llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
122 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Mike Stump0f590be2009-12-01 03:41:18 +0000123 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000124
125 const llvm::FunctionType *FTy =
Douglas Gregor86a3a032010-05-16 01:24:12 +0000126 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), Args,
Mike Stump0f590be2009-12-01 03:41:18 +0000127 false);
Mike Stump8755ec32009-12-10 00:06:18 +0000128
Douglas Gregor86a3a032010-05-16 01:24:12 +0000129 if (CGM.getLangOptions().SjLjExceptions)
John McCalla5f2de22010-08-11 20:59:53 +0000130 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor86a3a032010-05-16 01:24:12 +0000131 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump0f590be2009-12-01 03:41:18 +0000132}
133
Mike Stump99533832009-12-02 07:41:41 +0000134static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
135 // void __terminate();
136
Mike Stump8755ec32009-12-10 00:06:18 +0000137 const llvm::FunctionType *FTy =
Mike Stump99533832009-12-02 07:41:41 +0000138 llvm::FunctionType::get(llvm::Type::getVoidTy(CGF.getLLVMContext()), false);
Mike Stump8755ec32009-12-10 00:06:18 +0000139
David Chisnall79a9ad82010-05-17 13:49:20 +0000140 return CGF.CGM.CreateRuntimeFunction(FTy,
141 CGF.CGM.getLangOptions().CPlusPlus ? "_ZSt9terminatev" : "abort");
142}
143
John McCall8262b6a2010-07-17 00:43:08 +0000144static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
John McCallb2593832010-09-16 06:16:50 +0000145 llvm::StringRef Name) {
John McCall8262b6a2010-07-17 00:43:08 +0000146 const llvm::Type *Int8PtrTy =
147 llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
148 std::vector<const llvm::Type*> Args(1, Int8PtrTy);
149
150 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
151 const llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, Args, false);
152
153 return CGF.CGM.CreateRuntimeFunction(FTy, Name);
John McCallf1549f62010-07-06 01:34:17 +0000154}
155
John McCall8262b6a2010-07-17 00:43:08 +0000156const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
John McCall44680782010-11-07 02:35:25 +0000157const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
John McCall8262b6a2010-07-17 00:43:08 +0000158const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
159const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
160const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_sj0");
161const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
162 "objc_exception_throw");
David Chisnall80558d22011-03-20 21:35:39 +0000163const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personality_v0");
John McCall8262b6a2010-07-17 00:43:08 +0000164
165static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall44680782010-11-07 02:35:25 +0000166 if (L.SjLjExceptions)
167 return EHPersonality::GNU_C_SJLJ;
John McCall8262b6a2010-07-17 00:43:08 +0000168 return EHPersonality::GNU_C;
169}
170
171static const EHPersonality &getObjCPersonality(const LangOptions &L) {
172 if (L.NeXTRuntime) {
173 if (L.ObjCNonFragileABI) return EHPersonality::NeXT_ObjC;
174 else return getCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000175 } else {
John McCall8262b6a2010-07-17 00:43:08 +0000176 return EHPersonality::GNU_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000177 }
178}
179
John McCall8262b6a2010-07-17 00:43:08 +0000180static const EHPersonality &getCXXPersonality(const LangOptions &L) {
181 if (L.SjLjExceptions)
182 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallf1549f62010-07-06 01:34:17 +0000183 else
John McCall8262b6a2010-07-17 00:43:08 +0000184 return EHPersonality::GNU_CPlusPlus;
John McCallf1549f62010-07-06 01:34:17 +0000185}
186
187/// Determines the personality function to use when both C++
188/// and Objective-C exceptions are being caught.
John McCall8262b6a2010-07-17 00:43:08 +0000189static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCallf1549f62010-07-06 01:34:17 +0000190 // The ObjC personality defers to the C++ personality for non-ObjC
191 // handlers. Unlike the C++ case, we use the same personality
192 // function on targets using (backend-driven) SJLJ EH.
John McCall8262b6a2010-07-17 00:43:08 +0000193 if (L.NeXTRuntime) {
194 if (L.ObjCNonFragileABI)
195 return EHPersonality::NeXT_ObjC;
John McCallf1549f62010-07-06 01:34:17 +0000196
197 // In the fragile ABI, just use C++ exception handling and hope
198 // they're not doing crazy exception mixing.
199 else
John McCall8262b6a2010-07-17 00:43:08 +0000200 return getCXXPersonality(L);
Chandler Carruthdcf22ad2010-05-17 20:58:49 +0000201 }
David Chisnall79a9ad82010-05-17 13:49:20 +0000202
John McCall8262b6a2010-07-17 00:43:08 +0000203 // The GNU runtime's personality function inherently doesn't support
204 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnall80558d22011-03-20 21:35:39 +0000205 return EHPersonality::GNU_ObjCXX;
John McCallf1549f62010-07-06 01:34:17 +0000206}
207
John McCall8262b6a2010-07-17 00:43:08 +0000208const EHPersonality &EHPersonality::get(const LangOptions &L) {
209 if (L.CPlusPlus && L.ObjC1)
210 return getObjCXXPersonality(L);
211 else if (L.CPlusPlus)
212 return getCXXPersonality(L);
213 else if (L.ObjC1)
214 return getObjCPersonality(L);
John McCallf1549f62010-07-06 01:34:17 +0000215 else
John McCall8262b6a2010-07-17 00:43:08 +0000216 return getCPersonality(L);
217}
John McCallf1549f62010-07-06 01:34:17 +0000218
John McCallb2593832010-09-16 06:16:50 +0000219static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall8262b6a2010-07-17 00:43:08 +0000220 const EHPersonality &Personality) {
John McCall8262b6a2010-07-17 00:43:08 +0000221 llvm::Constant *Fn =
John McCallb2593832010-09-16 06:16:50 +0000222 CGM.CreateRuntimeFunction(llvm::FunctionType::get(
223 llvm::Type::getInt32Ty(CGM.getLLVMContext()),
224 true),
225 Personality.getPersonalityFnName());
226 return Fn;
227}
228
229static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
230 const EHPersonality &Personality) {
231 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCalld16c2cf2011-02-08 08:22:06 +0000232 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCallb2593832010-09-16 06:16:50 +0000233}
234
235/// Check whether a personality function could reasonably be swapped
236/// for a C++ personality function.
237static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
238 for (llvm::Constant::use_iterator
239 I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
240 llvm::User *User = *I;
241
242 // Conditionally white-list bitcasts.
243 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
244 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
245 if (!PersonalityHasOnlyCXXUses(CE))
246 return false;
247 continue;
248 }
249
250 // Otherwise, it has to be a selector call.
251 if (!isa<llvm::EHSelectorInst>(User)) return false;
252
253 llvm::EHSelectorInst *Selector = cast<llvm::EHSelectorInst>(User);
254 for (unsigned I = 2, E = Selector->getNumArgOperands(); I != E; ++I) {
255 // Look for something that would've been returned by the ObjC
256 // runtime's GetEHType() method.
257 llvm::GlobalVariable *GV
258 = dyn_cast<llvm::GlobalVariable>(Selector->getArgOperand(I));
259 if (!GV) continue;
260
261 // ObjC EH selector entries are always global variables with
262 // names starting like this.
263 if (GV->getName().startswith("OBJC_EHTYPE"))
264 return false;
265 }
266 }
267
268 return true;
269}
270
271/// Try to use the C++ personality function in ObjC++. Not doing this
272/// can cause some incompatibilities with gcc, which is more
273/// aggressive about only using the ObjC++ personality in a function
274/// when it really needs it.
275void CodeGenModule::SimplifyPersonality() {
276 // For now, this is really a Darwin-specific operation.
277 if (Context.Target.getTriple().getOS() != llvm::Triple::Darwin)
278 return;
279
280 // If we're not in ObjC++ -fexceptions, there's nothing to do.
281 if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
282 return;
283
284 const EHPersonality &ObjCXX = EHPersonality::get(Features);
285 const EHPersonality &CXX = getCXXPersonality(Features);
286 if (&ObjCXX == &CXX ||
287 ObjCXX.getPersonalityFnName() == CXX.getPersonalityFnName())
288 return;
289
290 llvm::Function *Fn =
291 getModule().getFunction(ObjCXX.getPersonalityFnName());
292
293 // Nothing to do if it's unused.
294 if (!Fn || Fn->use_empty()) return;
295
296 // Can't do the optimization if it has non-C++ uses.
297 if (!PersonalityHasOnlyCXXUses(Fn)) return;
298
299 // Create the C++ personality function and kill off the old
300 // function.
301 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
302
303 // This can happen if the user is screwing with us.
304 if (Fn->getType() != CXXFn->getType()) return;
305
306 Fn->replaceAllUsesWith(CXXFn);
307 Fn->eraseFromParent();
John McCallf1549f62010-07-06 01:34:17 +0000308}
309
310/// Returns the value to inject into a selector to indicate the
311/// presence of a catch-all.
312static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
313 // Possibly we should use @llvm.eh.catch.all.value here.
John McCalld16c2cf2011-02-08 08:22:06 +0000314 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallf1549f62010-07-06 01:34:17 +0000315}
316
317/// Returns the value to inject into a selector to indicate the
318/// presence of a cleanup.
319static llvm::Constant *getCleanupValue(CodeGenFunction &CGF) {
320 return llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
Mike Stump99533832009-12-02 07:41:41 +0000321}
322
John McCall09faeab2010-07-13 21:17:51 +0000323namespace {
324 /// A cleanup to free the exception object if its initialization
325 /// throws.
John McCall3ad32c82011-01-28 08:37:24 +0000326 struct FreeException {
327 static void Emit(CodeGenFunction &CGF, bool forEH,
328 llvm::Value *exn) {
329 CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
John McCall09faeab2010-07-13 21:17:51 +0000330 ->setDoesNotThrow();
John McCall09faeab2010-07-13 21:17:51 +0000331 }
332 };
333}
334
John McCallac418162010-04-22 01:10:34 +0000335// Emits an exception expression into the given location. This
336// differs from EmitAnyExprToMem only in that, if a final copy-ctor
337// call is required, an exception within that copy ctor causes
338// std::terminate to be invoked.
John McCall3ad32c82011-01-28 08:37:24 +0000339static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
340 llvm::Value *addr) {
John McCallf1549f62010-07-06 01:34:17 +0000341 // Make sure the exception object is cleaned up if there's an
342 // exception during initialization.
John McCall3ad32c82011-01-28 08:37:24 +0000343 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
344 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCallac418162010-04-22 01:10:34 +0000345
346 // __cxa_allocate_exception returns a void*; we need to cast this
347 // to the appropriate type for the object.
John McCall3ad32c82011-01-28 08:37:24 +0000348 const llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
349 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCallac418162010-04-22 01:10:34 +0000350
351 // FIXME: this isn't quite right! If there's a final unelided call
352 // to a copy constructor, then according to [except.terminate]p1 we
353 // must call std::terminate() if that constructor throws, because
354 // technically that copy occurs after the exception expression is
355 // evaluated but before the exception is caught. But the best way
356 // to handle that is to teach EmitAggExpr to do the final copy
357 // differently if it can't be elided.
John McCall3ad32c82011-01-28 08:37:24 +0000358 CGF.EmitAnyExprToMem(e, typedAddr, /*Volatile*/ false, /*IsInit*/ true);
John McCallac418162010-04-22 01:10:34 +0000359
John McCall3ad32c82011-01-28 08:37:24 +0000360 // Deactivate the cleanup block.
361 CGF.DeactivateCleanupBlock(cleanup);
Mike Stump0f590be2009-12-01 03:41:18 +0000362}
363
John McCallf1549f62010-07-06 01:34:17 +0000364llvm::Value *CodeGenFunction::getExceptionSlot() {
365 if (!ExceptionSlot) {
366 const llvm::Type *i8p = llvm::Type::getInt8PtrTy(getLLVMContext());
367 ExceptionSlot = CreateTempAlloca(i8p, "exn.slot");
Mike Stump0f590be2009-12-01 03:41:18 +0000368 }
John McCallf1549f62010-07-06 01:34:17 +0000369 return ExceptionSlot;
Mike Stump0f590be2009-12-01 03:41:18 +0000370}
371
Anders Carlsson756b5c42009-10-30 01:42:31 +0000372void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
Anders Carlssond3379292009-10-30 02:27:02 +0000373 if (!E->getSubExpr()) {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000374 if (getInvokeDest()) {
John McCallf1549f62010-07-06 01:34:17 +0000375 Builder.CreateInvoke(getReThrowFn(*this),
376 getUnreachableBlock(),
377 getInvokeDest())
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000378 ->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000379 } else {
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000380 Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000381 Builder.CreateUnreachable();
382 }
Douglas Gregor1eb2e592010-05-16 00:44:00 +0000383
John McCallcd5b22e2011-01-12 03:41:02 +0000384 // throw is an expression, and the expression emitters expect us
385 // to leave ourselves at a valid insertion point.
386 EmitBlock(createBasicBlock("throw.cont"));
387
Anders Carlssond3379292009-10-30 02:27:02 +0000388 return;
389 }
Mike Stump8755ec32009-12-10 00:06:18 +0000390
Anders Carlssond3379292009-10-30 02:27:02 +0000391 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump8755ec32009-12-10 00:06:18 +0000392
Anders Carlssond3379292009-10-30 02:27:02 +0000393 // Now allocate the exception object.
394 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall3d3ec1c2010-04-21 10:05:39 +0000395 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump8755ec32009-12-10 00:06:18 +0000396
Anders Carlssond3379292009-10-30 02:27:02 +0000397 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
John McCallf1549f62010-07-06 01:34:17 +0000398 llvm::CallInst *ExceptionPtr =
Mike Stump8755ec32009-12-10 00:06:18 +0000399 Builder.CreateCall(AllocExceptionFn,
Anders Carlssond3379292009-10-30 02:27:02 +0000400 llvm::ConstantInt::get(SizeTy, TypeSize),
401 "exception");
John McCallf1549f62010-07-06 01:34:17 +0000402 ExceptionPtr->setDoesNotThrow();
Anders Carlsson8370c582009-12-11 00:32:37 +0000403
John McCallac418162010-04-22 01:10:34 +0000404 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump8755ec32009-12-10 00:06:18 +0000405
Anders Carlssond3379292009-10-30 02:27:02 +0000406 // Now throw the exception.
407 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Anders Carlsson82a113a2011-01-24 01:59:49 +0000408 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
409 /*ForEH=*/true);
John McCallac418162010-04-22 01:10:34 +0000410
411 // The address of the destructor. If the exception type has a
412 // trivial destructor (or isn't a record), we just pass null.
413 llvm::Constant *Dtor = 0;
414 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
415 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
416 if (!Record->hasTrivialDestructor()) {
Douglas Gregor1d110e02010-07-01 14:13:13 +0000417 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCallac418162010-04-22 01:10:34 +0000418 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
419 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
420 }
421 }
422 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump8755ec32009-12-10 00:06:18 +0000423
Mike Stump0a3816e2009-12-04 01:51:45 +0000424 if (getInvokeDest()) {
Mike Stump8755ec32009-12-10 00:06:18 +0000425 llvm::InvokeInst *ThrowCall =
John McCallf1549f62010-07-06 01:34:17 +0000426 Builder.CreateInvoke3(getThrowFn(*this),
427 getUnreachableBlock(), getInvokeDest(),
Mike Stump0a3816e2009-12-04 01:51:45 +0000428 ExceptionPtr, TypeInfo, Dtor);
429 ThrowCall->setDoesNotReturn();
Mike Stump0a3816e2009-12-04 01:51:45 +0000430 } else {
Mike Stump8755ec32009-12-10 00:06:18 +0000431 llvm::CallInst *ThrowCall =
Mike Stump0a3816e2009-12-04 01:51:45 +0000432 Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
433 ThrowCall->setDoesNotReturn();
John McCallf1549f62010-07-06 01:34:17 +0000434 Builder.CreateUnreachable();
Mike Stump0a3816e2009-12-04 01:51:45 +0000435 }
Mike Stump8755ec32009-12-10 00:06:18 +0000436
John McCallcd5b22e2011-01-12 03:41:02 +0000437 // throw is an expression, and the expression emitters expect us
438 // to leave ourselves at a valid insertion point.
439 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson756b5c42009-10-30 01:42:31 +0000440}
Mike Stump2bf701e2009-11-20 23:44:51 +0000441
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000442void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000443 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000444 return;
445
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000446 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
447 if (FD == 0)
448 return;
449 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
450 if (Proto == 0)
451 return;
452
Sebastian Redla968e972011-03-15 18:42:48 +0000453 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
454 if (isNoexceptExceptionSpec(EST)) {
455 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
456 // noexcept functions are simple terminate scopes.
457 EHStack.pushTerminate();
458 }
459 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
460 unsigned NumExceptions = Proto->getNumExceptions();
461 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000462
Sebastian Redla968e972011-03-15 18:42:48 +0000463 for (unsigned I = 0; I != NumExceptions; ++I) {
464 QualType Ty = Proto->getExceptionType(I);
465 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
466 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
467 /*ForEH=*/true);
468 Filter->setFilter(I, EHType);
469 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000470 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000471}
472
473void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
Anders Carlsson15348ae2011-02-28 02:27:16 +0000474 if (!CGM.getLangOptions().CXXExceptions)
Anders Carlssona994ee42010-02-06 23:59:05 +0000475 return;
476
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000477 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
478 if (FD == 0)
479 return;
480 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
481 if (Proto == 0)
482 return;
483
Sebastian Redla968e972011-03-15 18:42:48 +0000484 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
485 if (isNoexceptExceptionSpec(EST)) {
486 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
487 EHStack.popTerminate();
488 }
489 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
490 EHStack.popFilter();
491 }
Mike Stumpcce3d4f2009-12-07 23:38:24 +0000492}
493
Mike Stump2bf701e2009-11-20 23:44:51 +0000494void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCall59a70002010-07-07 06:56:46 +0000495 EnterCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000496 EmitStmt(S.getTryBlock());
John McCall59a70002010-07-07 06:56:46 +0000497 ExitCXXTryStmt(S);
John McCall9fc6a772010-02-19 09:25:03 +0000498}
499
John McCall59a70002010-07-07 06:56:46 +0000500void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +0000501 unsigned NumHandlers = S.getNumHandlers();
502 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCall9fc6a772010-02-19 09:25:03 +0000503
John McCallf1549f62010-07-06 01:34:17 +0000504 for (unsigned I = 0; I != NumHandlers; ++I) {
505 const CXXCatchStmt *C = S.getHandler(I);
John McCall9fc6a772010-02-19 09:25:03 +0000506
John McCallf1549f62010-07-06 01:34:17 +0000507 llvm::BasicBlock *Handler = createBasicBlock("catch");
508 if (C->getExceptionDecl()) {
509 // FIXME: Dropping the reference type on the type into makes it
510 // impossible to correctly implement catch-by-reference
511 // semantics for pointers. Unfortunately, this is what all
512 // existing compilers do, and it's not clear that the standard
513 // personality routine is capable of doing this right. See C++ DR 388:
514 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
515 QualType CaughtType = C->getCaughtType();
516 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall5a180392010-07-24 00:37:23 +0000517
518 llvm::Value *TypeInfo = 0;
519 if (CaughtType->isObjCObjectPointerType())
520 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
521 else
Anders Carlsson82a113a2011-01-24 01:59:49 +0000522 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallf1549f62010-07-06 01:34:17 +0000523 CatchScope->setHandler(I, TypeInfo, Handler);
524 } else {
525 // No exception decl indicates '...', a catch-all.
526 CatchScope->setCatchAllHandler(I, Handler);
527 }
528 }
John McCallf1549f62010-07-06 01:34:17 +0000529}
530
531/// Check whether this is a non-EH scope, i.e. a scope which doesn't
532/// affect exception handling. Currently, the only non-EH scopes are
533/// normal-only cleanup scopes.
534static bool isNonEHScope(const EHScope &S) {
John McCallda65ea82010-07-13 20:32:21 +0000535 switch (S.getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000536 case EHScope::Cleanup:
537 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000538 case EHScope::Filter:
539 case EHScope::Catch:
540 case EHScope::Terminate:
541 return false;
542 }
543
544 // Suppress warning.
545 return false;
John McCallf1549f62010-07-06 01:34:17 +0000546}
547
548llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
549 assert(EHStack.requiresLandingPad());
550 assert(!EHStack.empty());
551
Anders Carlsson7a178512011-02-28 00:33:03 +0000552 if (!CGM.getLangOptions().Exceptions)
John McCallda65ea82010-07-13 20:32:21 +0000553 return 0;
554
John McCallf1549f62010-07-06 01:34:17 +0000555 // Check the innermost scope for a cached landing pad. If this is
556 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
557 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
558 if (LP) return LP;
559
560 // Build the landing pad for this scope.
561 LP = EmitLandingPad();
562 assert(LP);
563
564 // Cache the landing pad on the innermost scope. If this is a
565 // non-EH scope, cache the landing pad on the enclosing scope, too.
566 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
567 ir->setCachedLandingPad(LP);
568 if (!isNonEHScope(*ir)) break;
569 }
570
571 return LP;
572}
573
574llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
575 assert(EHStack.requiresLandingPad());
576
577 // This function contains a hack to work around a design flaw in
578 // LLVM's EH IR which breaks semantics after inlining. This same
579 // hack is implemented in llvm-gcc.
580 //
581 // The LLVM EH abstraction is basically a thin veneer over the
582 // traditional GCC zero-cost design: for each range of instructions
583 // in the function, there is (at most) one "landing pad" with an
584 // associated chain of EH actions. A language-specific personality
585 // function interprets this chain of actions and (1) decides whether
586 // or not to resume execution at the landing pad and (2) if so,
587 // provides an integer indicating why it's stopping. In LLVM IR,
588 // the association of a landing pad with a range of instructions is
589 // achieved via an invoke instruction, the chain of actions becomes
590 // the arguments to the @llvm.eh.selector call, and the selector
591 // call returns the integer indicator. Other than the required
592 // presence of two intrinsic function calls in the landing pad,
593 // the IR exactly describes the layout of the output code.
594 //
595 // A principal advantage of this design is that it is completely
596 // language-agnostic; in theory, the LLVM optimizers can treat
597 // landing pads neutrally, and targets need only know how to lower
598 // the intrinsics to have a functioning exceptions system (assuming
599 // that platform exceptions follow something approximately like the
600 // GCC design). Unfortunately, landing pads cannot be combined in a
601 // language-agnostic way: given selectors A and B, there is no way
602 // to make a single landing pad which faithfully represents the
603 // semantics of propagating an exception first through A, then
604 // through B, without knowing how the personality will interpret the
605 // (lowered form of the) selectors. This means that inlining has no
606 // choice but to crudely chain invokes (i.e., to ignore invokes in
607 // the inlined function, but to turn all unwindable calls into
608 // invokes), which is only semantically valid if every unwind stops
609 // at every landing pad.
610 //
611 // Therefore, the invoke-inline hack is to guarantee that every
612 // landing pad has a catch-all.
613 const bool UseInvokeInlineHack = true;
614
615 for (EHScopeStack::iterator ir = EHStack.begin(); ; ) {
616 assert(ir != EHStack.end() &&
617 "stack requiring landing pad is nothing but non-EH scopes?");
618
619 // If this is a terminate scope, just use the singleton terminate
620 // landing pad.
621 if (isa<EHTerminateScope>(*ir))
622 return getTerminateLandingPad();
623
624 // If this isn't an EH scope, iterate; otherwise break out.
625 if (!isNonEHScope(*ir)) break;
626 ++ir;
627
628 // We haven't checked this scope for a cached landing pad yet.
629 if (llvm::BasicBlock *LP = ir->getCachedLandingPad())
630 return LP;
631 }
632
633 // Save the current IR generation state.
634 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
635
John McCalld16c2cf2011-02-08 08:22:06 +0000636 const EHPersonality &Personality = EHPersonality::get(getLangOptions());
John McCall8262b6a2010-07-17 00:43:08 +0000637
John McCallf1549f62010-07-06 01:34:17 +0000638 // Create and configure the landing pad.
639 llvm::BasicBlock *LP = createBasicBlock("lpad");
640 EmitBlock(LP);
641
642 // Save the exception pointer. It's safe to use a single exception
643 // pointer per function because EH cleanups can never have nested
644 // try/catches.
645 llvm::CallInst *Exn =
646 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
647 Exn->setDoesNotThrow();
648 Builder.CreateStore(Exn, getExceptionSlot());
649
650 // Build the selector arguments.
651 llvm::SmallVector<llvm::Value*, 8> EHSelector;
652 EHSelector.push_back(Exn);
John McCallb2593832010-09-16 06:16:50 +0000653 EHSelector.push_back(getOpaquePersonalityFn(CGM, Personality));
John McCallf1549f62010-07-06 01:34:17 +0000654
655 // Accumulate all the handlers in scope.
John McCallff8e1152010-07-23 21:56:41 +0000656 llvm::DenseMap<llvm::Value*, UnwindDest> EHHandlers;
657 UnwindDest CatchAll;
John McCallf1549f62010-07-06 01:34:17 +0000658 bool HasEHCleanup = false;
659 bool HasEHFilter = false;
660 llvm::SmallVector<llvm::Value*, 8> EHFilters;
661 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
662 I != E; ++I) {
663
664 switch (I->getKind()) {
John McCall1f0fca52010-07-21 07:22:38 +0000665 case EHScope::Cleanup:
John McCallda65ea82010-07-13 20:32:21 +0000666 if (!HasEHCleanup)
John McCall1f0fca52010-07-21 07:22:38 +0000667 HasEHCleanup = cast<EHCleanupScope>(*I).isEHCleanup();
John McCallda65ea82010-07-13 20:32:21 +0000668 // We otherwise don't care about cleanups.
669 continue;
670
John McCallf1549f62010-07-06 01:34:17 +0000671 case EHScope::Filter: {
672 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCallff8e1152010-07-23 21:56:41 +0000673 assert(!CatchAll.isValid() && "EH filter reached after catch-all");
John McCallf1549f62010-07-06 01:34:17 +0000674
675 // Filter scopes get added to the selector in wierd ways.
676 EHFilterScope &Filter = cast<EHFilterScope>(*I);
677 HasEHFilter = true;
678
679 // Add all the filter values which we aren't already explicitly
680 // catching.
681 for (unsigned I = 0, E = Filter.getNumFilters(); I != E; ++I) {
682 llvm::Value *FV = Filter.getFilter(I);
683 if (!EHHandlers.count(FV))
684 EHFilters.push_back(FV);
685 }
686 goto done;
687 }
688
689 case EHScope::Terminate:
690 // Terminate scopes are basically catch-alls.
John McCallff8e1152010-07-23 21:56:41 +0000691 assert(!CatchAll.isValid());
692 CatchAll = UnwindDest(getTerminateHandler(),
693 EHStack.getEnclosingEHCleanup(I),
694 cast<EHTerminateScope>(*I).getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000695 goto done;
696
697 case EHScope::Catch:
698 break;
699 }
700
701 EHCatchScope &Catch = cast<EHCatchScope>(*I);
702 for (unsigned HI = 0, HE = Catch.getNumHandlers(); HI != HE; ++HI) {
703 EHCatchScope::Handler Handler = Catch.getHandler(HI);
704
705 // Catch-all. We should only have one of these per catch.
706 if (!Handler.Type) {
John McCallff8e1152010-07-23 21:56:41 +0000707 assert(!CatchAll.isValid());
708 CatchAll = UnwindDest(Handler.Block,
709 EHStack.getEnclosingEHCleanup(I),
710 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000711 continue;
712 }
713
714 // Check whether we already have a handler for this type.
John McCallff8e1152010-07-23 21:56:41 +0000715 UnwindDest &Dest = EHHandlers[Handler.Type];
716 if (Dest.isValid()) continue;
John McCallf1549f62010-07-06 01:34:17 +0000717
718 EHSelector.push_back(Handler.Type);
John McCallff8e1152010-07-23 21:56:41 +0000719 Dest = UnwindDest(Handler.Block,
720 EHStack.getEnclosingEHCleanup(I),
721 Handler.Index);
John McCallf1549f62010-07-06 01:34:17 +0000722 }
723
724 // Stop if we found a catch-all.
John McCallff8e1152010-07-23 21:56:41 +0000725 if (CatchAll.isValid()) break;
John McCallf1549f62010-07-06 01:34:17 +0000726 }
727
728 done:
729 unsigned LastToEmitInLoop = EHSelector.size();
730
731 // If we have a catch-all, add null to the selector.
John McCallff8e1152010-07-23 21:56:41 +0000732 if (CatchAll.isValid()) {
John McCalld16c2cf2011-02-08 08:22:06 +0000733 EHSelector.push_back(getCatchAllValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000734
735 // If we have an EH filter, we need to add those handlers in the
736 // right place in the selector, which is to say, at the end.
737 } else if (HasEHFilter) {
738 // Create a filter expression: an integer constant saying how many
739 // filters there are (+1 to avoid ambiguity with 0 for cleanup),
740 // followed by the filter types. The personality routine only
741 // lands here if the filter doesn't match.
742 EHSelector.push_back(llvm::ConstantInt::get(Builder.getInt32Ty(),
743 EHFilters.size() + 1));
744 EHSelector.append(EHFilters.begin(), EHFilters.end());
745
746 // Also check whether we need a cleanup.
747 if (UseInvokeInlineHack || HasEHCleanup)
748 EHSelector.push_back(UseInvokeInlineHack
John McCalld16c2cf2011-02-08 08:22:06 +0000749 ? getCatchAllValue(*this)
750 : getCleanupValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000751
752 // Otherwise, signal that we at least have cleanups.
753 } else if (UseInvokeInlineHack || HasEHCleanup) {
754 EHSelector.push_back(UseInvokeInlineHack
John McCalld16c2cf2011-02-08 08:22:06 +0000755 ? getCatchAllValue(*this)
756 : getCleanupValue(*this));
John McCallf1549f62010-07-06 01:34:17 +0000757 } else {
758 assert(LastToEmitInLoop > 2);
759 LastToEmitInLoop--;
760 }
761
762 assert(EHSelector.size() >= 3 && "selector call has only two arguments!");
763
764 // Tell the backend how to generate the landing pad.
765 llvm::CallInst *Selection =
766 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
767 EHSelector.begin(), EHSelector.end(), "eh.selector");
768 Selection->setDoesNotThrow();
769
770 // Select the right handler.
771 llvm::Value *llvm_eh_typeid_for =
772 CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
773
774 // The results of llvm_eh_typeid_for aren't reliable --- at least
775 // not locally --- so we basically have to do this as an 'if' chain.
776 // We walk through the first N-1 catch clauses, testing and chaining,
777 // and then fall into the final clause (which is either a cleanup, a
778 // filter (possibly with a cleanup), a catch-all, or another catch).
779 for (unsigned I = 2; I != LastToEmitInLoop; ++I) {
780 llvm::Value *Type = EHSelector[I];
John McCallff8e1152010-07-23 21:56:41 +0000781 UnwindDest Dest = EHHandlers[Type];
782 assert(Dest.isValid() && "no handler entry for value in selector?");
John McCallf1549f62010-07-06 01:34:17 +0000783
784 // Figure out where to branch on a match. As a debug code-size
785 // optimization, if the scope depth matches the innermost cleanup,
786 // we branch directly to the catch handler.
John McCallff8e1152010-07-23 21:56:41 +0000787 llvm::BasicBlock *Match = Dest.getBlock();
788 bool MatchNeedsCleanup =
789 Dest.getScopeDepth() != EHStack.getInnermostEHCleanup();
John McCallf1549f62010-07-06 01:34:17 +0000790 if (MatchNeedsCleanup)
791 Match = createBasicBlock("eh.match");
792
793 llvm::BasicBlock *Next = createBasicBlock("eh.next");
794
795 // Check whether the exception matches.
796 llvm::CallInst *Id
797 = Builder.CreateCall(llvm_eh_typeid_for,
John McCalld16c2cf2011-02-08 08:22:06 +0000798 Builder.CreateBitCast(Type, Int8PtrTy));
John McCallf1549f62010-07-06 01:34:17 +0000799 Id->setDoesNotThrow();
800 Builder.CreateCondBr(Builder.CreateICmpEQ(Selection, Id),
801 Match, Next);
802
803 // Emit match code if necessary.
804 if (MatchNeedsCleanup) {
805 EmitBlock(Match);
806 EmitBranchThroughEHCleanup(Dest);
807 }
808
809 // Continue to the next match.
810 EmitBlock(Next);
811 }
812
813 // Emit the final case in the selector.
814 // This might be a catch-all....
John McCallff8e1152010-07-23 21:56:41 +0000815 if (CatchAll.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000816 assert(isa<llvm::ConstantPointerNull>(EHSelector.back()));
817 EmitBranchThroughEHCleanup(CatchAll);
818
819 // ...or an EH filter...
820 } else if (HasEHFilter) {
821 llvm::Value *SavedSelection = Selection;
822
823 // First, unwind out to the outermost scope if necessary.
824 if (EHStack.hasEHCleanups()) {
825 // The end here might not dominate the beginning, so we might need to
826 // save the selector if we need it.
827 llvm::AllocaInst *SelectorVar = 0;
828 if (HasEHCleanup) {
829 SelectorVar = CreateTempAlloca(Builder.getInt32Ty(), "selector.var");
830 Builder.CreateStore(Selection, SelectorVar);
831 }
832
833 llvm::BasicBlock *CleanupContBB = createBasicBlock("ehspec.cleanup.cont");
John McCallff8e1152010-07-23 21:56:41 +0000834 EmitBranchThroughEHCleanup(UnwindDest(CleanupContBB, EHStack.stable_end(),
835 EHStack.getNextEHDestIndex()));
John McCallf1549f62010-07-06 01:34:17 +0000836 EmitBlock(CleanupContBB);
837
838 if (HasEHCleanup)
839 SavedSelection = Builder.CreateLoad(SelectorVar, "ehspec.saved-selector");
840 }
841
842 // If there was a cleanup, we'll need to actually check whether we
843 // landed here because the filter triggered.
844 if (UseInvokeInlineHack || HasEHCleanup) {
845 llvm::BasicBlock *RethrowBB = createBasicBlock("cleanup");
846 llvm::BasicBlock *UnexpectedBB = createBasicBlock("ehspec.unexpected");
847
848 llvm::Constant *Zero = llvm::ConstantInt::get(Builder.getInt32Ty(), 0);
849 llvm::Value *FailsFilter =
850 Builder.CreateICmpSLT(SavedSelection, Zero, "ehspec.fails");
851 Builder.CreateCondBr(FailsFilter, UnexpectedBB, RethrowBB);
852
853 // The rethrow block is where we land if this was a cleanup.
854 // TODO: can this be _Unwind_Resume if the InvokeInlineHack is off?
855 EmitBlock(RethrowBB);
856 Builder.CreateCall(getUnwindResumeOrRethrowFn(),
857 Builder.CreateLoad(getExceptionSlot()))
858 ->setDoesNotReturn();
859 Builder.CreateUnreachable();
860
861 EmitBlock(UnexpectedBB);
862 }
863
864 // Call __cxa_call_unexpected. This doesn't need to be an invoke
865 // because __cxa_call_unexpected magically filters exceptions
866 // according to the last landing pad the exception was thrown
867 // into. Seriously.
868 Builder.CreateCall(getUnexpectedFn(*this),
869 Builder.CreateLoad(getExceptionSlot()))
870 ->setDoesNotReturn();
871 Builder.CreateUnreachable();
872
873 // ...or a normal catch handler...
874 } else if (!UseInvokeInlineHack && !HasEHCleanup) {
875 llvm::Value *Type = EHSelector.back();
876 EmitBranchThroughEHCleanup(EHHandlers[Type]);
877
878 // ...or a cleanup.
879 } else {
John McCallff8e1152010-07-23 21:56:41 +0000880 EmitBranchThroughEHCleanup(getRethrowDest());
John McCallf1549f62010-07-06 01:34:17 +0000881 }
882
883 // Restore the old IR generation state.
884 Builder.restoreIP(SavedIP);
885
886 return LP;
887}
888
John McCall8e3f8612010-07-13 22:12:14 +0000889namespace {
890 /// A cleanup to call __cxa_end_catch. In many cases, the caught
891 /// exception type lets us state definitively that the thrown exception
892 /// type does not have a destructor. In particular:
893 /// - Catch-alls tell us nothing, so we have to conservatively
894 /// assume that the thrown exception might have a destructor.
895 /// - Catches by reference behave according to their base types.
896 /// - Catches of non-record types will only trigger for exceptions
897 /// of non-record types, which never have destructors.
898 /// - Catches of record types can trigger for arbitrary subclasses
899 /// of the caught type, so we have to assume the actual thrown
900 /// exception type might have a throwing destructor, even if the
901 /// caught type's destructor is trivial or nothrow.
John McCall1f0fca52010-07-21 07:22:38 +0000902 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall8e3f8612010-07-13 22:12:14 +0000903 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
904 bool MightThrow;
905
906 void Emit(CodeGenFunction &CGF, bool IsForEH) {
907 if (!MightThrow) {
908 CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
909 return;
910 }
911
912 CGF.EmitCallOrInvoke(getEndCatchFn(CGF), 0, 0);
913 }
914 };
915}
916
John McCallf1549f62010-07-06 01:34:17 +0000917/// Emits a call to __cxa_begin_catch and enters a cleanup to call
918/// __cxa_end_catch.
John McCall8e3f8612010-07-13 22:12:14 +0000919///
920/// \param EndMightThrow - true if __cxa_end_catch might throw
921static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
922 llvm::Value *Exn,
923 bool EndMightThrow) {
John McCallf1549f62010-07-06 01:34:17 +0000924 llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
925 Call->setDoesNotThrow();
926
John McCall1f0fca52010-07-21 07:22:38 +0000927 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallf1549f62010-07-06 01:34:17 +0000928
929 return Call;
930}
931
932/// A "special initializer" callback for initializing a catch
933/// parameter during catch initialization.
934static void InitCatchParam(CodeGenFunction &CGF,
935 const VarDecl &CatchParam,
936 llvm::Value *ParamAddr) {
937 // Load the exception from where the landing pad saved it.
938 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
939
940 CanQualType CatchType =
941 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
942 const llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
943
944 // If we're catching by reference, we can just cast the object
945 // pointer to the appropriate pointer.
946 if (isa<ReferenceType>(CatchType)) {
John McCall204b0752010-07-20 22:17:55 +0000947 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
948 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall8e3f8612010-07-13 22:12:14 +0000949
John McCallf1549f62010-07-06 01:34:17 +0000950 // __cxa_begin_catch returns the adjusted object pointer.
John McCall8e3f8612010-07-13 22:12:14 +0000951 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall204b0752010-07-20 22:17:55 +0000952
953 // We have no way to tell the personality function that we're
954 // catching by reference, so if we're catching a pointer,
955 // __cxa_begin_catch will actually return that pointer by value.
956 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
957 QualType PointeeType = PT->getPointeeType();
958
959 // When catching by reference, generally we should just ignore
960 // this by-value pointer and use the exception object instead.
961 if (!PointeeType->isRecordType()) {
962
963 // Exn points to the struct _Unwind_Exception header, which
964 // we have to skip past in order to reach the exception data.
965 unsigned HeaderSize =
966 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
967 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
968
969 // However, if we're catching a pointer-to-record type that won't
970 // work, because the personality function might have adjusted
971 // the pointer. There's actually no way for us to fully satisfy
972 // the language/ABI contract here: we can't use Exn because it
973 // might have the wrong adjustment, but we can't use the by-value
974 // pointer because it's off by a level of abstraction.
975 //
976 // The current solution is to dump the adjusted pointer into an
977 // alloca, which breaks language semantics (because changing the
978 // pointer doesn't change the exception) but at least works.
979 // The better solution would be to filter out non-exact matches
980 // and rethrow them, but this is tricky because the rethrow
981 // really needs to be catchable by other sites at this landing
982 // pad. The best solution is to fix the personality function.
983 } else {
984 // Pull the pointer for the reference type off.
985 const llvm::Type *PtrTy =
986 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
987
988 // Create the temporary and write the adjusted pointer into it.
989 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
990 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
991 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
992
993 // Bind the reference to the temporary.
994 AdjustedExn = ExnPtrTmp;
995 }
996 }
997
John McCallf1549f62010-07-06 01:34:17 +0000998 llvm::Value *ExnCast =
999 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1000 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1001 return;
1002 }
1003
1004 // Non-aggregates (plus complexes).
1005 bool IsComplex = false;
1006 if (!CGF.hasAggregateLLVMType(CatchType) ||
1007 (IsComplex = CatchType->isAnyComplexType())) {
John McCall8e3f8612010-07-13 22:12:14 +00001008 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallf1549f62010-07-06 01:34:17 +00001009
1010 // If the catch type is a pointer type, __cxa_begin_catch returns
1011 // the pointer by value.
1012 if (CatchType->hasPointerRepresentation()) {
1013 llvm::Value *CastExn =
1014 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
1015 CGF.Builder.CreateStore(CastExn, ParamAddr);
1016 return;
1017 }
1018
1019 // Otherwise, it returns a pointer into the exception object.
1020
1021 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1022 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1023
1024 if (IsComplex) {
1025 CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
1026 ParamAddr, /*volatile*/ false);
1027 } else {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001028 unsigned Alignment =
1029 CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
John McCallf1549f62010-07-06 01:34:17 +00001030 llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001031 CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
1032 CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001033 }
1034 return;
1035 }
1036
John McCallacff6962011-02-16 08:39:19 +00001037 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallf1549f62010-07-06 01:34:17 +00001038
1039 const llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
1040
John McCallacff6962011-02-16 08:39:19 +00001041 // Check for a copy expression. If we don't have a copy expression,
1042 // that means a trivial copy is okay.
John McCalle996ffd2011-02-16 08:02:54 +00001043 const Expr *copyExpr = CatchParam.getInit();
1044 if (!copyExpr) {
John McCallacff6962011-02-16 08:39:19 +00001045 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1046 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
1047 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallf1549f62010-07-06 01:34:17 +00001048 return;
1049 }
1050
1051 // We have to call __cxa_get_exception_ptr to get the adjusted
1052 // pointer before copying.
John McCalle996ffd2011-02-16 08:02:54 +00001053 llvm::CallInst *rawAdjustedExn =
John McCallf1549f62010-07-06 01:34:17 +00001054 CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
John McCalle996ffd2011-02-16 08:02:54 +00001055 rawAdjustedExn->setDoesNotThrow();
John McCallf1549f62010-07-06 01:34:17 +00001056
John McCalle996ffd2011-02-16 08:02:54 +00001057 // Cast that to the appropriate type.
1058 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallf1549f62010-07-06 01:34:17 +00001059
John McCalle996ffd2011-02-16 08:02:54 +00001060 // The copy expression is defined in terms of an OpaqueValueExpr.
1061 // Find it and map it to the adjusted expression.
1062 CodeGenFunction::OpaqueValueMapping
John McCall56ca35d2011-02-17 10:25:35 +00001063 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1064 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallf1549f62010-07-06 01:34:17 +00001065
1066 // Call the copy ctor in a terminate scope.
1067 CGF.EHStack.pushTerminate();
John McCalle996ffd2011-02-16 08:02:54 +00001068
1069 // Perform the copy construction.
1070 CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, false, false));
1071
1072 // Leave the terminate scope.
John McCallf1549f62010-07-06 01:34:17 +00001073 CGF.EHStack.popTerminate();
1074
John McCalle996ffd2011-02-16 08:02:54 +00001075 // Undo the opaque value mapping.
1076 opaque.pop();
1077
John McCallf1549f62010-07-06 01:34:17 +00001078 // Finally we can call __cxa_begin_catch.
John McCall8e3f8612010-07-13 22:12:14 +00001079 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001080}
1081
1082/// Begins a catch statement by initializing the catch variable and
1083/// calling __cxa_begin_catch.
John McCalle996ffd2011-02-16 08:02:54 +00001084static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallf1549f62010-07-06 01:34:17 +00001085 // We have to be very careful with the ordering of cleanups here:
1086 // C++ [except.throw]p4:
1087 // The destruction [of the exception temporary] occurs
1088 // immediately after the destruction of the object declared in
1089 // the exception-declaration in the handler.
1090 //
1091 // So the precise ordering is:
1092 // 1. Construct catch variable.
1093 // 2. __cxa_begin_catch
1094 // 3. Enter __cxa_end_catch cleanup
1095 // 4. Enter dtor cleanup
1096 //
John McCall34695852011-02-22 06:44:22 +00001097 // We do this by using a slightly abnormal initialization process.
1098 // Delegation sequence:
John McCallf1549f62010-07-06 01:34:17 +00001099 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCall34695852011-02-22 06:44:22 +00001100 // - EmitAutoVarAlloca creates the variable and debug info
John McCallf1549f62010-07-06 01:34:17 +00001101 // - InitCatchParam initializes the variable from the exception
John McCall34695852011-02-22 06:44:22 +00001102 // - CallBeginCatch calls __cxa_begin_catch
1103 // - CallBeginCatch enters the __cxa_end_catch cleanup
1104 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallf1549f62010-07-06 01:34:17 +00001105 // - EmitCXXTryStmt emits the code for the catch body
1106 // - EmitCXXTryStmt close the RunCleanupsScope
1107
1108 VarDecl *CatchParam = S->getExceptionDecl();
1109 if (!CatchParam) {
1110 llvm::Value *Exn = CGF.Builder.CreateLoad(CGF.getExceptionSlot(), "exn");
John McCall8e3f8612010-07-13 22:12:14 +00001111 CallBeginCatch(CGF, Exn, true);
John McCallf1549f62010-07-06 01:34:17 +00001112 return;
1113 }
1114
1115 // Emit the local.
John McCall34695852011-02-22 06:44:22 +00001116 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
1117 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
1118 CGF.EmitAutoVarCleanups(var);
John McCall9fc6a772010-02-19 09:25:03 +00001119}
1120
John McCallfcd5c0c2010-07-13 22:24:23 +00001121namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001122 struct CallRethrow : EHScopeStack::Cleanup {
John McCallfcd5c0c2010-07-13 22:24:23 +00001123 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1124 CGF.EmitCallOrInvoke(getReThrowFn(CGF), 0, 0);
1125 }
1126 };
1127}
1128
John McCall59a70002010-07-07 06:56:46 +00001129void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallf1549f62010-07-06 01:34:17 +00001130 unsigned NumHandlers = S.getNumHandlers();
1131 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1132 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump2bf701e2009-11-20 23:44:51 +00001133
John McCallf1549f62010-07-06 01:34:17 +00001134 // Copy the handler blocks off before we pop the EH stack. Emitting
1135 // the handlers might scribble on this memory.
1136 llvm::SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
1137 memcpy(Handlers.data(), CatchScope.begin(),
1138 NumHandlers * sizeof(EHCatchScope::Handler));
1139 EHStack.popCatch();
Mike Stump2bf701e2009-11-20 23:44:51 +00001140
John McCallf1549f62010-07-06 01:34:17 +00001141 // The fall-through block.
1142 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump2bf701e2009-11-20 23:44:51 +00001143
John McCallf1549f62010-07-06 01:34:17 +00001144 // We just emitted the body of the try; jump to the continue block.
1145 if (HaveInsertPoint())
1146 Builder.CreateBr(ContBB);
Mike Stump639787c2009-12-02 19:53:57 +00001147
John McCall59a70002010-07-07 06:56:46 +00001148 // Determine if we need an implicit rethrow for all these catch handlers.
1149 bool ImplicitRethrow = false;
1150 if (IsFnTryBlock)
1151 ImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1152 isa<CXXConstructorDecl>(CurCodeDecl);
1153
John McCallf1549f62010-07-06 01:34:17 +00001154 for (unsigned I = 0; I != NumHandlers; ++I) {
1155 llvm::BasicBlock *CatchBlock = Handlers[I].Block;
1156 EmitBlock(CatchBlock);
Mike Stump8755ec32009-12-10 00:06:18 +00001157
John McCallf1549f62010-07-06 01:34:17 +00001158 // Catch the exception if this isn't a catch-all.
1159 const CXXCatchStmt *C = S.getHandler(I);
Mike Stump2bf701e2009-11-20 23:44:51 +00001160
John McCallf1549f62010-07-06 01:34:17 +00001161 // Enter a cleanup scope, including the catch variable and the
1162 // end-catch.
1163 RunCleanupsScope CatchScope(*this);
Mike Stump2bf701e2009-11-20 23:44:51 +00001164
John McCallf1549f62010-07-06 01:34:17 +00001165 // Initialize the catch variable and set up the cleanups.
1166 BeginCatch(*this, C);
1167
John McCall59a70002010-07-07 06:56:46 +00001168 // If there's an implicit rethrow, push a normal "cleanup" to call
John McCallfcd5c0c2010-07-13 22:24:23 +00001169 // _cxa_rethrow. This needs to happen before __cxa_end_catch is
1170 // called, and so it is pushed after BeginCatch.
1171 if (ImplicitRethrow)
John McCall1f0fca52010-07-21 07:22:38 +00001172 EHStack.pushCleanup<CallRethrow>(NormalCleanup);
John McCall59a70002010-07-07 06:56:46 +00001173
John McCallf1549f62010-07-06 01:34:17 +00001174 // Perform the body of the catch.
1175 EmitStmt(C->getHandlerBlock());
1176
1177 // Fall out through the catch cleanups.
1178 CatchScope.ForceCleanup();
1179
1180 // Branch out of the try.
1181 if (HaveInsertPoint())
1182 Builder.CreateBr(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001183 }
1184
John McCallf1549f62010-07-06 01:34:17 +00001185 EmitBlock(ContBB);
Mike Stump2bf701e2009-11-20 23:44:51 +00001186}
Mike Stumpd88ea562009-12-09 03:35:49 +00001187
John McCall55b20fc2010-07-21 00:52:03 +00001188namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001189 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall55b20fc2010-07-21 00:52:03 +00001190 llvm::Value *ForEHVar;
1191 llvm::Value *EndCatchFn;
1192 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1193 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1194
1195 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1196 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1197 llvm::BasicBlock *CleanupContBB =
1198 CGF.createBasicBlock("finally.cleanup.cont");
1199
1200 llvm::Value *ShouldEndCatch =
1201 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1202 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1203 CGF.EmitBlock(EndCatchBB);
1204 CGF.EmitCallOrInvoke(EndCatchFn, 0, 0); // catch-all, so might throw
1205 CGF.EmitBlock(CleanupContBB);
1206 }
1207 };
John McCall77199712010-07-21 05:47:49 +00001208
John McCall1f0fca52010-07-21 07:22:38 +00001209 struct PerformFinally : EHScopeStack::Cleanup {
John McCall77199712010-07-21 05:47:49 +00001210 const Stmt *Body;
1211 llvm::Value *ForEHVar;
1212 llvm::Value *EndCatchFn;
1213 llvm::Value *RethrowFn;
1214 llvm::Value *SavedExnVar;
1215
1216 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1217 llvm::Value *EndCatchFn,
1218 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1219 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1220 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1221
1222 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1223 // Enter a cleanup to call the end-catch function if one was provided.
1224 if (EndCatchFn)
John McCall1f0fca52010-07-21 07:22:38 +00001225 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1226 ForEHVar, EndCatchFn);
John McCall77199712010-07-21 05:47:49 +00001227
John McCalld96a8e72010-08-11 00:16:14 +00001228 // Save the current cleanup destination in case there are
1229 // cleanups in the finally block.
1230 llvm::Value *SavedCleanupDest =
1231 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1232 "cleanup.dest.saved");
1233
John McCall77199712010-07-21 05:47:49 +00001234 // Emit the finally block.
1235 CGF.EmitStmt(Body);
1236
1237 // If the end of the finally is reachable, check whether this was
1238 // for EH. If so, rethrow.
1239 if (CGF.HaveInsertPoint()) {
1240 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1241 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1242
1243 llvm::Value *ShouldRethrow =
1244 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1245 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1246
1247 CGF.EmitBlock(RethrowBB);
1248 if (SavedExnVar) {
1249 llvm::Value *Args[] = { CGF.Builder.CreateLoad(SavedExnVar) };
1250 CGF.EmitCallOrInvoke(RethrowFn, Args, Args+1);
1251 } else {
1252 CGF.EmitCallOrInvoke(RethrowFn, 0, 0);
1253 }
1254 CGF.Builder.CreateUnreachable();
1255
1256 CGF.EmitBlock(ContBB);
John McCalld96a8e72010-08-11 00:16:14 +00001257
1258 // Restore the cleanup destination.
1259 CGF.Builder.CreateStore(SavedCleanupDest,
1260 CGF.getNormalCleanupDestSlot());
John McCall77199712010-07-21 05:47:49 +00001261 }
1262
1263 // Leave the end-catch cleanup. As an optimization, pretend that
1264 // the fallthrough path was inaccessible; we've dynamically proven
1265 // that we're not in the EH case along that path.
1266 if (EndCatchFn) {
1267 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1268 CGF.PopCleanupBlock();
1269 CGF.Builder.restoreIP(SavedIP);
1270 }
1271
1272 // Now make sure we actually have an insertion point or the
1273 // cleanup gods will hate us.
1274 CGF.EnsureInsertPoint();
1275 }
1276 };
John McCall55b20fc2010-07-21 00:52:03 +00001277}
1278
John McCallf1549f62010-07-06 01:34:17 +00001279/// Enters a finally block for an implementation using zero-cost
1280/// exceptions. This is mostly general, but hard-codes some
1281/// language/ABI-specific behavior in the catch-all sections.
1282CodeGenFunction::FinallyInfo
1283CodeGenFunction::EnterFinallyBlock(const Stmt *Body,
1284 llvm::Constant *BeginCatchFn,
1285 llvm::Constant *EndCatchFn,
1286 llvm::Constant *RethrowFn) {
1287 assert((BeginCatchFn != 0) == (EndCatchFn != 0) &&
1288 "begin/end catch functions not paired");
1289 assert(RethrowFn && "rethrow function is required");
Mike Stumpd88ea562009-12-09 03:35:49 +00001290
John McCallf1549f62010-07-06 01:34:17 +00001291 // The rethrow function has one of the following two types:
1292 // void (*)()
1293 // void (*)(void*)
1294 // In the latter case we need to pass it the exception object.
1295 // But we can't use the exception slot because the @finally might
1296 // have a landing pad (which would overwrite the exception slot).
1297 const llvm::FunctionType *RethrowFnTy =
1298 cast<llvm::FunctionType>(
1299 cast<llvm::PointerType>(RethrowFn->getType())
1300 ->getElementType());
1301 llvm::Value *SavedExnVar = 0;
1302 if (RethrowFnTy->getNumParams())
1303 SavedExnVar = CreateTempAlloca(Builder.getInt8PtrTy(), "finally.exn");
Mike Stumpd88ea562009-12-09 03:35:49 +00001304
John McCallf1549f62010-07-06 01:34:17 +00001305 // A finally block is a statement which must be executed on any edge
1306 // out of a given scope. Unlike a cleanup, the finally block may
1307 // contain arbitrary control flow leading out of itself. In
1308 // addition, finally blocks should always be executed, even if there
1309 // are no catch handlers higher on the stack. Therefore, we
1310 // surround the protected scope with a combination of a normal
1311 // cleanup (to catch attempts to break out of the block via normal
1312 // control flow) and an EH catch-all (semantically "outside" any try
1313 // statement to which the finally block might have been attached).
1314 // The finally block itself is generated in the context of a cleanup
1315 // which conditionally leaves the catch-all.
John McCall3d3ec1c2010-04-21 10:05:39 +00001316
John McCallf1549f62010-07-06 01:34:17 +00001317 FinallyInfo Info;
John McCall3d3ec1c2010-04-21 10:05:39 +00001318
John McCallf1549f62010-07-06 01:34:17 +00001319 // Jump destination for performing the finally block on an exception
1320 // edge. We'll never actually reach this block, so unreachable is
1321 // fine.
1322 JumpDest RethrowDest = getJumpDestInCurrentScope(getUnreachableBlock());
John McCall3d3ec1c2010-04-21 10:05:39 +00001323
John McCallf1549f62010-07-06 01:34:17 +00001324 // Whether the finally block is being executed for EH purposes.
John McCalld16c2cf2011-02-08 08:22:06 +00001325 llvm::AllocaInst *ForEHVar = CreateTempAlloca(Builder.getInt1Ty(),
John McCallf1549f62010-07-06 01:34:17 +00001326 "finally.for-eh");
1327 InitTempAlloca(ForEHVar, llvm::ConstantInt::getFalse(getLLVMContext()));
Mike Stumpd88ea562009-12-09 03:35:49 +00001328
John McCallf1549f62010-07-06 01:34:17 +00001329 // Enter a normal cleanup which will perform the @finally block.
John McCall1f0fca52010-07-21 07:22:38 +00001330 EHStack.pushCleanup<PerformFinally>(NormalCleanup, Body,
1331 ForEHVar, EndCatchFn,
1332 RethrowFn, SavedExnVar);
John McCallf1549f62010-07-06 01:34:17 +00001333
1334 // Enter a catch-all scope.
1335 llvm::BasicBlock *CatchAllBB = createBasicBlock("finally.catchall");
1336 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1337 Builder.SetInsertPoint(CatchAllBB);
1338
1339 // If there's a begin-catch function, call it.
1340 if (BeginCatchFn) {
1341 Builder.CreateCall(BeginCatchFn, Builder.CreateLoad(getExceptionSlot()))
1342 ->setDoesNotThrow();
1343 }
1344
1345 // If we need to remember the exception pointer to rethrow later, do so.
1346 if (SavedExnVar) {
1347 llvm::Value *SavedExn = Builder.CreateLoad(getExceptionSlot());
1348 Builder.CreateStore(SavedExn, SavedExnVar);
1349 }
1350
1351 // Tell the finally block that we're in EH.
1352 Builder.CreateStore(llvm::ConstantInt::getTrue(getLLVMContext()), ForEHVar);
1353
1354 // Thread a jump through the finally cleanup.
1355 EmitBranchThroughCleanup(RethrowDest);
1356
1357 Builder.restoreIP(SavedIP);
1358
1359 EHCatchScope *CatchScope = EHStack.pushCatch(1);
1360 CatchScope->setCatchAllHandler(0, CatchAllBB);
1361
1362 return Info;
1363}
1364
1365void CodeGenFunction::ExitFinallyBlock(FinallyInfo &Info) {
1366 // Leave the finally catch-all.
1367 EHCatchScope &Catch = cast<EHCatchScope>(*EHStack.begin());
1368 llvm::BasicBlock *CatchAllBB = Catch.getHandler(0).Block;
1369 EHStack.popCatch();
1370
1371 // And leave the normal cleanup.
1372 PopCleanupBlock();
1373
1374 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1375 EmitBlock(CatchAllBB, true);
1376
1377 Builder.restoreIP(SavedIP);
1378}
1379
1380llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1381 if (TerminateLandingPad)
1382 return TerminateLandingPad;
1383
1384 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1385
1386 // This will get inserted at the end of the function.
1387 TerminateLandingPad = createBasicBlock("terminate.lpad");
1388 Builder.SetInsertPoint(TerminateLandingPad);
1389
1390 // Tell the backend that this is a landing pad.
1391 llvm::CallInst *Exn =
1392 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_exception), "exn");
1393 Exn->setDoesNotThrow();
John McCall8262b6a2010-07-17 00:43:08 +00001394
1395 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
John McCallf1549f62010-07-06 01:34:17 +00001396
1397 // Tell the backend what the exception table should be:
1398 // nothing but a catch-all.
John McCallb2593832010-09-16 06:16:50 +00001399 llvm::Value *Args[3] = { Exn, getOpaquePersonalityFn(CGM, Personality),
John McCallf1549f62010-07-06 01:34:17 +00001400 getCatchAllValue(*this) };
1401 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::eh_selector),
1402 Args, Args+3, "eh.selector")
1403 ->setDoesNotThrow();
1404
1405 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
1406 TerminateCall->setDoesNotReturn();
1407 TerminateCall->setDoesNotThrow();
John McCalld16c2cf2011-02-08 08:22:06 +00001408 Builder.CreateUnreachable();
Mike Stumpd88ea562009-12-09 03:35:49 +00001409
John McCallf1549f62010-07-06 01:34:17 +00001410 // Restore the saved insertion state.
1411 Builder.restoreIP(SavedIP);
John McCall891f80e2010-04-30 00:06:43 +00001412
John McCallf1549f62010-07-06 01:34:17 +00001413 return TerminateLandingPad;
Mike Stumpd88ea562009-12-09 03:35:49 +00001414}
Mike Stump9b39c512009-12-09 22:59:31 +00001415
1416llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stump182f3832009-12-10 00:02:42 +00001417 if (TerminateHandler)
1418 return TerminateHandler;
1419
John McCallf1549f62010-07-06 01:34:17 +00001420 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump76958092009-12-09 23:31:35 +00001421
John McCallf1549f62010-07-06 01:34:17 +00001422 // Set up the terminate handler. This block is inserted at the very
1423 // end of the function by FinishFunction.
Mike Stump182f3832009-12-10 00:02:42 +00001424 TerminateHandler = createBasicBlock("terminate.handler");
John McCallf1549f62010-07-06 01:34:17 +00001425 Builder.SetInsertPoint(TerminateHandler);
1426 llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
Mike Stump9b39c512009-12-09 22:59:31 +00001427 TerminateCall->setDoesNotReturn();
1428 TerminateCall->setDoesNotThrow();
1429 Builder.CreateUnreachable();
1430
John McCall3d3ec1c2010-04-21 10:05:39 +00001431 // Restore the saved insertion state.
John McCallf1549f62010-07-06 01:34:17 +00001432 Builder.restoreIP(SavedIP);
Mike Stump76958092009-12-09 23:31:35 +00001433
Mike Stump9b39c512009-12-09 22:59:31 +00001434 return TerminateHandler;
1435}
John McCallf1549f62010-07-06 01:34:17 +00001436
John McCallff8e1152010-07-23 21:56:41 +00001437CodeGenFunction::UnwindDest CodeGenFunction::getRethrowDest() {
1438 if (RethrowBlock.isValid()) return RethrowBlock;
1439
1440 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1441
1442 // We emit a jump to a notional label at the outermost unwind state.
1443 llvm::BasicBlock *Unwind = createBasicBlock("eh.resume");
1444 Builder.SetInsertPoint(Unwind);
1445
1446 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOptions());
1447
1448 // This can always be a call because we necessarily didn't find
1449 // anything on the EH stack which needs our help.
John McCallb2593832010-09-16 06:16:50 +00001450 llvm::StringRef RethrowName = Personality.getCatchallRethrowFnName();
John McCallff8e1152010-07-23 21:56:41 +00001451 llvm::Constant *RethrowFn;
John McCallb2593832010-09-16 06:16:50 +00001452 if (!RethrowName.empty())
John McCallff8e1152010-07-23 21:56:41 +00001453 RethrowFn = getCatchallRethrowFn(*this, RethrowName);
1454 else
1455 RethrowFn = getUnwindResumeOrRethrowFn();
1456
1457 Builder.CreateCall(RethrowFn, Builder.CreateLoad(getExceptionSlot()))
1458 ->setDoesNotReturn();
1459 Builder.CreateUnreachable();
1460
1461 Builder.restoreIP(SavedIP);
1462
1463 RethrowBlock = UnwindDest(Unwind, EHStack.stable_end(), 0);
1464 return RethrowBlock;
1465}
1466