blob: 05fc8631766bda8ccfa2d46269fd2d8a247df135 [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"
David Majnemer442d0a22014-11-25 07:20:20 +000016#include "CGCXXABI.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000017#include "CGObjCRuntime.h"
John McCall5add20c2010-07-20 22:17:55 +000018#include "TargetInfo.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000019#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000020#include "clang/AST/StmtObjC.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
John McCallbd309292010-07-06 01:34:17 +000023
Anders Carlsson4b08db72009-10-30 01:42:31 +000024using namespace clang;
25using namespace CodeGen;
26
John McCall2c33ba82013-02-12 03:51:38 +000027static llvm::Constant *getAllocateExceptionFn(CodeGenModule &CGM) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000028 // void *__cxa_allocate_exception(size_t thrown_size);
Mike Stump75546b82009-12-10 00:06:18 +000029
Chris Lattner2192fe52011-07-18 04:24:23 +000030 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000031 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000032
John McCall2c33ba82013-02-12 03:51:38 +000033 return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000034}
35
John McCall2c33ba82013-02-12 03:51:38 +000036static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000037 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000038
Chris Lattner2192fe52011-07-18 04:24:23 +000039 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000040 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000041
John McCall2c33ba82013-02-12 03:51:38 +000042 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000043}
44
John McCall2c33ba82013-02-12 03:51:38 +000045static llvm::Constant *getThrowFn(CodeGenModule &CGM) {
Mike Stump75546b82009-12-10 00:06:18 +000046 // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
Mike Stump33270212009-12-02 07:41:41 +000047 // void (*dest) (void *));
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000048
John McCall2c33ba82013-02-12 03:51:38 +000049 llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +000050 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000051 llvm::FunctionType::get(CGM.VoidTy, Args, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000052
John McCall2c33ba82013-02-12 03:51:38 +000053 return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
Anders Carlsson32e1b1c2009-10-30 02:27:02 +000054}
55
John McCall2c33ba82013-02-12 03:51:38 +000056static llvm::Constant *getGetExceptionPtrFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000057 // void *__cxa_get_exception_ptr(void*);
John McCallbd309292010-07-06 01:34:17 +000058
Chris Lattner2192fe52011-07-18 04:24:23 +000059 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000060 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCallbd309292010-07-06 01:34:17 +000061
John McCall2c33ba82013-02-12 03:51:38 +000062 return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
John McCallbd309292010-07-06 01:34:17 +000063}
64
John McCall2c33ba82013-02-12 03:51:38 +000065static llvm::Constant *getBeginCatchFn(CodeGenModule &CGM) {
John McCallbd309292010-07-06 01:34:17 +000066 // void *__cxa_begin_catch(void*);
Mike Stump58ef18b2009-11-20 23:44:51 +000067
Chris Lattner2192fe52011-07-18 04:24:23 +000068 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000069 llvm::FunctionType::get(CGM.Int8PtrTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000070
John McCall2c33ba82013-02-12 03:51:38 +000071 return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000072}
73
John McCall2c33ba82013-02-12 03:51:38 +000074static llvm::Constant *getEndCatchFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000075 // void __cxa_end_catch();
Mike Stump58ef18b2009-11-20 23:44:51 +000076
Chris Lattner2192fe52011-07-18 04:24:23 +000077 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000078 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000079
John McCall2c33ba82013-02-12 03:51:38 +000080 return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
Mike Stump58ef18b2009-11-20 23:44:51 +000081}
82
John McCall2c33ba82013-02-12 03:51:38 +000083static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000084 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000085
Chris Lattner2192fe52011-07-18 04:24:23 +000086 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000087 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000088
John McCall2c33ba82013-02-12 03:51:38 +000089 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000090}
91
John McCall2c33ba82013-02-12 03:51:38 +000092static llvm::Constant *getTerminateFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000093 // void __terminate();
94
Chris Lattner2192fe52011-07-18 04:24:23 +000095 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000096 llvm::FunctionType::get(CGM.VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000097
Chris Lattner0e62c1c2011-07-23 10:55:15 +000098 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000099
100 // In C++, use std::terminate().
John McCall2c33ba82013-02-12 03:51:38 +0000101 if (CGM.getLangOpts().CPlusPlus)
John McCall9de19782011-07-06 01:22:26 +0000102 name = "_ZSt9terminatev"; // FIXME: mangling!
John McCall2c33ba82013-02-12 03:51:38 +0000103 else if (CGM.getLangOpts().ObjC1 &&
104 CGM.getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +0000105 name = "objc_terminate";
106 else
107 name = "abort";
John McCall2c33ba82013-02-12 03:51:38 +0000108 return CGM.CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +0000109}
110
John McCall2c33ba82013-02-12 03:51:38 +0000111static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000112 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000113 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +0000114 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +0000115
John McCall2c33ba82013-02-12 03:51:38 +0000116 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +0000117}
118
Benjamin Kramer793bd552012-02-08 12:41:24 +0000119namespace {
120 /// The exceptions personality for a function.
121 struct EHPersonality {
122 const char *PersonalityFn;
123
124 // If this is non-null, this personality requires a non-standard
125 // function for rethrowing an exception after a catchall cleanup.
126 // This function must have prototype void(void*).
127 const char *CatchallRethrowFn;
128
Reid Klecknere070b992014-11-14 02:01:10 +0000129 static const EHPersonality &get(CodeGenModule &CGM);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000130 static const EHPersonality GNU_C;
131 static const EHPersonality GNU_C_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000132 static const EHPersonality GNU_C_SEH;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000133 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000134 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000135 static const EHPersonality GNU_ObjCXX;
136 static const EHPersonality NeXT_ObjC;
137 static const EHPersonality GNU_CPlusPlus;
138 static const EHPersonality GNU_CPlusPlus_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000139 static const EHPersonality GNU_CPlusPlus_SEH;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000140 };
141}
142
Craig Topper8a13c412014-05-21 05:09:00 +0000143const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000144const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000145EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
146const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000147EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
148const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000149EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
150const EHPersonality
151EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
152const EHPersonality
153EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000154const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000155EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
156const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +0000157EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
158const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000159EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000160const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000161EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000162
Reid Klecknere070b992014-11-14 02:01:10 +0000163/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
164/// other platforms, unless the user asked for SjLj exceptions.
165static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
166 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
167}
168
169static const EHPersonality &getCPersonality(const llvm::Triple &T,
170 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000171 if (L.SjLjExceptions)
172 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000173 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000174 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000175 return EHPersonality::GNU_C;
176}
177
Reid Klecknere070b992014-11-14 02:01:10 +0000178static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
179 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000180 switch (L.ObjCRuntime.getKind()) {
181 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000182 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000183 case ObjCRuntime::MacOSX:
184 case ObjCRuntime::iOS:
185 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000186 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000187 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
188 return EHPersonality::GNUstep_ObjC;
189 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000190 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000191 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000192 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000193 }
John McCall5fb5df92012-06-20 06:18:46 +0000194 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000195}
196
Reid Klecknere070b992014-11-14 02:01:10 +0000197static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
198 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000199 if (L.SjLjExceptions)
200 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000201 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000202 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000203 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000204}
205
206/// Determines the personality function to use when both C++
207/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000208static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
209 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000210 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000211 // The ObjC personality defers to the C++ personality for non-ObjC
212 // handlers. Unlike the C++ case, we use the same personality
213 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000214 case ObjCRuntime::MacOSX:
215 case ObjCRuntime::iOS:
216 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000217
John McCall5fb5df92012-06-20 06:18:46 +0000218 // In the fragile ABI, just use C++ exception handling and hope
219 // they're not doing crazy exception mixing.
220 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000221 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000222
David Chisnallb601c962012-07-03 20:49:52 +0000223 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000224 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000225 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000226 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000227 return EHPersonality::GNU_ObjC;
228 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000229 return EHPersonality::GNU_ObjCXX;
230 }
231 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000232}
233
Reid Klecknere070b992014-11-14 02:01:10 +0000234const EHPersonality &EHPersonality::get(CodeGenModule &CGM) {
235 const llvm::Triple &T = CGM.getTarget().getTriple();
236 const LangOptions &L = CGM.getLangOpts();
John McCall36ea3722010-07-17 00:43:08 +0000237 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000238 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000239 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000240 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000241 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000242 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000243 else
Reid Klecknere070b992014-11-14 02:01:10 +0000244 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000245}
John McCallbd309292010-07-06 01:34:17 +0000246
John McCall0bdb1fd2010-09-16 06:16:50 +0000247static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000248 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000249 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000250 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000251 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000252 return Fn;
253}
254
255static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
256 const EHPersonality &Personality) {
257 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000258 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000259}
260
261/// Check whether a personality function could reasonably be swapped
262/// for a C++ personality function.
263static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000264 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000265 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000266 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000267 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
268 if (!PersonalityHasOnlyCXXUses(CE))
269 return false;
270 continue;
271 }
272
Bill Wendling58e58fe2011-09-19 22:08:36 +0000273 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000274 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000275 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000276
Bill Wendling58e58fe2011-09-19 22:08:36 +0000277 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000278 // Look for something that would've been returned by the ObjC
279 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000280 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
281 if (LPI->isCatch(I)) {
282 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000283 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
284 // ObjC EH selector entries are always global variables with
285 // names starting like this.
286 if (GV->getName().startswith("OBJC_EHTYPE"))
287 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000288 } else {
289 // Check if any of the filter values have the ObjC prefix.
290 llvm::Constant *CVal = cast<llvm::Constant>(Val);
291 for (llvm::User::op_iterator
292 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000293 if (llvm::GlobalVariable *GV =
294 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
295 // ObjC EH selector entries are always global variables with
296 // names starting like this.
297 if (GV->getName().startswith("OBJC_EHTYPE"))
298 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000299 }
300 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000301 }
302 }
303
304 return true;
305}
306
307/// Try to use the C++ personality function in ObjC++. Not doing this
308/// can cause some incompatibilities with gcc, which is more
309/// aggressive about only using the ObjC++ personality in a function
310/// when it really needs it.
311void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000312 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000313 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000314 return;
315
John McCall3c223932012-11-14 17:48:31 +0000316 // Both the problem this endeavors to fix and the way the logic
317 // above works is specific to the NeXT runtime.
318 if (!LangOpts.ObjCRuntime.isNeXTFamily())
319 return;
320
Reid Klecknere070b992014-11-14 02:01:10 +0000321 const EHPersonality &ObjCXX = EHPersonality::get(*this);
322 const EHPersonality &CXX =
323 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000324 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000325 return;
326
Benjamin Kramer793bd552012-02-08 12:41:24 +0000327 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
328 "Different EHPersonalities using the same personality function.");
329
330 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000331
332 // Nothing to do if it's unused.
333 if (!Fn || Fn->use_empty()) return;
334
335 // Can't do the optimization if it has non-C++ uses.
336 if (!PersonalityHasOnlyCXXUses(Fn)) return;
337
338 // Create the C++ personality function and kill off the old
339 // function.
340 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
341
342 // This can happen if the user is screwing with us.
343 if (Fn->getType() != CXXFn->getType()) return;
344
345 Fn->replaceAllUsesWith(CXXFn);
346 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000347}
348
349/// Returns the value to inject into a selector to indicate the
350/// presence of a catch-all.
351static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
352 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000353 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000354}
355
John McCallbb026012010-07-13 21:17:51 +0000356namespace {
357 /// A cleanup to free the exception object if its initialization
358 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000359 struct FreeException : EHScopeStack::Cleanup {
360 llvm::Value *exn;
361 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000362 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000363 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000364 }
365 };
366}
367
John McCall2e6567a2010-04-22 01:10:34 +0000368// Emits an exception expression into the given location. This
369// differs from EmitAnyExprToMem only in that, if a final copy-ctor
370// call is required, an exception within that copy ctor causes
371// std::terminate to be invoked.
John McCalle4df6c82011-01-28 08:37:24 +0000372static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
373 llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000374 // Make sure the exception object is cleaned up if there's an
375 // exception during initialization.
John McCalle4df6c82011-01-28 08:37:24 +0000376 CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
377 EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000378
379 // __cxa_allocate_exception returns a void*; we need to cast this
380 // to the appropriate type for the object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000381 llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
John McCalle4df6c82011-01-28 08:37:24 +0000382 llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000383
384 // FIXME: this isn't quite right! If there's a final unelided call
385 // to a copy constructor, then according to [except.terminate]p1 we
386 // must call std::terminate() if that constructor throws, because
387 // technically that copy occurs after the exception expression is
388 // evaluated but before the exception is caught. But the best way
389 // to handle that is to teach EmitAggExpr to do the final copy
390 // differently if it can't be elided.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000391 CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
392 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000393
John McCalle4df6c82011-01-28 08:37:24 +0000394 // Deactivate the cleanup block.
John McCallf4beacd2011-11-10 10:43:54 +0000395 CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000396}
397
John McCallbd309292010-07-06 01:34:17 +0000398llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000399 if (!ExceptionSlot)
400 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000401 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000402}
403
John McCall9b382dd2011-05-28 21:13:02 +0000404llvm::Value *CodeGenFunction::getEHSelectorSlot() {
405 if (!EHSelectorSlot)
406 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
407 return EHSelectorSlot;
408}
409
Bill Wendling79a70e42011-09-15 18:57:19 +0000410llvm::Value *CodeGenFunction::getExceptionFromSlot() {
411 return Builder.CreateLoad(getExceptionSlot(), "exn");
412}
413
414llvm::Value *CodeGenFunction::getSelectorFromSlot() {
415 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
416}
417
Richard Smithea852322013-05-07 21:53:22 +0000418void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
419 bool KeepInsertionPoint) {
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000420 if (!E->getSubExpr()) {
David Majnemer442d0a22014-11-25 07:20:20 +0000421 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/true);
Douglas Gregorc278d1b2010-05-16 00:44:00 +0000422
John McCall20f6ab82011-01-12 03:41:02 +0000423 // throw is an expression, and the expression emitters expect us
424 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000425 if (KeepInsertionPoint)
426 EmitBlock(createBasicBlock("throw.cont"));
John McCall20f6ab82011-01-12 03:41:02 +0000427
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000428 return;
429 }
Mike Stump75546b82009-12-10 00:06:18 +0000430
David Majnemer442d0a22014-11-25 07:20:20 +0000431 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
432 ErrorUnsupported(E, "throw expression");
433 return;
434 }
435
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000436 QualType ThrowType = E->getSubExpr()->getType();
Mike Stump75546b82009-12-10 00:06:18 +0000437
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000438 if (ThrowType->isObjCObjectPointerType()) {
439 const Stmt *ThrowStmt = E->getSubExpr();
440 const ObjCAtThrowStmt S(E->getExprLoc(),
441 const_cast<Stmt *>(ThrowStmt));
442 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
443 // This will clear insertion point which was not cleared in
444 // call to EmitThrowStmt.
Richard Smithea852322013-05-07 21:53:22 +0000445 if (KeepInsertionPoint)
446 EmitBlock(createBasicBlock("throw.cont"));
Fariborz Jahanian1eab0522013-01-10 19:02:56 +0000447 return;
448 }
449
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000450 // Now allocate the exception object.
Chris Lattner2192fe52011-07-18 04:24:23 +0000451 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
John McCall21886962010-04-21 10:05:39 +0000452 uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
Mike Stump75546b82009-12-10 00:06:18 +0000453
John McCall2c33ba82013-02-12 03:51:38 +0000454 llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(CGM);
John McCallbd309292010-07-06 01:34:17 +0000455 llvm::CallInst *ExceptionPtr =
John McCall882987f2013-02-28 19:01:20 +0000456 EmitNounwindRuntimeCall(AllocExceptionFn,
457 llvm::ConstantInt::get(SizeTy, TypeSize),
458 "exception");
Anders Carlssonafd1edb2009-12-11 00:32:37 +0000459
John McCall2e6567a2010-04-22 01:10:34 +0000460 EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
Mike Stump75546b82009-12-10 00:06:18 +0000461
Anders Carlsson32e1b1c2009-10-30 02:27:02 +0000462 // Now throw the exception.
Anders Carlssonba840fb2011-01-24 01:59:49 +0000463 llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
464 /*ForEH=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000465
466 // The address of the destructor. If the exception type has a
467 // trivial destructor (or isn't a record), we just pass null.
Craig Topper8a13c412014-05-21 05:09:00 +0000468 llvm::Constant *Dtor = nullptr;
John McCall2e6567a2010-04-22 01:10:34 +0000469 if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
470 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
471 if (!Record->hasTrivialDestructor()) {
Douglas Gregorbac74902010-07-01 14:13:13 +0000472 CXXDestructorDecl *DtorD = Record->getDestructor();
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000473 Dtor = CGM.getAddrOfCXXStructor(DtorD, StructorType::Complete);
John McCall2e6567a2010-04-22 01:10:34 +0000474 Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
475 }
476 }
477 if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
Mike Stump75546b82009-12-10 00:06:18 +0000478
John McCall882987f2013-02-28 19:01:20 +0000479 llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
480 EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
Mike Stump75546b82009-12-10 00:06:18 +0000481
John McCall20f6ab82011-01-12 03:41:02 +0000482 // throw is an expression, and the expression emitters expect us
483 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000484 if (KeepInsertionPoint)
485 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000486}
Mike Stump58ef18b2009-11-20 23:44:51 +0000487
Mike Stump1d849212009-12-07 23:38:24 +0000488void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000489 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000490 return;
491
Mike Stump1d849212009-12-07 23:38:24 +0000492 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000493 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000494 // Check if CapturedDecl is nothrow and create terminate scope for it.
495 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
496 if (CD->isNothrow())
497 EHStack.pushTerminate();
498 }
Mike Stump1d849212009-12-07 23:38:24 +0000499 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000500 }
Mike Stump1d849212009-12-07 23:38:24 +0000501 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000502 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000503 return;
504
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000505 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
506 if (isNoexceptExceptionSpec(EST)) {
507 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
508 // noexcept functions are simple terminate scopes.
509 EHStack.pushTerminate();
510 }
511 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
512 unsigned NumExceptions = Proto->getNumExceptions();
513 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000514
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000515 for (unsigned I = 0; I != NumExceptions; ++I) {
516 QualType Ty = Proto->getExceptionType(I);
517 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
518 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
519 /*ForEH=*/true);
520 Filter->setFilter(I, EHType);
521 }
Mike Stump1d849212009-12-07 23:38:24 +0000522 }
Mike Stump1d849212009-12-07 23:38:24 +0000523}
524
John McCall8e4c74b2011-08-11 02:22:43 +0000525/// Emit the dispatch block for a filter scope if necessary.
526static void emitFilterDispatchBlock(CodeGenFunction &CGF,
527 EHFilterScope &filterScope) {
528 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
529 if (!dispatchBlock) return;
530 if (dispatchBlock->use_empty()) {
531 delete dispatchBlock;
532 return;
533 }
534
John McCall8e4c74b2011-08-11 02:22:43 +0000535 CGF.EmitBlockAfterUses(dispatchBlock);
536
537 // If this isn't a catch-all filter, we need to check whether we got
538 // here because the filter triggered.
539 if (filterScope.getNumFilters()) {
540 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000541 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000542 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
543
544 llvm::Value *zero = CGF.Builder.getInt32(0);
545 llvm::Value *failsFilter =
546 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
David Chisnall9a837be2012-11-07 16:50:40 +0000547 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000548
549 CGF.EmitBlock(unexpectedBB);
550 }
551
552 // Call __cxa_call_unexpected. This doesn't need to be an invoke
553 // because __cxa_call_unexpected magically filters exceptions
554 // according to the last landing pad the exception was thrown
555 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000556 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000557 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000558 ->setDoesNotReturn();
559 CGF.Builder.CreateUnreachable();
560}
561
Mike Stump1d849212009-12-07 23:38:24 +0000562void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000563 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000564 return;
565
Mike Stump1d849212009-12-07 23:38:24 +0000566 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000567 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000568 // Check if CapturedDecl is nothrow and pop terminate scope for it.
569 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
570 if (CD->isNothrow())
571 EHStack.popTerminate();
572 }
Mike Stump1d849212009-12-07 23:38:24 +0000573 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000574 }
Mike Stump1d849212009-12-07 23:38:24 +0000575 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000576 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000577 return;
578
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000579 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
580 if (isNoexceptExceptionSpec(EST)) {
581 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
582 EHStack.popTerminate();
583 }
584 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall8e4c74b2011-08-11 02:22:43 +0000585 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
586 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000587 EHStack.popFilter();
588 }
Mike Stump1d849212009-12-07 23:38:24 +0000589}
590
Mike Stump58ef18b2009-11-20 23:44:51 +0000591void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
Saleem Abdulrasoolb7698742014-11-17 22:11:07 +0000592 if (CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment()) {
Reid Klecknera82b5d82014-05-05 21:12:12 +0000593 ErrorUnsupported(&S, "try statement");
594 return;
595 }
596
John McCallb609d3f2010-07-07 06:56:46 +0000597 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000598 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000599 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000600}
601
John McCallb609d3f2010-07-07 06:56:46 +0000602void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000603 unsigned NumHandlers = S.getNumHandlers();
604 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000605
John McCallbd309292010-07-06 01:34:17 +0000606 for (unsigned I = 0; I != NumHandlers; ++I) {
607 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000608
John McCallbd309292010-07-06 01:34:17 +0000609 llvm::BasicBlock *Handler = createBasicBlock("catch");
610 if (C->getExceptionDecl()) {
611 // FIXME: Dropping the reference type on the type into makes it
612 // impossible to correctly implement catch-by-reference
613 // semantics for pointers. Unfortunately, this is what all
614 // existing compilers do, and it's not clear that the standard
615 // personality routine is capable of doing this right. See C++ DR 388:
616 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000617 Qualifiers CaughtTypeQuals;
618 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
619 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000620
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000621 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000622 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000623 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000624 else
Anders Carlssonba840fb2011-01-24 01:59:49 +0000625 TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
John McCallbd309292010-07-06 01:34:17 +0000626 CatchScope->setHandler(I, TypeInfo, Handler);
627 } else {
628 // No exception decl indicates '...', a catch-all.
629 CatchScope->setCatchAllHandler(I, Handler);
630 }
631 }
John McCallbd309292010-07-06 01:34:17 +0000632}
633
John McCall8e4c74b2011-08-11 02:22:43 +0000634llvm::BasicBlock *
635CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
636 // The dispatch block for the end of the scope chain is a block that
637 // just resumes unwinding.
638 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000639 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000640
641 // Otherwise, we should look at the actual scope.
642 EHScope &scope = *EHStack.find(si);
643
644 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
645 if (!dispatchBlock) {
646 switch (scope.getKind()) {
647 case EHScope::Catch: {
648 // Apply a special case to a single catch-all.
649 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
650 if (catchScope.getNumHandlers() == 1 &&
651 catchScope.getHandler(0).isCatchAll()) {
652 dispatchBlock = catchScope.getHandler(0).Block;
653
654 // Otherwise, make a dispatch block.
655 } else {
656 dispatchBlock = createBasicBlock("catch.dispatch");
657 }
658 break;
659 }
660
661 case EHScope::Cleanup:
662 dispatchBlock = createBasicBlock("ehcleanup");
663 break;
664
665 case EHScope::Filter:
666 dispatchBlock = createBasicBlock("filter.dispatch");
667 break;
668
669 case EHScope::Terminate:
670 dispatchBlock = getTerminateHandler();
671 break;
672 }
673 scope.setCachedEHDispatchBlock(dispatchBlock);
674 }
675 return dispatchBlock;
676}
677
John McCallbd309292010-07-06 01:34:17 +0000678/// Check whether this is a non-EH scope, i.e. a scope which doesn't
679/// affect exception handling. Currently, the only non-EH scopes are
680/// normal-only cleanup scopes.
681static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000682 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000683 case EHScope::Cleanup:
684 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000685 case EHScope::Filter:
686 case EHScope::Catch:
687 case EHScope::Terminate:
688 return false;
689 }
690
David Blaikiee4d798f2012-01-20 21:50:17 +0000691 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000692}
693
694llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
695 assert(EHStack.requiresLandingPad());
696 assert(!EHStack.empty());
697
David Blaikiebbafb8a2012-03-11 07:00:24 +0000698 if (!CGM.getLangOpts().Exceptions)
Craig Topper8a13c412014-05-21 05:09:00 +0000699 return nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000700
John McCallbd309292010-07-06 01:34:17 +0000701 // Check the innermost scope for a cached landing pad. If this is
702 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
703 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
704 if (LP) return LP;
705
706 // Build the landing pad for this scope.
707 LP = EmitLandingPad();
708 assert(LP);
709
710 // Cache the landing pad on the innermost scope. If this is a
711 // non-EH scope, cache the landing pad on the enclosing scope, too.
712 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
713 ir->setCachedLandingPad(LP);
714 if (!isNonEHScope(*ir)) break;
715 }
716
717 return LP;
718}
719
720llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
721 assert(EHStack.requiresLandingPad());
722
John McCall8e4c74b2011-08-11 02:22:43 +0000723 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
724 switch (innermostEHScope.getKind()) {
725 case EHScope::Terminate:
726 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000727
John McCall8e4c74b2011-08-11 02:22:43 +0000728 case EHScope::Catch:
729 case EHScope::Cleanup:
730 case EHScope::Filter:
731 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
732 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000733 }
734
735 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000736 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantld1b151e2014-01-17 00:15:10 +0000737 SaveAndRestoreLocation AutoRestoreLocation(*this, Builder);
738 if (CGDebugInfo *DI = getDebugInfo())
Adrian Prantl5e5ff6e2013-05-16 00:41:29 +0000739 DI->EmitLocation(Builder, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000740
Reid Klecknere070b992014-11-14 02:01:10 +0000741 const EHPersonality &personality = EHPersonality::get(CGM);
John McCall36ea3722010-07-17 00:43:08 +0000742
John McCallbd309292010-07-06 01:34:17 +0000743 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000744 llvm::BasicBlock *lpad = createBasicBlock("lpad");
745 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000746
Bill Wendlingf0724e82011-09-19 20:31:14 +0000747 llvm::LandingPadInst *LPadInst =
748 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
749 getOpaquePersonalityFn(CGM, personality), 0);
750
751 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
752 Builder.CreateStore(LPadExn, getExceptionSlot());
753 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
754 Builder.CreateStore(LPadSel, getEHSelectorSlot());
755
John McCallbd309292010-07-06 01:34:17 +0000756 // Save the exception pointer. It's safe to use a single exception
757 // pointer per function because EH cleanups can never have nested
758 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000759 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000760
761 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000762 bool hasCatchAll = false;
763 bool hasCleanup = false;
764 bool hasFilter = false;
765 SmallVector<llvm::Value*, 4> filterTypes;
766 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallbd309292010-07-06 01:34:17 +0000767 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
768 I != E; ++I) {
769
770 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000771 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000772 // If we have a cleanup, remember that.
773 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000774 continue;
775
John McCallbd309292010-07-06 01:34:17 +0000776 case EHScope::Filter: {
777 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000778 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000779
Bill Wendlingf0724e82011-09-19 20:31:14 +0000780 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000781 EHFilterScope &filter = cast<EHFilterScope>(*I);
782 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000783
Bill Wendling8c4b7162011-09-22 20:32:54 +0000784 // Add all the filter values.
785 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
786 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000787 goto done;
788 }
789
790 case EHScope::Terminate:
791 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000792 assert(!hasCatchAll);
793 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000794 goto done;
795
796 case EHScope::Catch:
797 break;
798 }
799
John McCall8e4c74b2011-08-11 02:22:43 +0000800 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
801 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
802 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000803
John McCall8e4c74b2011-08-11 02:22:43 +0000804 // If this is a catch-all, register that and abort.
805 if (!handler.Type) {
806 assert(!hasCatchAll);
807 hasCatchAll = true;
808 goto done;
John McCallbd309292010-07-06 01:34:17 +0000809 }
810
811 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000812 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000813 // If not, add it directly to the landingpad.
814 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000815 }
John McCallbd309292010-07-06 01:34:17 +0000816 }
817
818 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000819 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000820 assert(!(hasCatchAll && hasFilter));
821 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000822 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000823
824 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000825 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000826 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000827 // Create a filter expression: a constant array indicating which filter
828 // types there are. The personality routine only lands here if the filter
829 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000830 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000831 llvm::ArrayType *AType =
832 llvm::ArrayType::get(!filterTypes.empty() ?
833 filterTypes[0]->getType() : Int8PtrTy,
834 filterTypes.size());
835
836 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
837 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
838 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
839 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000840
841 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000842 if (hasCleanup)
843 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000844
845 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000846 } else if (hasCleanup) {
847 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000848 }
849
Bill Wendlingf0724e82011-09-19 20:31:14 +0000850 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
851 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000852
853 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000854 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000855
856 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000857 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000858
John McCall8e4c74b2011-08-11 02:22:43 +0000859 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000860}
861
John McCall5c08ab92010-07-13 22:12:14 +0000862namespace {
863 /// A cleanup to call __cxa_end_catch. In many cases, the caught
864 /// exception type lets us state definitively that the thrown exception
865 /// type does not have a destructor. In particular:
866 /// - Catch-alls tell us nothing, so we have to conservatively
867 /// assume that the thrown exception might have a destructor.
868 /// - Catches by reference behave according to their base types.
869 /// - Catches of non-record types will only trigger for exceptions
870 /// of non-record types, which never have destructors.
871 /// - Catches of record types can trigger for arbitrary subclasses
872 /// of the caught type, so we have to assume the actual thrown
873 /// exception type might have a throwing destructor, even if the
874 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000875 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000876 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
877 bool MightThrow;
878
Craig Topper4f12f102014-03-12 06:41:41 +0000879 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5c08ab92010-07-13 22:12:14 +0000880 if (!MightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000881 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000882 return;
883 }
884
John McCall882987f2013-02-28 19:01:20 +0000885 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000886 }
887 };
888}
889
John McCallbd309292010-07-06 01:34:17 +0000890/// Emits a call to __cxa_begin_catch and enters a cleanup to call
891/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000892///
893/// \param EndMightThrow - true if __cxa_end_catch might throw
894static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
895 llvm::Value *Exn,
896 bool EndMightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000897 llvm::CallInst *call =
898 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +0000899
John McCallcda666c2010-07-21 07:22:38 +0000900 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000901
John McCall882987f2013-02-28 19:01:20 +0000902 return call;
John McCallbd309292010-07-06 01:34:17 +0000903}
904
905/// A "special initializer" callback for initializing a catch
906/// parameter during catch initialization.
907static void InitCatchParam(CodeGenFunction &CGF,
908 const VarDecl &CatchParam,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000909 llvm::Value *ParamAddr,
910 SourceLocation Loc) {
John McCallbd309292010-07-06 01:34:17 +0000911 // Load the exception from where the landing pad saved it.
Bill Wendling79a70e42011-09-15 18:57:19 +0000912 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallbd309292010-07-06 01:34:17 +0000913
914 CanQualType CatchType =
915 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000916 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallbd309292010-07-06 01:34:17 +0000917
918 // If we're catching by reference, we can just cast the object
919 // pointer to the appropriate pointer.
920 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000921 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
922 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000923
John McCallbd309292010-07-06 01:34:17 +0000924 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000925 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000926
927 // We have no way to tell the personality function that we're
928 // catching by reference, so if we're catching a pointer,
929 // __cxa_begin_catch will actually return that pointer by value.
930 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
931 QualType PointeeType = PT->getPointeeType();
932
933 // When catching by reference, generally we should just ignore
934 // this by-value pointer and use the exception object instead.
935 if (!PointeeType->isRecordType()) {
936
937 // Exn points to the struct _Unwind_Exception header, which
938 // we have to skip past in order to reach the exception data.
939 unsigned HeaderSize =
940 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
941 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
942
943 // However, if we're catching a pointer-to-record type that won't
944 // work, because the personality function might have adjusted
945 // the pointer. There's actually no way for us to fully satisfy
946 // the language/ABI contract here: we can't use Exn because it
947 // might have the wrong adjustment, but we can't use the by-value
948 // pointer because it's off by a level of abstraction.
949 //
950 // The current solution is to dump the adjusted pointer into an
951 // alloca, which breaks language semantics (because changing the
952 // pointer doesn't change the exception) but at least works.
953 // The better solution would be to filter out non-exact matches
954 // and rethrow them, but this is tricky because the rethrow
955 // really needs to be catchable by other sites at this landing
956 // pad. The best solution is to fix the personality function.
957 } else {
958 // Pull the pointer for the reference type off.
Chris Lattner2192fe52011-07-18 04:24:23 +0000959 llvm::Type *PtrTy =
John McCall5add20c2010-07-20 22:17:55 +0000960 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
961
962 // Create the temporary and write the adjusted pointer into it.
963 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
964 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
965 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
966
967 // Bind the reference to the temporary.
968 AdjustedExn = ExnPtrTmp;
969 }
970 }
971
John McCallbd309292010-07-06 01:34:17 +0000972 llvm::Value *ExnCast =
973 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
974 CGF.Builder.CreateStore(ExnCast, ParamAddr);
975 return;
976 }
977
John McCall47fb9502013-03-07 21:37:08 +0000978 // Scalars and complexes.
979 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
980 if (TEK != TEK_Aggregate) {
John McCall5c08ab92010-07-13 22:12:14 +0000981 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +0000982
983 // If the catch type is a pointer type, __cxa_begin_catch returns
984 // the pointer by value.
985 if (CatchType->hasPointerRepresentation()) {
986 llvm::Value *CastExn =
987 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCall97017312012-01-17 20:16:56 +0000988
989 switch (CatchType.getQualifiers().getObjCLifetime()) {
990 case Qualifiers::OCL_Strong:
991 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
992 // fallthrough
993
994 case Qualifiers::OCL_None:
995 case Qualifiers::OCL_ExplicitNone:
996 case Qualifiers::OCL_Autoreleasing:
997 CGF.Builder.CreateStore(CastExn, ParamAddr);
998 return;
999
1000 case Qualifiers::OCL_Weak:
1001 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1002 return;
1003 }
1004 llvm_unreachable("bad ownership qualifier!");
John McCallbd309292010-07-06 01:34:17 +00001005 }
1006
1007 // Otherwise, it returns a pointer into the exception object.
1008
Chris Lattner2192fe52011-07-18 04:24:23 +00001009 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001010 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1011
John McCall47fb9502013-03-07 21:37:08 +00001012 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1013 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1014 CGF.getContext().getDeclAlign(&CatchParam));
1015 switch (TEK) {
1016 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00001017 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall47fb9502013-03-07 21:37:08 +00001018 /*init*/ true);
1019 return;
1020 case TEK_Scalar: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001021 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00001022 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1023 return;
John McCallbd309292010-07-06 01:34:17 +00001024 }
John McCall47fb9502013-03-07 21:37:08 +00001025 case TEK_Aggregate:
1026 llvm_unreachable("evaluation kind filtered out!");
1027 }
1028 llvm_unreachable("bad evaluation kind");
John McCallbd309292010-07-06 01:34:17 +00001029 }
1030
John McCallb5011ab2011-02-16 08:39:19 +00001031 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001032
Chris Lattner2192fe52011-07-18 04:24:23 +00001033 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001034
John McCallb5011ab2011-02-16 08:39:19 +00001035 // Check for a copy expression. If we don't have a copy expression,
1036 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001037 const Expr *copyExpr = CatchParam.getInit();
1038 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001039 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1040 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001041 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001042 return;
1043 }
1044
1045 // We have to call __cxa_get_exception_ptr to get the adjusted
1046 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001047 llvm::CallInst *rawAdjustedExn =
John McCall882987f2013-02-28 19:01:20 +00001048 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +00001049
John McCall1bf58462011-02-16 08:02:54 +00001050 // Cast that to the appropriate type.
1051 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001052
John McCall1bf58462011-02-16 08:02:54 +00001053 // The copy expression is defined in terms of an OpaqueValueExpr.
1054 // Find it and map it to the adjusted expression.
1055 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001056 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1057 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001058
1059 // Call the copy ctor in a terminate scope.
1060 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001061
1062 // Perform the copy construction.
Eli Friedman38cd36d2011-12-03 02:13:40 +00001063 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001064 CGF.EmitAggExpr(copyExpr,
1065 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1066 AggValueSlot::IsNotDestructed,
1067 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001068 AggValueSlot::IsNotAliased));
John McCall1bf58462011-02-16 08:02:54 +00001069
1070 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001071 CGF.EHStack.popTerminate();
1072
John McCall1bf58462011-02-16 08:02:54 +00001073 // Undo the opaque value mapping.
1074 opaque.pop();
1075
John McCallbd309292010-07-06 01:34:17 +00001076 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001077 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001078}
1079
1080/// Begins a catch statement by initializing the catch variable and
1081/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001082static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001083 // We have to be very careful with the ordering of cleanups here:
1084 // C++ [except.throw]p4:
1085 // The destruction [of the exception temporary] occurs
1086 // immediately after the destruction of the object declared in
1087 // the exception-declaration in the handler.
1088 //
1089 // So the precise ordering is:
1090 // 1. Construct catch variable.
1091 // 2. __cxa_begin_catch
1092 // 3. Enter __cxa_end_catch cleanup
1093 // 4. Enter dtor cleanup
1094 //
John McCallc533cb72011-02-22 06:44:22 +00001095 // We do this by using a slightly abnormal initialization process.
1096 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001097 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001098 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001099 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001100 // - CallBeginCatch calls __cxa_begin_catch
1101 // - CallBeginCatch enters the __cxa_end_catch cleanup
1102 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001103 // - EmitCXXTryStmt emits the code for the catch body
1104 // - EmitCXXTryStmt close the RunCleanupsScope
1105
1106 VarDecl *CatchParam = S->getExceptionDecl();
1107 if (!CatchParam) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001108 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall5c08ab92010-07-13 22:12:14 +00001109 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001110 return;
1111 }
1112
1113 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001114 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001115 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCallc533cb72011-02-22 06:44:22 +00001116 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001117}
1118
John McCall8e4c74b2011-08-11 02:22:43 +00001119/// Emit the structure of the dispatch block for the given catch scope.
1120/// It is an invariant that the dispatch block already exists.
1121static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1122 EHCatchScope &catchScope) {
1123 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1124 assert(dispatchBlock);
1125
1126 // If there's only a single catch-all, getEHDispatchBlock returned
1127 // that catch-all as the dispatch block.
1128 if (catchScope.getNumHandlers() == 1 &&
1129 catchScope.getHandler(0).isCatchAll()) {
1130 assert(dispatchBlock == catchScope.getHandler(0).Block);
1131 return;
1132 }
1133
1134 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1135 CGF.EmitBlockAfterUses(dispatchBlock);
1136
1137 // Select the right handler.
1138 llvm::Value *llvm_eh_typeid_for =
1139 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1140
1141 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001142 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001143
1144 // Test against each of the exception types we claim to catch.
1145 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1146 assert(i < e && "ran off end of handlers!");
1147 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1148
1149 llvm::Value *typeValue = handler.Type;
1150 assert(typeValue && "fell into catch-all case!");
1151 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1152
1153 // Figure out the next block.
1154 bool nextIsEnd;
1155 llvm::BasicBlock *nextBlock;
1156
1157 // If this is the last handler, we're at the end, and the next
1158 // block is the block for the enclosing EH scope.
1159 if (i + 1 == e) {
1160 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1161 nextIsEnd = true;
1162
1163 // If the next handler is a catch-all, we're at the end, and the
1164 // next block is that handler.
1165 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1166 nextBlock = catchScope.getHandler(i+1).Block;
1167 nextIsEnd = true;
1168
1169 // Otherwise, we're not at the end and we need a new block.
1170 } else {
1171 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1172 nextIsEnd = false;
1173 }
1174
1175 // Figure out the catch type's index in the LSDA's type table.
1176 llvm::CallInst *typeIndex =
1177 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1178 typeIndex->setDoesNotThrow();
1179
1180 llvm::Value *matchesTypeIndex =
1181 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1182 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1183
1184 // If the next handler is a catch-all, we're completely done.
1185 if (nextIsEnd) {
1186 CGF.Builder.restoreIP(savedIP);
1187 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001188 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001189 // Otherwise we need to emit and continue at that block.
1190 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001191 }
John McCall8e4c74b2011-08-11 02:22:43 +00001192}
1193
1194void CodeGenFunction::popCatchScope() {
1195 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1196 if (catchScope.hasEHBranches())
1197 emitCatchDispatchBlock(*this, catchScope);
1198 EHStack.popCatch();
1199}
1200
John McCallb609d3f2010-07-07 06:56:46 +00001201void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001202 unsigned NumHandlers = S.getNumHandlers();
1203 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1204 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001205
John McCall8e4c74b2011-08-11 02:22:43 +00001206 // If the catch was not required, bail out now.
1207 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001208 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001209 EHStack.popCatch();
1210 return;
1211 }
1212
1213 // Emit the structure of the EH dispatch for this catch.
1214 emitCatchDispatchBlock(*this, CatchScope);
1215
John McCallbd309292010-07-06 01:34:17 +00001216 // Copy the handler blocks off before we pop the EH stack. Emitting
1217 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001218 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +00001219 memcpy(Handlers.data(), CatchScope.begin(),
1220 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +00001221
John McCallbd309292010-07-06 01:34:17 +00001222 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001223
John McCallbd309292010-07-06 01:34:17 +00001224 // The fall-through block.
1225 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001226
John McCallbd309292010-07-06 01:34:17 +00001227 // We just emitted the body of the try; jump to the continue block.
1228 if (HaveInsertPoint())
1229 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001230
John McCalld8d00be2012-06-15 05:27:05 +00001231 // Determine if we need an implicit rethrow for all these catch handlers;
1232 // see the comment below.
1233 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001234 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001235 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1236 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001237
John McCall8e4c74b2011-08-11 02:22:43 +00001238 // Perversely, we emit the handlers backwards precisely because we
1239 // want them to appear in source order. In all of these cases, the
1240 // catch block will have exactly one predecessor, which will be a
1241 // particular block in the catch dispatch. However, in the case of
1242 // a catch-all, one of the dispatch blocks will branch to two
1243 // different handlers, and EmitBlockAfterUses will cause the second
1244 // handler to be moved before the first.
1245 for (unsigned I = NumHandlers; I != 0; --I) {
1246 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1247 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001248
John McCallbd309292010-07-06 01:34:17 +00001249 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001250 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001251
John McCallbd309292010-07-06 01:34:17 +00001252 // Enter a cleanup scope, including the catch variable and the
1253 // end-catch.
1254 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001255
John McCallbd309292010-07-06 01:34:17 +00001256 // Initialize the catch variable and set up the cleanups.
1257 BeginCatch(*this, C);
1258
Justin Bognerea278c32014-01-07 00:20:28 +00001259 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +00001260 RegionCounter CatchCnt = getPGORegionCounter(C);
1261 CatchCnt.beginRegion(Builder);
1262
John McCallbd309292010-07-06 01:34:17 +00001263 // Perform the body of the catch.
1264 EmitStmt(C->getHandlerBlock());
1265
John McCalld8d00be2012-06-15 05:27:05 +00001266 // [except.handle]p11:
1267 // The currently handled exception is rethrown if control
1268 // reaches the end of a handler of the function-try-block of a
1269 // constructor or destructor.
1270
1271 // It is important that we only do this on fallthrough and not on
1272 // return. Note that it's illegal to put a return in a
1273 // constructor function-try-block's catch handler (p14), so this
1274 // really only applies to destructors.
1275 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001276 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001277 Builder.CreateUnreachable();
1278 Builder.ClearInsertionPoint();
1279 }
1280
John McCallbd309292010-07-06 01:34:17 +00001281 // Fall out through the catch cleanups.
1282 CatchScope.ForceCleanup();
1283
1284 // Branch out of the try.
1285 if (HaveInsertPoint())
1286 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001287 }
1288
Justin Bogneref512b92014-01-06 22:27:43 +00001289 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +00001290 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +00001291 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +00001292}
Mike Stumpaff69af2009-12-09 03:35:49 +00001293
John McCall1e670402010-07-21 00:52:03 +00001294namespace {
John McCallcda666c2010-07-21 07:22:38 +00001295 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001296 llvm::Value *ForEHVar;
1297 llvm::Value *EndCatchFn;
1298 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1299 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1300
Craig Topper4f12f102014-03-12 06:41:41 +00001301 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001302 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1303 llvm::BasicBlock *CleanupContBB =
1304 CGF.createBasicBlock("finally.cleanup.cont");
1305
1306 llvm::Value *ShouldEndCatch =
1307 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1308 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1309 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001310 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001311 CGF.EmitBlock(CleanupContBB);
1312 }
1313 };
John McCall906da4b2010-07-21 05:47:49 +00001314
John McCallcda666c2010-07-21 07:22:38 +00001315 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001316 const Stmt *Body;
1317 llvm::Value *ForEHVar;
1318 llvm::Value *EndCatchFn;
1319 llvm::Value *RethrowFn;
1320 llvm::Value *SavedExnVar;
1321
1322 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1323 llvm::Value *EndCatchFn,
1324 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1325 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1326 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1327
Craig Topper4f12f102014-03-12 06:41:41 +00001328 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001329 // Enter a cleanup to call the end-catch function if one was provided.
1330 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001331 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1332 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001333
John McCallcebe0ca2010-08-11 00:16:14 +00001334 // Save the current cleanup destination in case there are
1335 // cleanups in the finally block.
1336 llvm::Value *SavedCleanupDest =
1337 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1338 "cleanup.dest.saved");
1339
John McCall906da4b2010-07-21 05:47:49 +00001340 // Emit the finally block.
1341 CGF.EmitStmt(Body);
1342
1343 // If the end of the finally is reachable, check whether this was
1344 // for EH. If so, rethrow.
1345 if (CGF.HaveInsertPoint()) {
1346 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1347 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1348
1349 llvm::Value *ShouldRethrow =
1350 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1351 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1352
1353 CGF.EmitBlock(RethrowBB);
1354 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001355 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1356 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001357 } else {
John McCall882987f2013-02-28 19:01:20 +00001358 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001359 }
1360 CGF.Builder.CreateUnreachable();
1361
1362 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001363
1364 // Restore the cleanup destination.
1365 CGF.Builder.CreateStore(SavedCleanupDest,
1366 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001367 }
1368
1369 // Leave the end-catch cleanup. As an optimization, pretend that
1370 // the fallthrough path was inaccessible; we've dynamically proven
1371 // that we're not in the EH case along that path.
1372 if (EndCatchFn) {
1373 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1374 CGF.PopCleanupBlock();
1375 CGF.Builder.restoreIP(SavedIP);
1376 }
1377
1378 // Now make sure we actually have an insertion point or the
1379 // cleanup gods will hate us.
1380 CGF.EnsureInsertPoint();
1381 }
1382 };
John McCall1e670402010-07-21 00:52:03 +00001383}
1384
John McCallbd309292010-07-06 01:34:17 +00001385/// Enters a finally block for an implementation using zero-cost
1386/// exceptions. This is mostly general, but hard-codes some
1387/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001388void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1389 const Stmt *body,
1390 llvm::Constant *beginCatchFn,
1391 llvm::Constant *endCatchFn,
1392 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001393 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001394 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001395 assert(rethrowFn && "rethrow function is required");
1396
1397 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001398
John McCallbd309292010-07-06 01:34:17 +00001399 // The rethrow function has one of the following two types:
1400 // void (*)()
1401 // void (*)(void*)
1402 // In the latter case we need to pass it the exception object.
1403 // But we can't use the exception slot because the @finally might
1404 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001405 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001406 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001407 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001408 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001409 if (rethrowFnTy->getNumParams())
1410 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001411
John McCallbd309292010-07-06 01:34:17 +00001412 // A finally block is a statement which must be executed on any edge
1413 // out of a given scope. Unlike a cleanup, the finally block may
1414 // contain arbitrary control flow leading out of itself. In
1415 // addition, finally blocks should always be executed, even if there
1416 // are no catch handlers higher on the stack. Therefore, we
1417 // surround the protected scope with a combination of a normal
1418 // cleanup (to catch attempts to break out of the block via normal
1419 // control flow) and an EH catch-all (semantically "outside" any try
1420 // statement to which the finally block might have been attached).
1421 // The finally block itself is generated in the context of a cleanup
1422 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001423
John McCallbd309292010-07-06 01:34:17 +00001424 // Jump destination for performing the finally block on an exception
1425 // edge. We'll never actually reach this block, so unreachable is
1426 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001427 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001428
John McCallbd309292010-07-06 01:34:17 +00001429 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001430 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1431 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001432
John McCallbd309292010-07-06 01:34:17 +00001433 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001434 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1435 ForEHVar, endCatchFn,
1436 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001437
1438 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001439 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1440 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1441 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001442}
1443
John McCall6b0feb72011-06-22 02:32:12 +00001444void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001445 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001446 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1447 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001448
1449 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001450
John McCall6b0feb72011-06-22 02:32:12 +00001451 // If there are any references to the catch-all block, emit it.
1452 if (catchBB->use_empty()) {
1453 delete catchBB;
1454 } else {
1455 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1456 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001457
Craig Topper8a13c412014-05-21 05:09:00 +00001458 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001459
John McCall6b0feb72011-06-22 02:32:12 +00001460 // If there's a begin-catch function, call it.
1461 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001462 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001463 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001464 }
1465
1466 // If we need to remember the exception pointer to rethrow later, do so.
1467 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001468 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001469 CGF.Builder.CreateStore(exn, SavedExnVar);
1470 }
1471
1472 // Tell the cleanups in the finally block that we're do this for EH.
1473 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1474
1475 // Thread a jump through the finally cleanup.
1476 CGF.EmitBranchThroughCleanup(RethrowDest);
1477
1478 CGF.Builder.restoreIP(savedIP);
1479 }
1480
1481 // Finally, leave the @finally cleanup.
1482 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001483}
1484
John McCalle142ad52013-02-12 03:51:46 +00001485/// In a terminate landing pad, should we use __clang__call_terminate
1486/// or just a naked call to std::terminate?
1487///
1488/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1489/// std::terminate to usefully report something about the
1490/// violating exception.
1491static bool useClangCallTerminate(CodeGenModule &CGM) {
1492 // Only do this for Itanium-family ABIs in C++ mode.
1493 return (CGM.getLangOpts().CPlusPlus &&
1494 CGM.getTarget().getCXXABI().isItaniumFamily());
1495}
1496
1497/// Get or define the following function:
1498/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1499/// This code is used only in C++.
1500static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1501 llvm::FunctionType *fnTy =
1502 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1503 llvm::Constant *fnRef =
1504 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1505
1506 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1507 if (fn && fn->empty()) {
1508 fn->setDoesNotThrow();
1509 fn->setDoesNotReturn();
1510
1511 // What we really want is to massively penalize inlining without
1512 // forbidding it completely. The difference between that and
1513 // 'noinline' is negligible.
1514 fn->addFnAttr(llvm::Attribute::NoInline);
1515
1516 // Allow this function to be shared across translation units, but
1517 // we don't want it to turn into an exported symbol.
1518 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1519 fn->setVisibility(llvm::Function::HiddenVisibility);
1520
1521 // Set up the function.
1522 llvm::BasicBlock *entry =
1523 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1524 CGBuilderTy builder(entry);
1525
1526 // Pull the exception pointer out of the parameter list.
1527 llvm::Value *exn = &*fn->arg_begin();
1528
1529 // Call __cxa_begin_catch(exn).
John McCall882987f2013-02-28 19:01:20 +00001530 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1531 catchCall->setDoesNotThrow();
1532 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001533
1534 // Call std::terminate().
1535 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1536 termCall->setDoesNotThrow();
1537 termCall->setDoesNotReturn();
John McCall882987f2013-02-28 19:01:20 +00001538 termCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001539
1540 // std::terminate cannot return.
1541 builder.CreateUnreachable();
1542 }
1543
1544 return fnRef;
1545}
1546
John McCallbd309292010-07-06 01:34:17 +00001547llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1548 if (TerminateLandingPad)
1549 return TerminateLandingPad;
1550
1551 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1552
1553 // This will get inserted at the end of the function.
1554 TerminateLandingPad = createBasicBlock("terminate.lpad");
1555 Builder.SetInsertPoint(TerminateLandingPad);
1556
1557 // Tell the backend that this is a landing pad.
Reid Klecknere070b992014-11-14 02:01:10 +00001558 const EHPersonality &Personality = EHPersonality::get(CGM);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001559 llvm::LandingPadInst *LPadInst =
1560 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
1561 getOpaquePersonalityFn(CGM, Personality), 0);
1562 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001563
John McCalle142ad52013-02-12 03:51:46 +00001564 llvm::CallInst *terminateCall;
1565 if (useClangCallTerminate(CGM)) {
1566 // Extract out the exception pointer.
1567 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCall882987f2013-02-28 19:01:20 +00001568 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCalle142ad52013-02-12 03:51:46 +00001569 } else {
John McCall882987f2013-02-28 19:01:20 +00001570 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCalle142ad52013-02-12 03:51:46 +00001571 }
1572 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001573 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001574
John McCallbd309292010-07-06 01:34:17 +00001575 // Restore the saved insertion state.
1576 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001577
John McCallbd309292010-07-06 01:34:17 +00001578 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001579}
Mike Stump2b488872009-12-09 22:59:31 +00001580
1581llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001582 if (TerminateHandler)
1583 return TerminateHandler;
1584
John McCallbd309292010-07-06 01:34:17 +00001585 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001586
John McCallbd309292010-07-06 01:34:17 +00001587 // Set up the terminate handler. This block is inserted at the very
1588 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001589 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001590 Builder.SetInsertPoint(TerminateHandler);
John McCallc84e4e92013-06-20 21:37:43 +00001591 llvm::CallInst *terminateCall;
1592 if (useClangCallTerminate(CGM)) {
1593 // Load the exception pointer.
1594 llvm::Value *exn = getExceptionFromSlot();
1595 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1596 } else {
1597 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1598 }
1599 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001600 Builder.CreateUnreachable();
1601
John McCall21886962010-04-21 10:05:39 +00001602 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001603 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001604
Mike Stump2b488872009-12-09 22:59:31 +00001605 return TerminateHandler;
1606}
John McCallbd309292010-07-06 01:34:17 +00001607
David Chisnall9a837be2012-11-07 16:50:40 +00001608llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001609 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001610
1611 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1612
1613 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001614 EHResumeBlock = createBasicBlock("eh.resume");
1615 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001616
Reid Klecknere070b992014-11-14 02:01:10 +00001617 const EHPersonality &Personality = EHPersonality::get(CGM);
John McCallad5d61e2010-07-23 21:56:41 +00001618
1619 // This can always be a call because we necessarily didn't find
1620 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001621 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001622 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001623 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001624 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001625 ->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001626 Builder.CreateUnreachable();
1627 Builder.restoreIP(SavedIP);
1628 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001629 }
1630
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001631 // Recreate the landingpad's return value for the 'resume' instruction.
1632 llvm::Value *Exn = getExceptionFromSlot();
1633 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001634
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001635 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
1636 Sel->getType(), NULL);
1637 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1638 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1639 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1640
1641 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001642 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001643 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001644}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001645
1646void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1647 CGM.ErrorUnsupported(&S, "SEH __try");
1648}
Nico Weber9b982072014-07-07 00:12:30 +00001649
1650void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1651 CGM.ErrorUnsupported(&S, "SEH __leave");
1652}