blob: bd545234938458e9e81b3842b682c9dc24dd0b0f [file] [log] [blame]
Anders Carlsson4b08db72009-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
14#include "CodeGenFunction.h"
John McCalled1ae862011-01-28 11:13:47 +000015#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000016#include "CGObjCRuntime.h"
John McCall5add20c2010-07-20 22:17:55 +000017#include "TargetInfo.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000018#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000019#include "clang/AST/StmtObjC.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000020#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000021#include "llvm/IR/Intrinsics.h"
John McCallbd309292010-07-06 01:34:17 +000022
Anders Carlsson4b08db72009-10-30 01:42:31 +000023using namespace clang;
24using namespace CodeGen;
25
John McCall2c33ba82013-02-12 03:51:38 +000026static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000027 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump75546b82009-12-10 00:06:18 +000028
Chris Lattner2192fe52011-07-18 04:24:23 +000029 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000030 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000031
John McCall2c33ba82013-02-12 03:51:38 +000032 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000033}
34
John McCall2c33ba82013-02-12 03:51:38 +000035static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000036 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000037
Chris Lattner2192fe52011-07-18 04:24:23 +000038 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000039 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000040
John McCall2c33ba82013-02-12 03:51:38 +000041 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000042}
43
John McCall2c33ba82013-02-12 03:51:38 +000044static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
Mike Stump75546b82009-12-10 00:06:18 +000045 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +000046 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000047
John McCall2c33ba82013-02-12 03:51:38 +000048 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +000049 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000050 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000051
John McCall2c33ba82013-02-12 03:51:38 +000052 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000053}
54
John McCall2c33ba82013-02-12 03:51:38 +000055static llvm::Constant *getReThrowFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000056 // void __cxa_rethrow();
Mike Stumpd1782cc2009-11-20 00:56:31 +000057
Chris Lattner2192fe52011-07-18 04:24:23 +000058 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000059 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000060
John McCall2c33ba82013-02-12 03:51:38 +000061 return CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
Mike Stumpd1782cc2009-11-20 00:56:31 +000062}
63
John McCall2c33ba82013-02-12 03:51:38 +000064static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000065 // void *__cxa_get_exception_ptr(void*);
John McCallbd309292010-07-06 01:34:17 +000066
Chris Lattner2192fe52011-07-18 04:24:23 +000067 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000068 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCallbd309292010-07-06 01:34:17 +000069
John McCall2c33ba82013-02-12 03:51:38 +000070 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
John McCallbd309292010-07-06 01:34:17 +000071}
72
John McCall2c33ba82013-02-12 03:51:38 +000073static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000074 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +000075
Chris Lattner2192fe52011-07-18 04:24:23 +000076 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000077 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000078
John McCall2c33ba82013-02-12 03:51:38 +000079 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000080}
81
John McCall2c33ba82013-02-12 03:51:38 +000082static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000083 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +000084
Chris Lattner2192fe52011-07-18 04:24:23 +000085 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000086 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000087
John McCall2c33ba82013-02-12 03:51:38 +000088 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000089}
90
John McCall2c33ba82013-02-12 03:51:38 +000091static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000092 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000093
Chris Lattner2192fe52011-07-18 04:24:23 +000094 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000095 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000096
John McCall2c33ba82013-02-12 03:51:38 +000097 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000098}
99
John McCall9b382dd2011-05-28 21:13:02 +0000100llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
Chris Lattner2192fe52011-07-18 04:24:23 +0000101 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +0000102 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
John McCall9b382dd2011-05-28 21:13:02 +0000103
David Blaikiebbafb8a2012-03-11 07:00:24 +0000104 if (CGM.getLangOpts().SjLjExceptions)
John McCall9b382dd2011-05-28 21:13:02 +0000105 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
106 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
107}
108
109llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
Chris Lattner2192fe52011-07-18 04:24:23 +0000110 llvm::FunctionType *FTy =
Jay Foad5709f7c2011-07-29 13:56:53 +0000111 llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000112
David Blaikiebbafb8a2012-03-11 07:00:24 +0000113 if (CGM.getLangOpts().SjLjExceptions)
John McCallffe46302010-08-11 20:59:53 +0000114 return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
Douglas Gregor51150ab2010-05-16 01:24:12 +0000115 return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
Mike Stump54066142009-12-01 03:41:18 +0000116}
117
John McCall2c33ba82013-02-12 03:51:38 +0000118static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +0000119 // void __terminate();
120
Chris Lattner2192fe52011-07-18 04:24:23 +0000121 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +0000122 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +0000123
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000124 StringRef name;
John McCall9de19782011-07-06 01:22:26 +0000125
126 // In C++, use std::terminate().
John McCall2c33ba82013-02-12 03:51:38 +0000127 if (CGM.getLangOpts().CPlusPlus)
John McCall9de19782011-07-06 01:22:26 +0000128 name = "_ZSt9terminatev"; // FIXME: mangling!
John McCall2c33ba82013-02-12 03:51:38 +0000129 else if (CGM.getLangOpts().ObjC1 &&
130 CGM.getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +0000131 name = "objc_terminate";
132 else
133 name = "abort";
John McCall2c33ba82013-02-12 03:51:38 +0000134 return CGM.CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +0000135}
136
John McCall2c33ba82013-02-12 03:51:38 +0000137static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000138 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000139 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +0000140 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +0000141
John McCall2c33ba82013-02-12 03:51:38 +0000142 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000143}
144
Benjamin Kramer793bd552012-02-08 12:41:24 +0000145namespace {
146 /// The exceptions personality for a function.
147 struct EHPersonality {
148 const char *PersonalityFn;
149
150 // If this is non-null, this personality requires a non-standard
151 // function for rethrowing an exception after a catchall cleanup.
152 // This function must have prototype void(void*).
153 const char *CatchallRethrowFn;
154
155 static const EHPersonality &get(const LangOptions &Lang);
156 static const EHPersonality GNU_C;
157 static const EHPersonality GNU_C_SJLJ;
158 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000159 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000160 static const EHPersonality GNU_ObjCXX;
161 static const EHPersonality NeXT_ObjC;
162 static const EHPersonality GNU_CPlusPlus;
163 static const EHPersonality GNU_CPlusPlus_SJLJ;
164 };
165}
166
167const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", 0 };
168const EHPersonality EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", 0 };
169const EHPersonality EHPersonality::NeXT_ObjC = { "__objc_personality_v0", 0 };
170const EHPersonality EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", 0};
171const EHPersonality
172EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", 0 };
173const EHPersonality
174EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
175const EHPersonality
176EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", 0 };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000177const EHPersonality
178EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", 0 };
John McCall36ea3722010-07-17 00:43:08 +0000179
180static const EHPersonality &getCPersonality(const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000181 if (L.SjLjExceptions)
182 return EHPersonality::GNU_C_SJLJ;
John McCall36ea3722010-07-17 00:43:08 +0000183 return EHPersonality::GNU_C;
184}
185
186static const EHPersonality &getObjCPersonality(const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000187 switch (L.ObjCRuntime.getKind()) {
188 case ObjCRuntime::FragileMacOSX:
189 return getCPersonality(L);
190 case ObjCRuntime::MacOSX:
191 case ObjCRuntime::iOS:
192 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000193 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000194 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
195 return EHPersonality::GNUstep_ObjC;
196 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000197 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000198 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000199 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000200 }
John McCall5fb5df92012-06-20 06:18:46 +0000201 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000202}
203
John McCall36ea3722010-07-17 00:43:08 +0000204static const EHPersonality &getCXXPersonality(const LangOptions &L) {
205 if (L.SjLjExceptions)
206 return EHPersonality::GNU_CPlusPlus_SJLJ;
John McCallbd309292010-07-06 01:34:17 +0000207 else
John McCall36ea3722010-07-17 00:43:08 +0000208 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000209}
210
211/// Determines the personality function to use when both C++
212/// and Objective-C exceptions are being caught.
John McCall36ea3722010-07-17 00:43:08 +0000213static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000214 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000215 // The ObjC personality defers to the C++ personality for non-ObjC
216 // handlers. Unlike the C++ case, we use the same personality
217 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000218 case ObjCRuntime::MacOSX:
219 case ObjCRuntime::iOS:
220 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000221
John McCall5fb5df92012-06-20 06:18:46 +0000222 // In the fragile ABI, just use C++ exception handling and hope
223 // they're not doing crazy exception mixing.
224 case ObjCRuntime::FragileMacOSX:
225 return getCXXPersonality(L);
David Chisnallf9c42252010-05-17 13:49:20 +0000226
David Chisnallb601c962012-07-03 20:49:52 +0000227 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000228 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000229 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000230 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000231 return EHPersonality::GNU_ObjC;
232 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000233 return EHPersonality::GNU_ObjCXX;
234 }
235 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000236}
237
John McCall36ea3722010-07-17 00:43:08 +0000238const EHPersonality &EHPersonality::get(const LangOptions &L) {
239 if (L.CPlusPlus && L.ObjC1)
240 return getObjCXXPersonality(L);
241 else if (L.CPlusPlus)
242 return getCXXPersonality(L);
243 else if (L.ObjC1)
244 return getObjCPersonality(L);
John McCallbd309292010-07-06 01:34:17 +0000245 else
John McCall36ea3722010-07-17 00:43:08 +0000246 return getCPersonality(L);
247}
John McCallbd309292010-07-06 01:34:17 +0000248
John McCall0bdb1fd2010-09-16 06:16:50 +0000249static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000250 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000251 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000252 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000253 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000254 return Fn;
255}
256
257static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
258 const EHPersonality &Personality) {
259 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000260 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000261}
262
263/// Check whether a personality function could reasonably be swapped
264/// for a C++ personality function.
265static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000266 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000267 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000268 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000269 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
270 if (!PersonalityHasOnlyCXXUses(CE))
271 return false;
272 continue;
273 }
274
Bill Wendling58e58fe2011-09-19 22:08:36 +0000275 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000276 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000277 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000278
Bill Wendling58e58fe2011-09-19 22:08:36 +0000279 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000280 // Look for something that would've been returned by the ObjC
281 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000282 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
283 if (LPI->isCatch(I)) {
284 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000285 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
286 // ObjC EH selector entries are always global variables with
287 // names starting like this.
288 if (GV->getName().startswith("OBJC_EHTYPE"))
289 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000290 } else {
291 // Check if any of the filter values have the ObjC prefix.
292 llvm::Constant *CVal = cast<llvm::Constant>(Val);
293 for (llvm::User::op_iterator
294 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000295 if (llvm::GlobalVariable *GV =
296 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
297 // ObjC EH selector entries are always global variables with
298 // names starting like this.
299 if (GV->getName().startswith("OBJC_EHTYPE"))
300 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000301 }
302 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000303 }
304 }
305
306 return true;
307}
308
309/// Try to use the C++ personality function in ObjC++. Not doing this
310/// can cause some incompatibilities with gcc, which is more
311/// aggressive about only using the ObjC++ personality in a function
312/// when it really needs it.
313void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000314 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000315 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000316 return;
317
John McCall3c223932012-11-14 17:48:31 +0000318 // Both the problem this endeavors to fix and the way the logic
319 // above works is specific to the NeXT runtime.
320 if (!LangOpts.ObjCRuntime.isNeXTFamily())
321 return;
322
David Blaikiebbafb8a2012-03-11 07:00:24 +0000323 const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
324 const EHPersonality &CXX = getCXXPersonality(LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000325 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000326 return;
327
Benjamin Kramer793bd552012-02-08 12:41:24 +0000328 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
329 "Different EHPersonalities using the same personality function.");
330
331 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000332
333 // Nothing to do if it's unused.
334 if (!Fn || Fn->use_empty()) return;
335
336 // Can't do the optimization if it has non-C++ uses.
337 if (!PersonalityHasOnlyCXXUses(Fn)) return;
338
339 // Create the C++ personality function and kill off the old
340 // function.
341 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
342
343 // This can happen if the user is screwing with us.
344 if (Fn->getType() != CXXFn->getType()) return;
345
346 Fn->replaceAllUsesWith(CXXFn);
347 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000348}
349
350/// Returns the value to inject into a selector to indicate the
351/// presence of a catch-all.
352static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
353 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000354 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000355}
356
John McCallbb026012010-07-13 21:17:51 +0000357namespace {
358 /// A cleanup to free the exception object if its initialization
359 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000360 struct FreeException : EHScopeStack::Cleanup {
361 llvm::Value *exn;
362 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000363 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000364 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000365 }
366 };
367}
368
John McCall2e6567a2010-04-22 01:10:34 +0000369// Emits an exception expression into the given location. This
370// differs from EmitAnyExprToMem only in that, if a final copy-ctor
371// call is required, an exception within that copy ctor causes
372// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000373static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
374 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000375 // Make sure the exception object is cleaned up if there's an
376 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000377 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
378 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000379
380 // __cxa_allocate_exception returns a void*; we need to cast this
381 // to the appropriate type for the object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000382 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCalle4df6c82011-01-28 08:37:24 +0000383 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000384
385 // FIXME: this isn't quite right! If there's a final unelided call
386 // to a copy constructor, then according to [except.terminate]p1 we
387 // must call std::terminate() if that constructor throws, because
388 // technically that copy occurs after the exception expression is
389 // evaluated but before the exception is caught. But the best way
390 // to handle that is to teach EmitAggExpr to do the final copy
391 // differently if it can't be elided.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000392 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
393 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000394
John McCalle4df6c82011-01-28 08:37:24 +0000395 // Deactivate the cleanup block.
John McCallf4beacd2011-11-10 10:43:54 +0000396 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000397}
398
John McCallbd309292010-07-06 01:34:17 +0000399llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000400 if (!ExceptionSlot)
401 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000402 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000403}
404
John McCall9b382dd2011-05-28 21:13:02 +0000405llvm::Value *CodeGenFunction::getEHSelectorSlot() {
406 if (!EHSelectorSlot)
407 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
408 return EHSelectorSlot;
409}
410
Bill Wendling79a70e42011-09-15 18:57:19 +0000411llvm::Value *CodeGenFunction::getExceptionFromSlot() {
412 return Builder.CreateLoad(getExceptionSlot(), "exn");
413}
414
415llvm::Value *CodeGenFunction::getSelectorFromSlot() {
416 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
417}
418
Richard Smithea852322013-05-07 21:53:22 +0000419void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
420 bool KeepInsertionPoint) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000421 if (CGM.getTarget().getTriple().isWindowsMSVCEnvironment()) {
422 ErrorUnsupported(E, "throw expression");
423 return;
424 }
425
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000426 if (!E->getSubExpr()) {
John McCall882987f2013-02-28 19:01:20 +0000427 EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM),
428 ArrayRef<llvm::Value*>());
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000429
John McCall20f6ab82011-01-12 03:41:02 +0000430 // throw is an expression, and the expression emitters expect us
431 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000432 if (KeepInsertionPoint)
433 EmitBlock(createBasicBlock("throw.cont"));
John McCall20f6ab82011-01-12 03:41:02 +0000434
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000435 return;
436 }
Mike Stump75546b82009-12-10 00:06:18 +0000437
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000438 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000439
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000440 if (ThrowType->isObjCObjectPointerType()) {
441 const Stmt *ThrowStmt = E->getSubExpr();
442 const ObjCAtThrowStmt S(E->getExprLoc(),
443 const_cast<Stmt *>(ThrowStmt));
444 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
445 // This will clear insertion point which was not cleared in
446 // call to EmitThrowStmt.
Richard Smithea852322013-05-07 21:53:22 +0000447 if (KeepInsertionPoint)
448 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000449 return;
450 }
451
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000452 // Now allocate the exception object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000453 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000454 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000455
John McCall2c33ba82013-02-12 03:51:38 +0000456 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallbd309292010-07-06 01:34:17 +0000457 llvm::CallInst *ExceptionPtr =
John McCall882987f2013-02-28 19:01:20 +0000458 EmitNounwindRuntimeCall(AllocExceptionFn,
459 llvm::ConstantInt::get(SizeTy, TypeSize),
460 "exception");
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000461
John McCall2e6567a2010-04-22 01:10:34 +0000462 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000463
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000464 // Now throw the exception.
Anders Carlssonba840fb2011-01-24 01:59:49 +0000465 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
466 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000467
468 // The address of the destructor. If the exception type has a
469 // trivial destructor (or isn't a record), we just pass null.
470 llvm::Constant *Dtor = 0;
471 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
472 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
473 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000474 CXXDestructorDecl *DtorD = Record->getDestructor();
John McCall2e6567a2010-04-22 01:10:34 +0000475 Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
476 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
477 }
478 }
479 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000480
John McCall882987f2013-02-28 19:01:20 +0000481 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
482 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump75546b82009-12-10 00:06:18 +0000483
John McCall20f6ab82011-01-12 03:41:02 +0000484 // throw is an expression, and the expression emitters expect us
485 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000486 if (KeepInsertionPoint)
487 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000488}
Mike Stump58ef18b2009-11-20 23:44:51 +0000489
Mike Stump1d849212009-12-07 23:38:24 +0000490void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000491 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000492 return;
493
Mike Stump1d849212009-12-07 23:38:24 +0000494 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
495 if (FD == 0)
496 return;
497 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
498 if (Proto == 0)
499 return;
500
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000501 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
502 if (isNoexceptExceptionSpec(EST)) {
503 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
504 // noexcept functions are simple terminate scopes.
505 EHStack.pushTerminate();
506 }
507 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
508 unsigned NumExceptions = Proto->getNumExceptions();
509 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000510
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000511 for (unsigned I = 0; I != NumExceptions; ++I) {
512 QualType Ty = Proto->getExceptionType(I);
513 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
514 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
515 /*ForEH=*/true);
516 Filter->setFilter(I, EHType);
517 }
Mike Stump1d849212009-12-07 23:38:24 +0000518 }
Mike Stump1d849212009-12-07 23:38:24 +0000519}
520
John McCall8e4c74b2011-08-11 02:22:43 +0000521/// Emit the dispatch block for a filter scope if necessary.
522static void emitFilterDispatchBlock(CodeGenFunction &CGF,
523 EHFilterScope &filterScope) {
524 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
525 if (!dispatchBlock) return;
526 if (dispatchBlock->use_empty()) {
527 delete dispatchBlock;
528 return;
529 }
530
John McCall8e4c74b2011-08-11 02:22:43 +0000531 CGF.EmitBlockAfterUses(dispatchBlock);
532
533 // If this isn't a catch-all filter, we need to check whether we got
534 // here because the filter triggered.
535 if (filterScope.getNumFilters()) {
536 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000537 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000538 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
539
540 llvm::Value *zero = CGF.Builder.getInt32(0);
541 llvm::Value *failsFilter =
542 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
David Chisnall9a837be2012-11-07 16:50:40 +0000543 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000544
545 CGF.EmitBlock(unexpectedBB);
546 }
547
548 // Call __cxa_call_unexpected. This doesn't need to be an invoke
549 // because __cxa_call_unexpected magically filters exceptions
550 // according to the last landing pad the exception was thrown
551 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000552 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000553 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000554 ->setDoesNotReturn();
555 CGF.Builder.CreateUnreachable();
556}
557
Mike Stump1d849212009-12-07 23:38:24 +0000558void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000559 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000560 return;
561
Mike Stump1d849212009-12-07 23:38:24 +0000562 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
563 if (FD == 0)
564 return;
565 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
566 if (Proto == 0)
567 return;
568
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000569 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
570 if (isNoexceptExceptionSpec(EST)) {
571 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
572 EHStack.popTerminate();
573 }
574 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall8e4c74b2011-08-11 02:22:43 +0000575 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
576 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000577 EHStack.popFilter();
578 }
Mike Stump1d849212009-12-07 23:38:24 +0000579}
580
Mike Stump58ef18b2009-11-20 23:44:51 +0000581void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000582 if (CGM.getTarget().getTriple().isWindowsMSVCEnvironment()) {
583 ErrorUnsupported(&S, "try statement");
584 return;
585 }
586
John McCallb609d3f2010-07-07 06:56:46 +0000587 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000588 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000589 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000590}
591
John McCallb609d3f2010-07-07 06:56:46 +0000592void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000593 unsigned NumHandlers = S.getNumHandlers();
594 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000595
John McCallbd309292010-07-06 01:34:17 +0000596 for (unsigned I = 0; I != NumHandlers; ++I) {
597 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000598
John McCallbd309292010-07-06 01:34:17 +0000599 llvm::BasicBlock *Handler = createBasicBlock("catch");
600 if (C->getExceptionDecl()) {
601 // FIXME: Dropping the reference type on the type into makes it
602 // impossible to correctly implement catch-by-reference
603 // semantics for pointers. Unfortunately, this is what all
604 // existing compilers do, and it's not clear that the standard
605 // personality routine is capable of doing this right. See C++ DR 388:
606 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
607 QualType CaughtType = C->getCaughtType();
608 CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
John McCall2ca705e2010-07-24 00:37:23 +0000609
610 llvm::Value *TypeInfo = 0;
611 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000612 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000613 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000614 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000615 CatchScope->setHandler(I, TypeInfo, Handler);
616 } else {
617 // No exception decl indicates '...', a catch-all.
618 CatchScope->setCatchAllHandler(I, Handler);
619 }
620 }
John McCallbd309292010-07-06 01:34:17 +0000621}
622
John McCall8e4c74b2011-08-11 02:22:43 +0000623llvm::BasicBlock *
624CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
625 // The dispatch block for the end of the scope chain is a block that
626 // just resumes unwinding.
627 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000628 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000629
630 // Otherwise, we should look at the actual scope.
631 EHScope &scope = *EHStack.find(si);
632
633 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
634 if (!dispatchBlock) {
635 switch (scope.getKind()) {
636 case EHScope::Catch: {
637 // Apply a special case to a single catch-all.
638 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
639 if (catchScope.getNumHandlers() == 1 &&
640 catchScope.getHandler(0).isCatchAll()) {
641 dispatchBlock = catchScope.getHandler(0).Block;
642
643 // Otherwise, make a dispatch block.
644 } else {
645 dispatchBlock = createBasicBlock("catch.dispatch");
646 }
647 break;
648 }
649
650 case EHScope::Cleanup:
651 dispatchBlock = createBasicBlock("ehcleanup");
652 break;
653
654 case EHScope::Filter:
655 dispatchBlock = createBasicBlock("filter.dispatch");
656 break;
657
658 case EHScope::Terminate:
659 dispatchBlock = getTerminateHandler();
660 break;
661 }
662 scope.setCachedEHDispatchBlock(dispatchBlock);
663 }
664 return dispatchBlock;
665}
666
John McCallbd309292010-07-06 01:34:17 +0000667/// Check whether this is a non-EH scope, i.e. a scope which doesn't
668/// affect exception handling. Currently, the only non-EH scopes are
669/// normal-only cleanup scopes.
670static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000671 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000672 case EHScope::Cleanup:
673 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000674 case EHScope::Filter:
675 case EHScope::Catch:
676 case EHScope::Terminate:
677 return false;
678 }
679
David Blaikiee4d798f2012-01-20 21:50:17 +0000680 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000681}
682
683llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
684 assert(EHStack.requiresLandingPad());
685 assert(!EHStack.empty());
686
David Blaikiebbafb8a2012-03-11 07:00:24 +0000687 if (!CGM.getLangOpts().Exceptions)
John McCall2b7fc382010-07-13 20:32:21 +0000688 return 0;
689
John McCallbd309292010-07-06 01:34:17 +0000690 // Check the innermost scope for a cached landing pad. If this is
691 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
692 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
693 if (LP) return LP;
694
695 // Build the landing pad for this scope.
696 LP = EmitLandingPad();
697 assert(LP);
698
699 // Cache the landing pad on the innermost scope. If this is a
700 // non-EH scope, cache the landing pad on the enclosing scope, too.
701 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
702 ir->setCachedLandingPad(LP);
703 if (!isNonEHScope(*ir)) break;
704 }
705
706 return LP;
707}
708
John McCall9b382dd2011-05-28 21:13:02 +0000709// This code contains a hack to work around a design flaw in
710// LLVM's EH IR which breaks semantics after inlining. This same
711// hack is implemented in llvm-gcc.
712//
713// The LLVM EH abstraction is basically a thin veneer over the
714// traditional GCC zero-cost design: for each range of instructions
715// in the function, there is (at most) one "landing pad" with an
716// associated chain of EH actions. A language-specific personality
717// function interprets this chain of actions and (1) decides whether
718// or not to resume execution at the landing pad and (2) if so,
719// provides an integer indicating why it's stopping. In LLVM IR,
720// the association of a landing pad with a range of instructions is
721// achieved via an invoke instruction, the chain of actions becomes
722// the arguments to the @llvm.eh.selector call, and the selector
723// call returns the integer indicator. Other than the required
724// presence of two intrinsic function calls in the landing pad,
725// the IR exactly describes the layout of the output code.
726//
727// A principal advantage of this design is that it is completely
728// language-agnostic; in theory, the LLVM optimizers can treat
729// landing pads neutrally, and targets need only know how to lower
730// the intrinsics to have a functioning exceptions system (assuming
731// that platform exceptions follow something approximately like the
732// GCC design). Unfortunately, landing pads cannot be combined in a
733// language-agnostic way: given selectors A and B, there is no way
734// to make a single landing pad which faithfully represents the
735// semantics of propagating an exception first through A, then
736// through B, without knowing how the personality will interpret the
737// (lowered form of the) selectors. This means that inlining has no
738// choice but to crudely chain invokes (i.e., to ignore invokes in
739// the inlined function, but to turn all unwindable calls into
740// invokes), which is only semantically valid if every unwind stops
741// at every landing pad.
742//
743// Therefore, the invoke-inline hack is to guarantee that every
744// landing pad has a catch-all.
745enum CleanupHackLevel_t {
746 /// A level of hack that requires that all landing pads have
747 /// catch-alls.
748 CHL_MandatoryCatchall,
749
750 /// A level of hack that requires that all landing pads handle
751 /// cleanups.
752 CHL_MandatoryCleanup,
753
754 /// No hacks at all; ideal IR generation.
755 CHL_Ideal
756};
757const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
758
John McCallbd309292010-07-06 01:34:17 +0000759llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
760 assert(EHStack.requiresLandingPad());
761
John McCall8e4c74b2011-08-11 02:22:43 +0000762 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
763 switch (innermostEHScope.getKind()) {
764 case EHScope::Terminate:
765 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000766
John McCall8e4c74b2011-08-11 02:22:43 +0000767 case EHScope::Catch:
768 case EHScope::Cleanup:
769 case EHScope::Filter:
770 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
771 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000772 }
773
774 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000775 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantld1b151e2014-01-17 00:15:10 +0000776 SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
777 if (CGDebugInfo *DI = getDebugInfo())
Adrian Prantl5e5ff6e2013-05-16 00:41:29 +0000778 DI->EmitLocation(Builder, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000779
David Blaikiebbafb8a2012-03-11 07:00:24 +0000780 const EHPersonality &personality = EHPersonality::get(getLangOpts());
John McCall36ea3722010-07-17 00:43:08 +0000781
John McCallbd309292010-07-06 01:34:17 +0000782 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000783 llvm::BasicBlock *lpad = createBasicBlock("lpad");
784 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000785
Bill Wendlingf0724e82011-09-19 20:31:14 +0000786 llvm::LandingPadInst *LPadInst =
787 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
788 getOpaquePersonalityFn(CGM, personality), 0);
789
790 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
791 Builder.CreateStore(LPadExn, getExceptionSlot());
792 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
793 Builder.CreateStore(LPadSel, getEHSelectorSlot());
794
John McCallbd309292010-07-06 01:34:17 +0000795 // Save the exception pointer. It's safe to use a single exception
796 // pointer per function because EH cleanups can never have nested
797 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000798 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000799
800 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000801 bool hasCatchAll = false;
802 bool hasCleanup = false;
803 bool hasFilter = false;
804 SmallVector<llvm::Value*, 4> filterTypes;
805 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallbd309292010-07-06 01:34:17 +0000806 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
807 I != E; ++I) {
808
809 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000810 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000811 // If we have a cleanup, remember that.
812 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000813 continue;
814
John McCallbd309292010-07-06 01:34:17 +0000815 case EHScope::Filter: {
816 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000817 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000818
Bill Wendlingf0724e82011-09-19 20:31:14 +0000819 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000820 EHFilterScope &filter = cast<EHFilterScope>(*I);
821 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000822
Bill Wendling8c4b7162011-09-22 20:32:54 +0000823 // Add all the filter values.
824 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
825 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000826 goto done;
827 }
828
829 case EHScope::Terminate:
830 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000831 assert(!hasCatchAll);
832 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000833 goto done;
834
835 case EHScope::Catch:
836 break;
837 }
838
John McCall8e4c74b2011-08-11 02:22:43 +0000839 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
840 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
841 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000842
John McCall8e4c74b2011-08-11 02:22:43 +0000843 // If this is a catch-all, register that and abort.
844 if (!handler.Type) {
845 assert(!hasCatchAll);
846 hasCatchAll = true;
847 goto done;
John McCallbd309292010-07-06 01:34:17 +0000848 }
849
850 // Check whether we already have a handler for this type.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000851 if (catchTypes.insert(handler.Type))
852 // If not, add it directly to the landingpad.
853 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000854 }
John McCallbd309292010-07-06 01:34:17 +0000855 }
856
857 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000858 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000859 assert(!(hasCatchAll && hasFilter));
860 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000861 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000862
863 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000864 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000865 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000866 // Create a filter expression: a constant array indicating which filter
867 // types there are. The personality routine only lands here if the filter
868 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000869 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000870 llvm::ArrayType *AType =
871 llvm::ArrayType::get(!filterTypes.empty() ?
872 filterTypes[0]->getType() : Int8PtrTy,
873 filterTypes.size());
874
875 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
876 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
877 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
878 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000879
880 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000881 if (hasCleanup)
882 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000883
884 // Otherwise, signal that we at least have cleanups.
John McCall8e4c74b2011-08-11 02:22:43 +0000885 } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000886 if (CleanupHackLevel == CHL_MandatoryCatchall)
887 LPadInst->addClause(getCatchAllValue(*this));
888 else
889 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000890 }
891
Bill Wendlingf0724e82011-09-19 20:31:14 +0000892 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
893 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000894
895 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000896 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000897
898 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000899 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000900
John McCall8e4c74b2011-08-11 02:22:43 +0000901 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000902}
903
John McCall5c08ab92010-07-13 22:12:14 +0000904namespace {
905 /// A cleanup to call __cxa_end_catch. In many cases, the caught
906 /// exception type lets us state definitively that the thrown exception
907 /// type does not have a destructor. In particular:
908 /// - Catch-alls tell us nothing, so we have to conservatively
909 /// assume that the thrown exception might have a destructor.
910 /// - Catches by reference behave according to their base types.
911 /// - Catches of non-record types will only trigger for exceptions
912 /// of non-record types, which never have destructors.
913 /// - Catches of record types can trigger for arbitrary subclasses
914 /// of the caught type, so we have to assume the actual thrown
915 /// exception type might have a throwing destructor, even if the
916 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000917 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000918 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
919 bool MightThrow;
920
Craig Topper4f12f102014-03-12 06:41:41 +0000921 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5c08ab92010-07-13 22:12:14 +0000922 if (!MightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000923 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000924 return;
925 }
926
John McCall882987f2013-02-28 19:01:20 +0000927 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000928 }
929 };
930}
931
John McCallbd309292010-07-06 01:34:17 +0000932/// Emits a call to __cxa_begin_catch and enters a cleanup to call
933/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000934///
935/// \param EndMightThrow - true if __cxa_end_catch might throw
936static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
937 llvm::Value *Exn,
938 bool EndMightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000939 llvm::CallInst *call =
940 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +0000941
John McCallcda666c2010-07-21 07:22:38 +0000942 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000943
John McCall882987f2013-02-28 19:01:20 +0000944 return call;
John McCallbd309292010-07-06 01:34:17 +0000945}
946
947/// A "special initializer" callback for initializing a catch
948/// parameter during catch initialization.
949static void InitCatchParam(CodeGenFunction &CGF,
950 const VarDecl &CatchParam,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000951 llvm::Value *ParamAddr,
952 SourceLocation Loc) {
John McCallbd309292010-07-06 01:34:17 +0000953 // Load the exception from where the landing pad saved it.
Bill Wendling79a70e42011-09-15 18:57:19 +0000954 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallbd309292010-07-06 01:34:17 +0000955
956 CanQualType CatchType =
957 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000958 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallbd309292010-07-06 01:34:17 +0000959
960 // If we're catching by reference, we can just cast the object
961 // pointer to the appropriate pointer.
962 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000963 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
964 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000965
John McCallbd309292010-07-06 01:34:17 +0000966 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000967 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000968
969 // We have no way to tell the personality function that we're
970 // catching by reference, so if we're catching a pointer,
971 // __cxa_begin_catch will actually return that pointer by value.
972 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
973 QualType PointeeType = PT->getPointeeType();
974
975 // When catching by reference, generally we should just ignore
976 // this by-value pointer and use the exception object instead.
977 if (!PointeeType->isRecordType()) {
978
979 // Exn points to the struct _Unwind_Exception header, which
980 // we have to skip past in order to reach the exception data.
981 unsigned HeaderSize =
982 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
983 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
984
985 // However, if we're catching a pointer-to-record type that won't
986 // work, because the personality function might have adjusted
987 // the pointer. There's actually no way for us to fully satisfy
988 // the language/ABI contract here: we can't use Exn because it
989 // might have the wrong adjustment, but we can't use the by-value
990 // pointer because it's off by a level of abstraction.
991 //
992 // The current solution is to dump the adjusted pointer into an
993 // alloca, which breaks language semantics (because changing the
994 // pointer doesn't change the exception) but at least works.
995 // The better solution would be to filter out non-exact matches
996 // and rethrow them, but this is tricky because the rethrow
997 // really needs to be catchable by other sites at this landing
998 // pad. The best solution is to fix the personality function.
999 } else {
1000 // Pull the pointer for the reference type off.
Chris Lattner2192fe52011-07-18 04:24:23 +00001001 llvm::Type *PtrTy =
John McCall5add20c2010-07-20 22:17:55 +00001002 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
1003
1004 // Create the temporary and write the adjusted pointer into it.
1005 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
1006 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1007 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
1008
1009 // Bind the reference to the temporary.
1010 AdjustedExn = ExnPtrTmp;
1011 }
1012 }
1013
John McCallbd309292010-07-06 01:34:17 +00001014 llvm::Value *ExnCast =
1015 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
1016 CGF.Builder.CreateStore(ExnCast, ParamAddr);
1017 return;
1018 }
1019
John McCall47fb9502013-03-07 21:37:08 +00001020 // Scalars and complexes.
1021 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
1022 if (TEK != TEK_Aggregate) {
John McCall5c08ab92010-07-13 22:12:14 +00001023 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +00001024
1025 // If the catch type is a pointer type, __cxa_begin_catch returns
1026 // the pointer by value.
1027 if (CatchType->hasPointerRepresentation()) {
1028 llvm::Value *CastExn =
1029 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCall97017312012-01-17 20:16:56 +00001030
1031 switch (CatchType.getQualifiers().getObjCLifetime()) {
1032 case Qualifiers::OCL_Strong:
1033 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
1034 // fallthrough
1035
1036 case Qualifiers::OCL_None:
1037 case Qualifiers::OCL_ExplicitNone:
1038 case Qualifiers::OCL_Autoreleasing:
1039 CGF.Builder.CreateStore(CastExn, ParamAddr);
1040 return;
1041
1042 case Qualifiers::OCL_Weak:
1043 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1044 return;
1045 }
1046 llvm_unreachable("bad ownership qualifier!");
John McCallbd309292010-07-06 01:34:17 +00001047 }
1048
1049 // Otherwise, it returns a pointer into the exception object.
1050
Chris Lattner2192fe52011-07-18 04:24:23 +00001051 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001052 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1053
John McCall47fb9502013-03-07 21:37:08 +00001054 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1055 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1056 CGF.getContext().getDeclAlign(&CatchParam));
1057 switch (TEK) {
1058 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00001059 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall47fb9502013-03-07 21:37:08 +00001060 /*init*/ true);
1061 return;
1062 case TEK_Scalar: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001063 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00001064 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1065 return;
John McCallbd309292010-07-06 01:34:17 +00001066 }
John McCall47fb9502013-03-07 21:37:08 +00001067 case TEK_Aggregate:
1068 llvm_unreachable("evaluation kind filtered out!");
1069 }
1070 llvm_unreachable("bad evaluation kind");
John McCallbd309292010-07-06 01:34:17 +00001071 }
1072
John McCallb5011ab2011-02-16 08:39:19 +00001073 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001074
Chris Lattner2192fe52011-07-18 04:24:23 +00001075 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001076
John McCallb5011ab2011-02-16 08:39:19 +00001077 // Check for a copy expression. If we don't have a copy expression,
1078 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001079 const Expr *copyExpr = CatchParam.getInit();
1080 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001081 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1082 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001083 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001084 return;
1085 }
1086
1087 // We have to call __cxa_get_exception_ptr to get the adjusted
1088 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001089 llvm::CallInst *rawAdjustedExn =
John McCall882987f2013-02-28 19:01:20 +00001090 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +00001091
John McCall1bf58462011-02-16 08:02:54 +00001092 // Cast that to the appropriate type.
1093 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001094
John McCall1bf58462011-02-16 08:02:54 +00001095 // The copy expression is defined in terms of an OpaqueValueExpr.
1096 // Find it and map it to the adjusted expression.
1097 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001098 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1099 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001100
1101 // Call the copy ctor in a terminate scope.
1102 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001103
1104 // Perform the copy construction.
Eli Friedman38cd36d2011-12-03 02:13:40 +00001105 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001106 CGF.EmitAggExpr(copyExpr,
1107 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1108 AggValueSlot::IsNotDestructed,
1109 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001110 AggValueSlot::IsNotAliased));
John McCall1bf58462011-02-16 08:02:54 +00001111
1112 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001113 CGF.EHStack.popTerminate();
1114
John McCall1bf58462011-02-16 08:02:54 +00001115 // Undo the opaque value mapping.
1116 opaque.pop();
1117
John McCallbd309292010-07-06 01:34:17 +00001118 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001119 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001120}
1121
1122/// Begins a catch statement by initializing the catch variable and
1123/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001124static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001125 // We have to be very careful with the ordering of cleanups here:
1126 // C++ [except.throw]p4:
1127 // The destruction [of the exception temporary] occurs
1128 // immediately after the destruction of the object declared in
1129 // the exception-declaration in the handler.
1130 //
1131 // So the precise ordering is:
1132 // 1. Construct catch variable.
1133 // 2. __cxa_begin_catch
1134 // 3. Enter __cxa_end_catch cleanup
1135 // 4. Enter dtor cleanup
1136 //
John McCallc533cb72011-02-22 06:44:22 +00001137 // We do this by using a slightly abnormal initialization process.
1138 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001139 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001140 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001141 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001142 // - CallBeginCatch calls __cxa_begin_catch
1143 // - CallBeginCatch enters the __cxa_end_catch cleanup
1144 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001145 // - EmitCXXTryStmt emits the code for the catch body
1146 // - EmitCXXTryStmt close the RunCleanupsScope
1147
1148 VarDecl *CatchParam = S->getExceptionDecl();
1149 if (!CatchParam) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001150 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall5c08ab92010-07-13 22:12:14 +00001151 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001152 return;
1153 }
1154
1155 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001156 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001157 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCallc533cb72011-02-22 06:44:22 +00001158 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001159}
1160
John McCall8e4c74b2011-08-11 02:22:43 +00001161/// Emit the structure of the dispatch block for the given catch scope.
1162/// It is an invariant that the dispatch block already exists.
1163static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1164 EHCatchScope &catchScope) {
1165 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1166 assert(dispatchBlock);
1167
1168 // If there's only a single catch-all, getEHDispatchBlock returned
1169 // that catch-all as the dispatch block.
1170 if (catchScope.getNumHandlers() == 1 &&
1171 catchScope.getHandler(0).isCatchAll()) {
1172 assert(dispatchBlock == catchScope.getHandler(0).Block);
1173 return;
1174 }
1175
1176 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1177 CGF.EmitBlockAfterUses(dispatchBlock);
1178
1179 // Select the right handler.
1180 llvm::Value *llvm_eh_typeid_for =
1181 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1182
1183 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001184 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001185
1186 // Test against each of the exception types we claim to catch.
1187 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1188 assert(i < e && "ran off end of handlers!");
1189 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1190
1191 llvm::Value *typeValue = handler.Type;
1192 assert(typeValue && "fell into catch-all case!");
1193 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1194
1195 // Figure out the next block.
1196 bool nextIsEnd;
1197 llvm::BasicBlock *nextBlock;
1198
1199 // If this is the last handler, we're at the end, and the next
1200 // block is the block for the enclosing EH scope.
1201 if (i + 1 == e) {
1202 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1203 nextIsEnd = true;
1204
1205 // If the next handler is a catch-all, we're at the end, and the
1206 // next block is that handler.
1207 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1208 nextBlock = catchScope.getHandler(i+1).Block;
1209 nextIsEnd = true;
1210
1211 // Otherwise, we're not at the end and we need a new block.
1212 } else {
1213 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1214 nextIsEnd = false;
1215 }
1216
1217 // Figure out the catch type's index in the LSDA's type table.
1218 llvm::CallInst *typeIndex =
1219 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1220 typeIndex->setDoesNotThrow();
1221
1222 llvm::Value *matchesTypeIndex =
1223 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1224 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1225
1226 // If the next handler is a catch-all, we're completely done.
1227 if (nextIsEnd) {
1228 CGF.Builder.restoreIP(savedIP);
1229 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001230 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001231 // Otherwise we need to emit and continue at that block.
1232 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001233 }
John McCall8e4c74b2011-08-11 02:22:43 +00001234}
1235
1236void CodeGenFunction::popCatchScope() {
1237 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1238 if (catchScope.hasEHBranches())
1239 emitCatchDispatchBlock(*this, catchScope);
1240 EHStack.popCatch();
1241}
1242
John McCallb609d3f2010-07-07 06:56:46 +00001243void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001244 unsigned NumHandlers = S.getNumHandlers();
1245 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1246 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001247
John McCall8e4c74b2011-08-11 02:22:43 +00001248 // If the catch was not required, bail out now.
1249 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001250 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001251 EHStack.popCatch();
1252 return;
1253 }
1254
1255 // Emit the structure of the EH dispatch for this catch.
1256 emitCatchDispatchBlock(*this, CatchScope);
1257
John McCallbd309292010-07-06 01:34:17 +00001258 // Copy the handler blocks off before we pop the EH stack. Emitting
1259 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001260 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +00001261 memcpy(Handlers.data(), CatchScope.begin(),
1262 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +00001263
John McCallbd309292010-07-06 01:34:17 +00001264 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001265
John McCallbd309292010-07-06 01:34:17 +00001266 // The fall-through block.
1267 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001268
John McCallbd309292010-07-06 01:34:17 +00001269 // We just emitted the body of the try; jump to the continue block.
1270 if (HaveInsertPoint())
1271 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001272
John McCalld8d00be2012-06-15 05:27:05 +00001273 // Determine if we need an implicit rethrow for all these catch handlers;
1274 // see the comment below.
1275 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001276 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001277 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1278 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001279
John McCall8e4c74b2011-08-11 02:22:43 +00001280 // Perversely, we emit the handlers backwards precisely because we
1281 // want them to appear in source order. In all of these cases, the
1282 // catch block will have exactly one predecessor, which will be a
1283 // particular block in the catch dispatch. However, in the case of
1284 // a catch-all, one of the dispatch blocks will branch to two
1285 // different handlers, and EmitBlockAfterUses will cause the second
1286 // handler to be moved before the first.
1287 for (unsigned I = NumHandlers; I != 0; --I) {
1288 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1289 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001290
John McCallbd309292010-07-06 01:34:17 +00001291 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001292 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001293
John McCallbd309292010-07-06 01:34:17 +00001294 // Enter a cleanup scope, including the catch variable and the
1295 // end-catch.
1296 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001297
John McCallbd309292010-07-06 01:34:17 +00001298 // Initialize the catch variable and set up the cleanups.
1299 BeginCatch(*this, C);
1300
Justin Bognerea278c32014-01-07 00:20:28 +00001301 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +00001302 RegionCounter CatchCnt = getPGORegionCounter(C);
1303 CatchCnt.beginRegion(Builder);
1304
John McCallbd309292010-07-06 01:34:17 +00001305 // Perform the body of the catch.
1306 EmitStmt(C->getHandlerBlock());
1307
John McCalld8d00be2012-06-15 05:27:05 +00001308 // [except.handle]p11:
1309 // The currently handled exception is rethrown if control
1310 // reaches the end of a handler of the function-try-block of a
1311 // constructor or destructor.
1312
1313 // It is important that we only do this on fallthrough and not on
1314 // return. Note that it's illegal to put a return in a
1315 // constructor function-try-block's catch handler (p14), so this
1316 // really only applies to destructors.
1317 if (doImplicitRethrow && HaveInsertPoint()) {
John McCall882987f2013-02-28 19:01:20 +00001318 EmitRuntimeCallOrInvoke(getReThrowFn(CGM));
John McCalld8d00be2012-06-15 05:27:05 +00001319 Builder.CreateUnreachable();
1320 Builder.ClearInsertionPoint();
1321 }
1322
John McCallbd309292010-07-06 01:34:17 +00001323 // Fall out through the catch cleanups.
1324 CatchScope.ForceCleanup();
1325
1326 // Branch out of the try.
1327 if (HaveInsertPoint())
1328 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001329 }
1330
Justin Bogneref512b92014-01-06 22:27:43 +00001331 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +00001332 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +00001333 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +00001334}
Mike Stumpaff69af2009-12-09 03:35:49 +00001335
John McCall1e670402010-07-21 00:52:03 +00001336namespace {
John McCallcda666c2010-07-21 07:22:38 +00001337 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001338 llvm::Value *ForEHVar;
1339 llvm::Value *EndCatchFn;
1340 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1341 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1342
Craig Topper4f12f102014-03-12 06:41:41 +00001343 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001344 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1345 llvm::BasicBlock *CleanupContBB =
1346 CGF.createBasicBlock("finally.cleanup.cont");
1347
1348 llvm::Value *ShouldEndCatch =
1349 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1350 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1351 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001352 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001353 CGF.EmitBlock(CleanupContBB);
1354 }
1355 };
John McCall906da4b2010-07-21 05:47:49 +00001356
John McCallcda666c2010-07-21 07:22:38 +00001357 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001358 const Stmt *Body;
1359 llvm::Value *ForEHVar;
1360 llvm::Value *EndCatchFn;
1361 llvm::Value *RethrowFn;
1362 llvm::Value *SavedExnVar;
1363
1364 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1365 llvm::Value *EndCatchFn,
1366 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1367 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1368 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1369
Craig Topper4f12f102014-03-12 06:41:41 +00001370 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001371 // Enter a cleanup to call the end-catch function if one was provided.
1372 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001373 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1374 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001375
John McCallcebe0ca2010-08-11 00:16:14 +00001376 // Save the current cleanup destination in case there are
1377 // cleanups in the finally block.
1378 llvm::Value *SavedCleanupDest =
1379 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1380 "cleanup.dest.saved");
1381
John McCall906da4b2010-07-21 05:47:49 +00001382 // Emit the finally block.
1383 CGF.EmitStmt(Body);
1384
1385 // If the end of the finally is reachable, check whether this was
1386 // for EH. If so, rethrow.
1387 if (CGF.HaveInsertPoint()) {
1388 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1389 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1390
1391 llvm::Value *ShouldRethrow =
1392 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1393 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1394
1395 CGF.EmitBlock(RethrowBB);
1396 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001397 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1398 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001399 } else {
John McCall882987f2013-02-28 19:01:20 +00001400 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001401 }
1402 CGF.Builder.CreateUnreachable();
1403
1404 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001405
1406 // Restore the cleanup destination.
1407 CGF.Builder.CreateStore(SavedCleanupDest,
1408 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001409 }
1410
1411 // Leave the end-catch cleanup. As an optimization, pretend that
1412 // the fallthrough path was inaccessible; we've dynamically proven
1413 // that we're not in the EH case along that path.
1414 if (EndCatchFn) {
1415 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1416 CGF.PopCleanupBlock();
1417 CGF.Builder.restoreIP(SavedIP);
1418 }
1419
1420 // Now make sure we actually have an insertion point or the
1421 // cleanup gods will hate us.
1422 CGF.EnsureInsertPoint();
1423 }
1424 };
John McCall1e670402010-07-21 00:52:03 +00001425}
1426
John McCallbd309292010-07-06 01:34:17 +00001427/// Enters a finally block for an implementation using zero-cost
1428/// exceptions. This is mostly general, but hard-codes some
1429/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001430void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1431 const Stmt *body,
1432 llvm::Constant *beginCatchFn,
1433 llvm::Constant *endCatchFn,
1434 llvm::Constant *rethrowFn) {
1435 assert((beginCatchFn != 0) == (endCatchFn != 0) &&
John McCallbd309292010-07-06 01:34:17 +00001436 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001437 assert(rethrowFn && "rethrow function is required");
1438
1439 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001440
John McCallbd309292010-07-06 01:34:17 +00001441 // The rethrow function has one of the following two types:
1442 // void (*)()
1443 // void (*)(void*)
1444 // In the latter case we need to pass it the exception object.
1445 // But we can't use the exception slot because the @finally might
1446 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001447 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001448 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001449 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1450 SavedExnVar = 0;
1451 if (rethrowFnTy->getNumParams())
1452 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001453
John McCallbd309292010-07-06 01:34:17 +00001454 // A finally block is a statement which must be executed on any edge
1455 // out of a given scope. Unlike a cleanup, the finally block may
1456 // contain arbitrary control flow leading out of itself. In
1457 // addition, finally blocks should always be executed, even if there
1458 // are no catch handlers higher on the stack. Therefore, we
1459 // surround the protected scope with a combination of a normal
1460 // cleanup (to catch attempts to break out of the block via normal
1461 // control flow) and an EH catch-all (semantically "outside" any try
1462 // statement to which the finally block might have been attached).
1463 // The finally block itself is generated in the context of a cleanup
1464 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001465
John McCallbd309292010-07-06 01:34:17 +00001466 // Jump destination for performing the finally block on an exception
1467 // edge. We'll never actually reach this block, so unreachable is
1468 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001469 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001470
John McCallbd309292010-07-06 01:34:17 +00001471 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001472 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1473 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001474
John McCallbd309292010-07-06 01:34:17 +00001475 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001476 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1477 ForEHVar, endCatchFn,
1478 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001479
1480 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001481 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1482 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1483 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001484}
1485
John McCall6b0feb72011-06-22 02:32:12 +00001486void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001487 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001488 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1489 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001490
1491 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001492
John McCall6b0feb72011-06-22 02:32:12 +00001493 // If there are any references to the catch-all block, emit it.
1494 if (catchBB->use_empty()) {
1495 delete catchBB;
1496 } else {
1497 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1498 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001499
John McCall6b0feb72011-06-22 02:32:12 +00001500 llvm::Value *exn = 0;
John McCallbd309292010-07-06 01:34:17 +00001501
John McCall6b0feb72011-06-22 02:32:12 +00001502 // If there's a begin-catch function, call it.
1503 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001504 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001505 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001506 }
1507
1508 // If we need to remember the exception pointer to rethrow later, do so.
1509 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001510 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001511 CGF.Builder.CreateStore(exn, SavedExnVar);
1512 }
1513
1514 // Tell the cleanups in the finally block that we're do this for EH.
1515 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1516
1517 // Thread a jump through the finally cleanup.
1518 CGF.EmitBranchThroughCleanup(RethrowDest);
1519
1520 CGF.Builder.restoreIP(savedIP);
1521 }
1522
1523 // Finally, leave the @finally cleanup.
1524 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001525}
1526
John McCalle142ad52013-02-12 03:51:46 +00001527/// In a terminate landing pad, should we use __clang__call_terminate
1528/// or just a naked call to std::terminate?
1529///
1530/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1531/// std::terminate to usefully report something about the
1532/// violating exception.
1533static bool useClangCallTerminate(CodeGenModule &CGM) {
1534 // Only do this for Itanium-family ABIs in C++ mode.
1535 return (CGM.getLangOpts().CPlusPlus &&
1536 CGM.getTarget().getCXXABI().isItaniumFamily());
1537}
1538
1539/// Get or define the following function:
1540/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1541/// This code is used only in C++.
1542static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1543 llvm::FunctionType *fnTy =
1544 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1545 llvm::Constant *fnRef =
1546 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1547
1548 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1549 if (fn && fn->empty()) {
1550 fn->setDoesNotThrow();
1551 fn->setDoesNotReturn();
1552
1553 // What we really want is to massively penalize inlining without
1554 // forbidding it completely. The difference between that and
1555 // 'noinline' is negligible.
1556 fn->addFnAttr(llvm::Attribute::NoInline);
1557
1558 // Allow this function to be shared across translation units, but
1559 // we don't want it to turn into an exported symbol.
1560 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1561 fn->setVisibility(llvm::Function::HiddenVisibility);
1562
1563 // Set up the function.
1564 llvm::BasicBlock *entry =
1565 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1566 CGBuilderTy builder(entry);
1567
1568 // Pull the exception pointer out of the parameter list.
1569 llvm::Value *exn = &*fn->arg_begin();
1570
1571 // Call __cxa_begin_catch(exn).
John McCall882987f2013-02-28 19:01:20 +00001572 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1573 catchCall->setDoesNotThrow();
1574 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001575
1576 // Call std::terminate().
1577 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1578 termCall->setDoesNotThrow();
1579 termCall->setDoesNotReturn();
John McCall882987f2013-02-28 19:01:20 +00001580 termCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001581
1582 // std::terminate cannot return.
1583 builder.CreateUnreachable();
1584 }
1585
1586 return fnRef;
1587}
1588
John McCallbd309292010-07-06 01:34:17 +00001589llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1590 if (TerminateLandingPad)
1591 return TerminateLandingPad;
1592
1593 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1594
1595 // This will get inserted at the end of the function.
1596 TerminateLandingPad = createBasicBlock("terminate.lpad");
1597 Builder.SetInsertPoint(TerminateLandingPad);
1598
1599 // Tell the backend that this is a landing pad.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001600 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
Bill Wendlingf0724e82011-09-19 20:31:14 +00001601 llvm::LandingPadInst *LPadInst =
1602 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1603 getOpaquePersonalityFn(CGM, Personality), 0);
1604 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001605
John McCalle142ad52013-02-12 03:51:46 +00001606 llvm::CallInst *terminateCall;
1607 if (useClangCallTerminate(CGM)) {
1608 // Extract out the exception pointer.
1609 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCall882987f2013-02-28 19:01:20 +00001610 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCalle142ad52013-02-12 03:51:46 +00001611 } else {
John McCall882987f2013-02-28 19:01:20 +00001612 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCalle142ad52013-02-12 03:51:46 +00001613 }
1614 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001615 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001616
John McCallbd309292010-07-06 01:34:17 +00001617 // Restore the saved insertion state.
1618 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001619
John McCallbd309292010-07-06 01:34:17 +00001620 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001621}
Mike Stump2b488872009-12-09 22:59:31 +00001622
1623llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001624 if (TerminateHandler)
1625 return TerminateHandler;
1626
John McCallbd309292010-07-06 01:34:17 +00001627 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001628
John McCallbd309292010-07-06 01:34:17 +00001629 // Set up the terminate handler. This block is inserted at the very
1630 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001631 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001632 Builder.SetInsertPoint(TerminateHandler);
John McCallc84e4e92013-06-20 21:37:43 +00001633 llvm::CallInst *terminateCall;
1634 if (useClangCallTerminate(CGM)) {
1635 // Load the exception pointer.
1636 llvm::Value *exn = getExceptionFromSlot();
1637 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1638 } else {
1639 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1640 }
1641 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001642 Builder.CreateUnreachable();
1643
John McCall21886962010-04-21 10:05:39 +00001644 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001645 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001646
Mike Stump2b488872009-12-09 22:59:31 +00001647 return TerminateHandler;
1648}
John McCallbd309292010-07-06 01:34:17 +00001649
David Chisnall9a837be2012-11-07 16:50:40 +00001650llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001651 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001652
1653 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1654
1655 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001656 EHResumeBlock = createBasicBlock("eh.resume");
1657 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001658
David Blaikiebbafb8a2012-03-11 07:00:24 +00001659 const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
John McCallad5d61e2010-07-23 21:56:41 +00001660
1661 // This can always be a call because we necessarily didn't find
1662 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001663 const char *RethrowName = Personality.CatchallRethrowFn;
David Chisnall9a837be2012-11-07 16:50:40 +00001664 if (RethrowName != 0 && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001665 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1666 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001667 ->setDoesNotReturn();
1668 } else {
John McCall9b382dd2011-05-28 21:13:02 +00001669 switch (CleanupHackLevel) {
1670 case CHL_MandatoryCatchall:
1671 // In mandatory-catchall mode, we need to use
1672 // _Unwind_Resume_or_Rethrow, or whatever the personality's
1673 // equivalent is.
John McCall882987f2013-02-28 19:01:20 +00001674 EmitRuntimeCall(getUnwindResumeOrRethrowFn(),
1675 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001676 ->setDoesNotReturn();
1677 break;
1678 case CHL_MandatoryCleanup: {
Bill Wendlingf0724e82011-09-19 20:31:14 +00001679 // In mandatory-cleanup mode, we should use 'resume'.
1680
1681 // Recreate the landingpad's return value for the 'resume' instruction.
1682 llvm::Value *Exn = getExceptionFromSlot();
1683 llvm::Value *Sel = getSelectorFromSlot();
1684
1685 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1686 Sel->getType(), NULL);
1687 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1688 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1689 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1690
1691 Builder.CreateResume(LPadVal);
1692 Builder.restoreIP(SavedIP);
1693 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001694 }
1695 case CHL_Ideal:
1696 // In an idealized mode where we don't have to worry about the
1697 // optimizer combining landing pads, we should just use
1698 // _Unwind_Resume (or the personality's equivalent).
John McCall882987f2013-02-28 19:01:20 +00001699 EmitRuntimeCall(getUnwindResumeFn(), getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001700 ->setDoesNotReturn();
1701 break;
1702 }
1703 }
1704
John McCallad5d61e2010-07-23 21:56:41 +00001705 Builder.CreateUnreachable();
1706
1707 Builder.restoreIP(SavedIP);
1708
John McCall8e4c74b2011-08-11 02:22:43 +00001709 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001710}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001711
1712void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1713 CGM.ErrorUnsupported(&S, "SEH __try");
1714}