blob: 4b57533c609adaedfc1d2b8734637cb90c59666b [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();
David Blaikie3945d1b2014-12-29 18:18:45 +0000737 ApplyDebugLocation AutoRestoreLocation(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000738
Reid Klecknere070b992014-11-14 02:01:10 +0000739 const EHPersonality &personality = EHPersonality::get(CGM);
John McCall36ea3722010-07-17 00:43:08 +0000740
John McCallbd309292010-07-06 01:34:17 +0000741 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000742 llvm::BasicBlock *lpad = createBasicBlock("lpad");
743 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000744
Bill Wendlingf0724e82011-09-19 20:31:14 +0000745 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000746 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +0000747 getOpaquePersonalityFn(CGM, personality), 0);
748
749 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
750 Builder.CreateStore(LPadExn, getExceptionSlot());
751 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
752 Builder.CreateStore(LPadSel, getEHSelectorSlot());
753
John McCallbd309292010-07-06 01:34:17 +0000754 // Save the exception pointer. It's safe to use a single exception
755 // pointer per function because EH cleanups can never have nested
756 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000757 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000758
759 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000760 bool hasCatchAll = false;
761 bool hasCleanup = false;
762 bool hasFilter = false;
763 SmallVector<llvm::Value*, 4> filterTypes;
764 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
John McCallbd309292010-07-06 01:34:17 +0000765 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
766 I != E; ++I) {
767
768 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000769 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000770 // If we have a cleanup, remember that.
771 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000772 continue;
773
John McCallbd309292010-07-06 01:34:17 +0000774 case EHScope::Filter: {
775 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000776 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000777
Bill Wendlingf0724e82011-09-19 20:31:14 +0000778 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000779 EHFilterScope &filter = cast<EHFilterScope>(*I);
780 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000781
Bill Wendling8c4b7162011-09-22 20:32:54 +0000782 // Add all the filter values.
783 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
784 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000785 goto done;
786 }
787
788 case EHScope::Terminate:
789 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000790 assert(!hasCatchAll);
791 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000792 goto done;
793
794 case EHScope::Catch:
795 break;
796 }
797
John McCall8e4c74b2011-08-11 02:22:43 +0000798 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
799 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
800 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000801
John McCall8e4c74b2011-08-11 02:22:43 +0000802 // If this is a catch-all, register that and abort.
803 if (!handler.Type) {
804 assert(!hasCatchAll);
805 hasCatchAll = true;
806 goto done;
John McCallbd309292010-07-06 01:34:17 +0000807 }
808
809 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000810 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000811 // If not, add it directly to the landingpad.
812 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000813 }
John McCallbd309292010-07-06 01:34:17 +0000814 }
815
816 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000817 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000818 assert(!(hasCatchAll && hasFilter));
819 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000820 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000821
822 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000823 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000824 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000825 // Create a filter expression: a constant array indicating which filter
826 // types there are. The personality routine only lands here if the filter
827 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000828 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000829 llvm::ArrayType *AType =
830 llvm::ArrayType::get(!filterTypes.empty() ?
831 filterTypes[0]->getType() : Int8PtrTy,
832 filterTypes.size());
833
834 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
835 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
836 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
837 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000838
839 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000840 if (hasCleanup)
841 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000842
843 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000844 } else if (hasCleanup) {
845 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000846 }
847
Bill Wendlingf0724e82011-09-19 20:31:14 +0000848 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
849 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000850
851 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000852 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000853
854 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000855 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000856
John McCall8e4c74b2011-08-11 02:22:43 +0000857 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000858}
859
John McCall5c08ab92010-07-13 22:12:14 +0000860namespace {
861 /// A cleanup to call __cxa_end_catch. In many cases, the caught
862 /// exception type lets us state definitively that the thrown exception
863 /// type does not have a destructor. In particular:
864 /// - Catch-alls tell us nothing, so we have to conservatively
865 /// assume that the thrown exception might have a destructor.
866 /// - Catches by reference behave according to their base types.
867 /// - Catches of non-record types will only trigger for exceptions
868 /// of non-record types, which never have destructors.
869 /// - Catches of record types can trigger for arbitrary subclasses
870 /// of the caught type, so we have to assume the actual thrown
871 /// exception type might have a throwing destructor, even if the
872 /// caught type's destructor is trivial or nothrow.
John McCallcda666c2010-07-21 07:22:38 +0000873 struct CallEndCatch : EHScopeStack::Cleanup {
John McCall5c08ab92010-07-13 22:12:14 +0000874 CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
875 bool MightThrow;
876
Craig Topper4f12f102014-03-12 06:41:41 +0000877 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5c08ab92010-07-13 22:12:14 +0000878 if (!MightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000879 CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000880 return;
881 }
882
John McCall882987f2013-02-28 19:01:20 +0000883 CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
John McCall5c08ab92010-07-13 22:12:14 +0000884 }
885 };
886}
887
John McCallbd309292010-07-06 01:34:17 +0000888/// Emits a call to __cxa_begin_catch and enters a cleanup to call
889/// __cxa_end_catch.
John McCall5c08ab92010-07-13 22:12:14 +0000890///
891/// \param EndMightThrow - true if __cxa_end_catch might throw
892static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
893 llvm::Value *Exn,
894 bool EndMightThrow) {
John McCall882987f2013-02-28 19:01:20 +0000895 llvm::CallInst *call =
896 CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +0000897
John McCallcda666c2010-07-21 07:22:38 +0000898 CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
John McCallbd309292010-07-06 01:34:17 +0000899
John McCall882987f2013-02-28 19:01:20 +0000900 return call;
John McCallbd309292010-07-06 01:34:17 +0000901}
902
903/// A "special initializer" callback for initializing a catch
904/// parameter during catch initialization.
905static void InitCatchParam(CodeGenFunction &CGF,
906 const VarDecl &CatchParam,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000907 llvm::Value *ParamAddr,
908 SourceLocation Loc) {
John McCallbd309292010-07-06 01:34:17 +0000909 // Load the exception from where the landing pad saved it.
Bill Wendling79a70e42011-09-15 18:57:19 +0000910 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCallbd309292010-07-06 01:34:17 +0000911
912 CanQualType CatchType =
913 CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000914 llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
John McCallbd309292010-07-06 01:34:17 +0000915
916 // If we're catching by reference, we can just cast the object
917 // pointer to the appropriate pointer.
918 if (isa<ReferenceType>(CatchType)) {
John McCall5add20c2010-07-20 22:17:55 +0000919 QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
920 bool EndCatchMightThrow = CaughtType->isRecordType();
John McCall5c08ab92010-07-13 22:12:14 +0000921
John McCallbd309292010-07-06 01:34:17 +0000922 // __cxa_begin_catch returns the adjusted object pointer.
John McCall5c08ab92010-07-13 22:12:14 +0000923 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
John McCall5add20c2010-07-20 22:17:55 +0000924
925 // We have no way to tell the personality function that we're
926 // catching by reference, so if we're catching a pointer,
927 // __cxa_begin_catch will actually return that pointer by value.
928 if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
929 QualType PointeeType = PT->getPointeeType();
930
931 // When catching by reference, generally we should just ignore
932 // this by-value pointer and use the exception object instead.
933 if (!PointeeType->isRecordType()) {
934
935 // Exn points to the struct _Unwind_Exception header, which
936 // we have to skip past in order to reach the exception data.
937 unsigned HeaderSize =
938 CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
939 AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
940
941 // However, if we're catching a pointer-to-record type that won't
942 // work, because the personality function might have adjusted
943 // the pointer. There's actually no way for us to fully satisfy
944 // the language/ABI contract here: we can't use Exn because it
945 // might have the wrong adjustment, but we can't use the by-value
946 // pointer because it's off by a level of abstraction.
947 //
948 // The current solution is to dump the adjusted pointer into an
949 // alloca, which breaks language semantics (because changing the
950 // pointer doesn't change the exception) but at least works.
951 // The better solution would be to filter out non-exact matches
952 // and rethrow them, but this is tricky because the rethrow
953 // really needs to be catchable by other sites at this landing
954 // pad. The best solution is to fix the personality function.
955 } else {
956 // Pull the pointer for the reference type off.
Chris Lattner2192fe52011-07-18 04:24:23 +0000957 llvm::Type *PtrTy =
John McCall5add20c2010-07-20 22:17:55 +0000958 cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
959
960 // Create the temporary and write the adjusted pointer into it.
961 llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
962 llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
963 CGF.Builder.CreateStore(Casted, ExnPtrTmp);
964
965 // Bind the reference to the temporary.
966 AdjustedExn = ExnPtrTmp;
967 }
968 }
969
John McCallbd309292010-07-06 01:34:17 +0000970 llvm::Value *ExnCast =
971 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
972 CGF.Builder.CreateStore(ExnCast, ParamAddr);
973 return;
974 }
975
John McCall47fb9502013-03-07 21:37:08 +0000976 // Scalars and complexes.
977 TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
978 if (TEK != TEK_Aggregate) {
John McCall5c08ab92010-07-13 22:12:14 +0000979 llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
John McCallbd309292010-07-06 01:34:17 +0000980
981 // If the catch type is a pointer type, __cxa_begin_catch returns
982 // the pointer by value.
983 if (CatchType->hasPointerRepresentation()) {
984 llvm::Value *CastExn =
985 CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
John McCall97017312012-01-17 20:16:56 +0000986
987 switch (CatchType.getQualifiers().getObjCLifetime()) {
988 case Qualifiers::OCL_Strong:
989 CastExn = CGF.EmitARCRetainNonBlock(CastExn);
990 // fallthrough
991
992 case Qualifiers::OCL_None:
993 case Qualifiers::OCL_ExplicitNone:
994 case Qualifiers::OCL_Autoreleasing:
995 CGF.Builder.CreateStore(CastExn, ParamAddr);
996 return;
997
998 case Qualifiers::OCL_Weak:
999 CGF.EmitARCInitWeak(ParamAddr, CastExn);
1000 return;
1001 }
1002 llvm_unreachable("bad ownership qualifier!");
John McCallbd309292010-07-06 01:34:17 +00001003 }
1004
1005 // Otherwise, it returns a pointer into the exception object.
1006
Chris Lattner2192fe52011-07-18 04:24:23 +00001007 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001008 llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
1009
John McCall47fb9502013-03-07 21:37:08 +00001010 LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
1011 LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType,
1012 CGF.getContext().getDeclAlign(&CatchParam));
1013 switch (TEK) {
1014 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00001015 CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
John McCall47fb9502013-03-07 21:37:08 +00001016 /*init*/ true);
1017 return;
1018 case TEK_Scalar: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001019 llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00001020 CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
1021 return;
John McCallbd309292010-07-06 01:34:17 +00001022 }
John McCall47fb9502013-03-07 21:37:08 +00001023 case TEK_Aggregate:
1024 llvm_unreachable("evaluation kind filtered out!");
1025 }
1026 llvm_unreachable("bad evaluation kind");
John McCallbd309292010-07-06 01:34:17 +00001027 }
1028
John McCallb5011ab2011-02-16 08:39:19 +00001029 assert(isa<RecordType>(CatchType) && "unexpected catch type!");
John McCallbd309292010-07-06 01:34:17 +00001030
Chris Lattner2192fe52011-07-18 04:24:23 +00001031 llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
John McCallbd309292010-07-06 01:34:17 +00001032
John McCallb5011ab2011-02-16 08:39:19 +00001033 // Check for a copy expression. If we don't have a copy expression,
1034 // that means a trivial copy is okay.
John McCall1bf58462011-02-16 08:02:54 +00001035 const Expr *copyExpr = CatchParam.getInit();
1036 if (!copyExpr) {
John McCallb5011ab2011-02-16 08:39:19 +00001037 llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
1038 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001039 CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
John McCallbd309292010-07-06 01:34:17 +00001040 return;
1041 }
1042
1043 // We have to call __cxa_get_exception_ptr to get the adjusted
1044 // pointer before copying.
John McCall1bf58462011-02-16 08:02:54 +00001045 llvm::CallInst *rawAdjustedExn =
John McCall882987f2013-02-28 19:01:20 +00001046 CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
John McCallbd309292010-07-06 01:34:17 +00001047
John McCall1bf58462011-02-16 08:02:54 +00001048 // Cast that to the appropriate type.
1049 llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
John McCallbd309292010-07-06 01:34:17 +00001050
John McCall1bf58462011-02-16 08:02:54 +00001051 // The copy expression is defined in terms of an OpaqueValueExpr.
1052 // Find it and map it to the adjusted expression.
1053 CodeGenFunction::OpaqueValueMapping
John McCallc07a0c72011-02-17 10:25:35 +00001054 opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
1055 CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
John McCallbd309292010-07-06 01:34:17 +00001056
1057 // Call the copy ctor in a terminate scope.
1058 CGF.EHStack.pushTerminate();
John McCall1bf58462011-02-16 08:02:54 +00001059
1060 // Perform the copy construction.
Eli Friedman38cd36d2011-12-03 02:13:40 +00001061 CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001062 CGF.EmitAggExpr(copyExpr,
1063 AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
1064 AggValueSlot::IsNotDestructed,
1065 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001066 AggValueSlot::IsNotAliased));
John McCall1bf58462011-02-16 08:02:54 +00001067
1068 // Leave the terminate scope.
John McCallbd309292010-07-06 01:34:17 +00001069 CGF.EHStack.popTerminate();
1070
John McCall1bf58462011-02-16 08:02:54 +00001071 // Undo the opaque value mapping.
1072 opaque.pop();
1073
John McCallbd309292010-07-06 01:34:17 +00001074 // Finally we can call __cxa_begin_catch.
John McCall5c08ab92010-07-13 22:12:14 +00001075 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001076}
1077
1078/// Begins a catch statement by initializing the catch variable and
1079/// calling __cxa_begin_catch.
John McCall1bf58462011-02-16 08:02:54 +00001080static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
John McCallbd309292010-07-06 01:34:17 +00001081 // We have to be very careful with the ordering of cleanups here:
1082 // C++ [except.throw]p4:
1083 // The destruction [of the exception temporary] occurs
1084 // immediately after the destruction of the object declared in
1085 // the exception-declaration in the handler.
1086 //
1087 // So the precise ordering is:
1088 // 1. Construct catch variable.
1089 // 2. __cxa_begin_catch
1090 // 3. Enter __cxa_end_catch cleanup
1091 // 4. Enter dtor cleanup
1092 //
John McCallc533cb72011-02-22 06:44:22 +00001093 // We do this by using a slightly abnormal initialization process.
1094 // Delegation sequence:
John McCallbd309292010-07-06 01:34:17 +00001095 // - ExitCXXTryStmt opens a RunCleanupsScope
John McCallc533cb72011-02-22 06:44:22 +00001096 // - EmitAutoVarAlloca creates the variable and debug info
John McCallbd309292010-07-06 01:34:17 +00001097 // - InitCatchParam initializes the variable from the exception
John McCallc533cb72011-02-22 06:44:22 +00001098 // - CallBeginCatch calls __cxa_begin_catch
1099 // - CallBeginCatch enters the __cxa_end_catch cleanup
1100 // - EmitAutoVarCleanups enters the variable destructor cleanup
John McCallbd309292010-07-06 01:34:17 +00001101 // - EmitCXXTryStmt emits the code for the catch body
1102 // - EmitCXXTryStmt close the RunCleanupsScope
1103
1104 VarDecl *CatchParam = S->getExceptionDecl();
1105 if (!CatchParam) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001106 llvm::Value *Exn = CGF.getExceptionFromSlot();
John McCall5c08ab92010-07-13 22:12:14 +00001107 CallBeginCatch(CGF, Exn, true);
John McCallbd309292010-07-06 01:34:17 +00001108 return;
1109 }
1110
1111 // Emit the local.
John McCallc533cb72011-02-22 06:44:22 +00001112 CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001113 InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getLocStart());
John McCallc533cb72011-02-22 06:44:22 +00001114 CGF.EmitAutoVarCleanups(var);
John McCallb81884d2010-02-19 09:25:03 +00001115}
1116
John McCall8e4c74b2011-08-11 02:22:43 +00001117/// Emit the structure of the dispatch block for the given catch scope.
1118/// It is an invariant that the dispatch block already exists.
1119static void emitCatchDispatchBlock(CodeGenFunction &CGF,
1120 EHCatchScope &catchScope) {
1121 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1122 assert(dispatchBlock);
1123
1124 // If there's only a single catch-all, getEHDispatchBlock returned
1125 // that catch-all as the dispatch block.
1126 if (catchScope.getNumHandlers() == 1 &&
1127 catchScope.getHandler(0).isCatchAll()) {
1128 assert(dispatchBlock == catchScope.getHandler(0).Block);
1129 return;
1130 }
1131
1132 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1133 CGF.EmitBlockAfterUses(dispatchBlock);
1134
1135 // Select the right handler.
1136 llvm::Value *llvm_eh_typeid_for =
1137 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
1138
1139 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +00001140 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +00001141
1142 // Test against each of the exception types we claim to catch.
1143 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1144 assert(i < e && "ran off end of handlers!");
1145 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1146
1147 llvm::Value *typeValue = handler.Type;
1148 assert(typeValue && "fell into catch-all case!");
1149 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
1150
1151 // Figure out the next block.
1152 bool nextIsEnd;
1153 llvm::BasicBlock *nextBlock;
1154
1155 // If this is the last handler, we're at the end, and the next
1156 // block is the block for the enclosing EH scope.
1157 if (i + 1 == e) {
1158 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1159 nextIsEnd = true;
1160
1161 // If the next handler is a catch-all, we're at the end, and the
1162 // next block is that handler.
1163 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1164 nextBlock = catchScope.getHandler(i+1).Block;
1165 nextIsEnd = true;
1166
1167 // Otherwise, we're not at the end and we need a new block.
1168 } else {
1169 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1170 nextIsEnd = false;
1171 }
1172
1173 // Figure out the catch type's index in the LSDA's type table.
1174 llvm::CallInst *typeIndex =
1175 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1176 typeIndex->setDoesNotThrow();
1177
1178 llvm::Value *matchesTypeIndex =
1179 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1180 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1181
1182 // If the next handler is a catch-all, we're completely done.
1183 if (nextIsEnd) {
1184 CGF.Builder.restoreIP(savedIP);
1185 return;
John McCall8e4c74b2011-08-11 02:22:43 +00001186 }
Ahmed Charles289896d2012-02-19 11:57:29 +00001187 // Otherwise we need to emit and continue at that block.
1188 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +00001189 }
John McCall8e4c74b2011-08-11 02:22:43 +00001190}
1191
1192void CodeGenFunction::popCatchScope() {
1193 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1194 if (catchScope.hasEHBranches())
1195 emitCatchDispatchBlock(*this, catchScope);
1196 EHStack.popCatch();
1197}
1198
John McCallb609d3f2010-07-07 06:56:46 +00001199void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +00001200 unsigned NumHandlers = S.getNumHandlers();
1201 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1202 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +00001203
John McCall8e4c74b2011-08-11 02:22:43 +00001204 // If the catch was not required, bail out now.
1205 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +00001206 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +00001207 EHStack.popCatch();
1208 return;
1209 }
1210
1211 // Emit the structure of the EH dispatch for this catch.
1212 emitCatchDispatchBlock(*this, CatchScope);
1213
John McCallbd309292010-07-06 01:34:17 +00001214 // Copy the handler blocks off before we pop the EH stack. Emitting
1215 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001216 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +00001217 memcpy(Handlers.data(), CatchScope.begin(),
1218 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +00001219
John McCallbd309292010-07-06 01:34:17 +00001220 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +00001221
John McCallbd309292010-07-06 01:34:17 +00001222 // The fall-through block.
1223 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +00001224
John McCallbd309292010-07-06 01:34:17 +00001225 // We just emitted the body of the try; jump to the continue block.
1226 if (HaveInsertPoint())
1227 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +00001228
John McCalld8d00be2012-06-15 05:27:05 +00001229 // Determine if we need an implicit rethrow for all these catch handlers;
1230 // see the comment below.
1231 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +00001232 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +00001233 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1234 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +00001235
John McCall8e4c74b2011-08-11 02:22:43 +00001236 // Perversely, we emit the handlers backwards precisely because we
1237 // want them to appear in source order. In all of these cases, the
1238 // catch block will have exactly one predecessor, which will be a
1239 // particular block in the catch dispatch. However, in the case of
1240 // a catch-all, one of the dispatch blocks will branch to two
1241 // different handlers, and EmitBlockAfterUses will cause the second
1242 // handler to be moved before the first.
1243 for (unsigned I = NumHandlers; I != 0; --I) {
1244 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1245 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +00001246
John McCallbd309292010-07-06 01:34:17 +00001247 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +00001248 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +00001249
John McCallbd309292010-07-06 01:34:17 +00001250 // Enter a cleanup scope, including the catch variable and the
1251 // end-catch.
1252 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +00001253
John McCallbd309292010-07-06 01:34:17 +00001254 // Initialize the catch variable and set up the cleanups.
1255 BeginCatch(*this, C);
1256
Justin Bognerea278c32014-01-07 00:20:28 +00001257 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +00001258 RegionCounter CatchCnt = getPGORegionCounter(C);
1259 CatchCnt.beginRegion(Builder);
1260
John McCallbd309292010-07-06 01:34:17 +00001261 // Perform the body of the catch.
1262 EmitStmt(C->getHandlerBlock());
1263
John McCalld8d00be2012-06-15 05:27:05 +00001264 // [except.handle]p11:
1265 // The currently handled exception is rethrown if control
1266 // reaches the end of a handler of the function-try-block of a
1267 // constructor or destructor.
1268
1269 // It is important that we only do this on fallthrough and not on
1270 // return. Note that it's illegal to put a return in a
1271 // constructor function-try-block's catch handler (p14), so this
1272 // really only applies to destructors.
1273 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +00001274 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +00001275 Builder.CreateUnreachable();
1276 Builder.ClearInsertionPoint();
1277 }
1278
John McCallbd309292010-07-06 01:34:17 +00001279 // Fall out through the catch cleanups.
1280 CatchScope.ForceCleanup();
1281
1282 // Branch out of the try.
1283 if (HaveInsertPoint())
1284 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +00001285 }
1286
Justin Bogneref512b92014-01-06 22:27:43 +00001287 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +00001288 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +00001289 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +00001290}
Mike Stumpaff69af2009-12-09 03:35:49 +00001291
John McCall1e670402010-07-21 00:52:03 +00001292namespace {
John McCallcda666c2010-07-21 07:22:38 +00001293 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +00001294 llvm::Value *ForEHVar;
1295 llvm::Value *EndCatchFn;
1296 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1297 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1298
Craig Topper4f12f102014-03-12 06:41:41 +00001299 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001300 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1301 llvm::BasicBlock *CleanupContBB =
1302 CGF.createBasicBlock("finally.cleanup.cont");
1303
1304 llvm::Value *ShouldEndCatch =
1305 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1306 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1307 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001308 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001309 CGF.EmitBlock(CleanupContBB);
1310 }
1311 };
John McCall906da4b2010-07-21 05:47:49 +00001312
John McCallcda666c2010-07-21 07:22:38 +00001313 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001314 const Stmt *Body;
1315 llvm::Value *ForEHVar;
1316 llvm::Value *EndCatchFn;
1317 llvm::Value *RethrowFn;
1318 llvm::Value *SavedExnVar;
1319
1320 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1321 llvm::Value *EndCatchFn,
1322 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1323 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1324 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1325
Craig Topper4f12f102014-03-12 06:41:41 +00001326 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001327 // Enter a cleanup to call the end-catch function if one was provided.
1328 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001329 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1330 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001331
John McCallcebe0ca2010-08-11 00:16:14 +00001332 // Save the current cleanup destination in case there are
1333 // cleanups in the finally block.
1334 llvm::Value *SavedCleanupDest =
1335 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1336 "cleanup.dest.saved");
1337
John McCall906da4b2010-07-21 05:47:49 +00001338 // Emit the finally block.
1339 CGF.EmitStmt(Body);
1340
1341 // If the end of the finally is reachable, check whether this was
1342 // for EH. If so, rethrow.
1343 if (CGF.HaveInsertPoint()) {
1344 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1345 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1346
1347 llvm::Value *ShouldRethrow =
1348 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1349 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1350
1351 CGF.EmitBlock(RethrowBB);
1352 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001353 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1354 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001355 } else {
John McCall882987f2013-02-28 19:01:20 +00001356 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001357 }
1358 CGF.Builder.CreateUnreachable();
1359
1360 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001361
1362 // Restore the cleanup destination.
1363 CGF.Builder.CreateStore(SavedCleanupDest,
1364 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001365 }
1366
1367 // Leave the end-catch cleanup. As an optimization, pretend that
1368 // the fallthrough path was inaccessible; we've dynamically proven
1369 // that we're not in the EH case along that path.
1370 if (EndCatchFn) {
1371 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1372 CGF.PopCleanupBlock();
1373 CGF.Builder.restoreIP(SavedIP);
1374 }
1375
1376 // Now make sure we actually have an insertion point or the
1377 // cleanup gods will hate us.
1378 CGF.EnsureInsertPoint();
1379 }
1380 };
John McCall1e670402010-07-21 00:52:03 +00001381}
1382
John McCallbd309292010-07-06 01:34:17 +00001383/// Enters a finally block for an implementation using zero-cost
1384/// exceptions. This is mostly general, but hard-codes some
1385/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001386void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1387 const Stmt *body,
1388 llvm::Constant *beginCatchFn,
1389 llvm::Constant *endCatchFn,
1390 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001391 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001392 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001393 assert(rethrowFn && "rethrow function is required");
1394
1395 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001396
John McCallbd309292010-07-06 01:34:17 +00001397 // The rethrow function has one of the following two types:
1398 // void (*)()
1399 // void (*)(void*)
1400 // In the latter case we need to pass it the exception object.
1401 // But we can't use the exception slot because the @finally might
1402 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001403 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001404 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001405 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001406 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001407 if (rethrowFnTy->getNumParams())
1408 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001409
John McCallbd309292010-07-06 01:34:17 +00001410 // A finally block is a statement which must be executed on any edge
1411 // out of a given scope. Unlike a cleanup, the finally block may
1412 // contain arbitrary control flow leading out of itself. In
1413 // addition, finally blocks should always be executed, even if there
1414 // are no catch handlers higher on the stack. Therefore, we
1415 // surround the protected scope with a combination of a normal
1416 // cleanup (to catch attempts to break out of the block via normal
1417 // control flow) and an EH catch-all (semantically "outside" any try
1418 // statement to which the finally block might have been attached).
1419 // The finally block itself is generated in the context of a cleanup
1420 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001421
John McCallbd309292010-07-06 01:34:17 +00001422 // Jump destination for performing the finally block on an exception
1423 // edge. We'll never actually reach this block, so unreachable is
1424 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001425 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001426
John McCallbd309292010-07-06 01:34:17 +00001427 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001428 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1429 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001430
John McCallbd309292010-07-06 01:34:17 +00001431 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001432 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1433 ForEHVar, endCatchFn,
1434 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001435
1436 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001437 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1438 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1439 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001440}
1441
John McCall6b0feb72011-06-22 02:32:12 +00001442void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001443 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001444 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1445 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001446
1447 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001448
John McCall6b0feb72011-06-22 02:32:12 +00001449 // If there are any references to the catch-all block, emit it.
1450 if (catchBB->use_empty()) {
1451 delete catchBB;
1452 } else {
1453 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1454 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001455
Craig Topper8a13c412014-05-21 05:09:00 +00001456 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001457
John McCall6b0feb72011-06-22 02:32:12 +00001458 // If there's a begin-catch function, call it.
1459 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001460 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001461 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001462 }
1463
1464 // If we need to remember the exception pointer to rethrow later, do so.
1465 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001466 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001467 CGF.Builder.CreateStore(exn, SavedExnVar);
1468 }
1469
1470 // Tell the cleanups in the finally block that we're do this for EH.
1471 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1472
1473 // Thread a jump through the finally cleanup.
1474 CGF.EmitBranchThroughCleanup(RethrowDest);
1475
1476 CGF.Builder.restoreIP(savedIP);
1477 }
1478
1479 // Finally, leave the @finally cleanup.
1480 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001481}
1482
John McCalle142ad52013-02-12 03:51:46 +00001483/// In a terminate landing pad, should we use __clang__call_terminate
1484/// or just a naked call to std::terminate?
1485///
1486/// __clang_call_terminate calls __cxa_begin_catch, which then allows
1487/// std::terminate to usefully report something about the
1488/// violating exception.
1489static bool useClangCallTerminate(CodeGenModule &CGM) {
1490 // Only do this for Itanium-family ABIs in C++ mode.
1491 return (CGM.getLangOpts().CPlusPlus &&
1492 CGM.getTarget().getCXXABI().isItaniumFamily());
1493}
1494
1495/// Get or define the following function:
1496/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
1497/// This code is used only in C++.
1498static llvm::Constant *getClangCallTerminateFn(CodeGenModule &CGM) {
1499 llvm::FunctionType *fnTy =
1500 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
1501 llvm::Constant *fnRef =
1502 CGM.CreateRuntimeFunction(fnTy, "__clang_call_terminate");
1503
1504 llvm::Function *fn = dyn_cast<llvm::Function>(fnRef);
1505 if (fn && fn->empty()) {
1506 fn->setDoesNotThrow();
1507 fn->setDoesNotReturn();
1508
1509 // What we really want is to massively penalize inlining without
1510 // forbidding it completely. The difference between that and
1511 // 'noinline' is negligible.
1512 fn->addFnAttr(llvm::Attribute::NoInline);
1513
1514 // Allow this function to be shared across translation units, but
1515 // we don't want it to turn into an exported symbol.
1516 fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
1517 fn->setVisibility(llvm::Function::HiddenVisibility);
1518
1519 // Set up the function.
1520 llvm::BasicBlock *entry =
1521 llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
1522 CGBuilderTy builder(entry);
1523
1524 // Pull the exception pointer out of the parameter list.
1525 llvm::Value *exn = &*fn->arg_begin();
1526
1527 // Call __cxa_begin_catch(exn).
John McCall882987f2013-02-28 19:01:20 +00001528 llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
1529 catchCall->setDoesNotThrow();
1530 catchCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001531
1532 // Call std::terminate().
1533 llvm::CallInst *termCall = builder.CreateCall(getTerminateFn(CGM));
1534 termCall->setDoesNotThrow();
1535 termCall->setDoesNotReturn();
John McCall882987f2013-02-28 19:01:20 +00001536 termCall->setCallingConv(CGM.getRuntimeCC());
John McCalle142ad52013-02-12 03:51:46 +00001537
1538 // std::terminate cannot return.
1539 builder.CreateUnreachable();
1540 }
1541
1542 return fnRef;
1543}
1544
John McCallbd309292010-07-06 01:34:17 +00001545llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1546 if (TerminateLandingPad)
1547 return TerminateLandingPad;
1548
1549 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1550
1551 // This will get inserted at the end of the function.
1552 TerminateLandingPad = createBasicBlock("terminate.lpad");
1553 Builder.SetInsertPoint(TerminateLandingPad);
1554
1555 // Tell the backend that this is a landing pad.
Reid Klecknere070b992014-11-14 02:01:10 +00001556 const EHPersonality &Personality = EHPersonality::get(CGM);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001557 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +00001558 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +00001559 getOpaquePersonalityFn(CGM, Personality), 0);
1560 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001561
John McCalle142ad52013-02-12 03:51:46 +00001562 llvm::CallInst *terminateCall;
1563 if (useClangCallTerminate(CGM)) {
1564 // Extract out the exception pointer.
1565 llvm::Value *exn = Builder.CreateExtractValue(LPadInst, 0);
John McCall882987f2013-02-28 19:01:20 +00001566 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
John McCalle142ad52013-02-12 03:51:46 +00001567 } else {
John McCall882987f2013-02-28 19:01:20 +00001568 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
John McCalle142ad52013-02-12 03:51:46 +00001569 }
1570 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001571 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001572
John McCallbd309292010-07-06 01:34:17 +00001573 // Restore the saved insertion state.
1574 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001575
John McCallbd309292010-07-06 01:34:17 +00001576 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001577}
Mike Stump2b488872009-12-09 22:59:31 +00001578
1579llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001580 if (TerminateHandler)
1581 return TerminateHandler;
1582
John McCallbd309292010-07-06 01:34:17 +00001583 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001584
John McCallbd309292010-07-06 01:34:17 +00001585 // Set up the terminate handler. This block is inserted at the very
1586 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001587 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001588 Builder.SetInsertPoint(TerminateHandler);
John McCallc84e4e92013-06-20 21:37:43 +00001589 llvm::CallInst *terminateCall;
1590 if (useClangCallTerminate(CGM)) {
1591 // Load the exception pointer.
1592 llvm::Value *exn = getExceptionFromSlot();
1593 terminateCall = EmitNounwindRuntimeCall(getClangCallTerminateFn(CGM), exn);
1594 } else {
1595 terminateCall = EmitNounwindRuntimeCall(getTerminateFn(CGM));
1596 }
1597 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001598 Builder.CreateUnreachable();
1599
John McCall21886962010-04-21 10:05:39 +00001600 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001601 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001602
Mike Stump2b488872009-12-09 22:59:31 +00001603 return TerminateHandler;
1604}
John McCallbd309292010-07-06 01:34:17 +00001605
David Chisnall9a837be2012-11-07 16:50:40 +00001606llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001607 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001608
1609 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1610
1611 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001612 EHResumeBlock = createBasicBlock("eh.resume");
1613 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001614
Reid Klecknere070b992014-11-14 02:01:10 +00001615 const EHPersonality &Personality = EHPersonality::get(CGM);
John McCallad5d61e2010-07-23 21:56:41 +00001616
1617 // This can always be a call because we necessarily didn't find
1618 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001619 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001620 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001621 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001622 getExceptionFromSlot())
John McCall9b382dd2011-05-28 21:13:02 +00001623 ->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001624 Builder.CreateUnreachable();
1625 Builder.restoreIP(SavedIP);
1626 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001627 }
1628
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001629 // Recreate the landingpad's return value for the 'resume' instruction.
1630 llvm::Value *Exn = getExceptionFromSlot();
1631 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001632
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001633 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001634 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001635 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1636 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1637 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1638
1639 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001640 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001641 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001642}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001643
1644void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
1645 CGM.ErrorUnsupported(&S, "SEH __try");
1646}
Nico Weber9b982072014-07-07 00:12:30 +00001647
1648void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
1649 CGM.ErrorUnsupported(&S, "SEH __leave");
1650}