blob: 1925c57d1bdbad3fe70b251b4328adcccc5b2cc9 [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"
David Majnemer442d0a22014-11-25 07:20:20 +000015#include "CGCXXABI.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000016#include "CGCleanup.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000017#include "CGObjCRuntime.h"
John McCall5add20c2010-07-20 22:17:55 +000018#include "TargetInfo.h"
Reid Kleckner1d59f992015-01-22 01:36:17 +000019#include "clang/AST/Mangle.h"
Benjamin Kramer793bd552012-02-08 12:41:24 +000020#include "clang/AST/StmtCXX.h"
Chandler Carruth4b417452013-01-19 08:09:44 +000021#include "clang/AST/StmtObjC.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000022#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/Intrinsics.h"
John McCallbd309292010-07-06 01:34:17 +000024
Anders Carlsson4b08db72009-10-30 01:42:31 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall2c33ba82013-02-12 03:51:38 +000028static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
Mike Stump33270212009-12-02 07:41:41 +000029 // void __cxa_free_exception(void *thrown_exception);
Mike Stump75546b82009-12-10 00:06:18 +000030
Chris Lattner2192fe52011-07-18 04:24:23 +000031 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000032 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000033
John McCall2c33ba82013-02-12 03:51:38 +000034 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
Mike Stump33270212009-12-02 07:41:41 +000035}
36
John McCall2c33ba82013-02-12 03:51:38 +000037static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
Richard Smith2f7aa192013-06-20 23:03:35 +000038 // void __cxa_call_unexpected(void *thrown_exception);
Mike Stump1d849212009-12-07 23:38:24 +000039
Chris Lattner2192fe52011-07-18 04:24:23 +000040 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000041 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000042
John McCall2c33ba82013-02-12 03:51:38 +000043 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
Mike Stump1d849212009-12-07 23:38:24 +000044}
45
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000046llvm::Constant *CodeGenModule::getTerminateFn() {
Mike Stump33270212009-12-02 07:41:41 +000047 // void __terminate();
48
Chris Lattner2192fe52011-07-18 04:24:23 +000049 llvm::FunctionType *FTy =
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000050 llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
Mike Stump75546b82009-12-10 00:06:18 +000051
Chris Lattner0e62c1c2011-07-23 10:55:15 +000052 StringRef name;
John McCall9de19782011-07-06 01:22:26 +000053
54 // In C++, use std::terminate().
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000055 if (getLangOpts().CPlusPlus &&
56 getTarget().getCXXABI().isItaniumFamily()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +000057 name = "_ZSt9terminatev";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000058 } else if (getLangOpts().CPlusPlus &&
59 getTarget().getCXXABI().isMicrosoft()) {
David Majnemerdbdab402015-02-25 23:01:21 +000060 name = "\01?terminate@@YAXXZ";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000061 } else if (getLangOpts().ObjC1 &&
62 getLangOpts().ObjCRuntime.hasTerminate())
John McCall9de19782011-07-06 01:22:26 +000063 name = "objc_terminate";
64 else
65 name = "abort";
Reid Klecknerfff8e7f2015-03-03 19:21:04 +000066 return CreateRuntimeFunction(FTy, name);
David Chisnallf9c42252010-05-17 13:49:20 +000067}
68
John McCall2c33ba82013-02-12 03:51:38 +000069static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 StringRef Name) {
Chris Lattner2192fe52011-07-18 04:24:23 +000071 llvm::FunctionType *FTy =
John McCall2c33ba82013-02-12 03:51:38 +000072 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
John McCall36ea3722010-07-17 00:43:08 +000073
John McCall2c33ba82013-02-12 03:51:38 +000074 return CGM.CreateRuntimeFunction(FTy, Name);
John McCallbd309292010-07-06 01:34:17 +000075}
76
Benjamin Kramer793bd552012-02-08 12:41:24 +000077namespace {
78 /// The exceptions personality for a function.
79 struct EHPersonality {
80 const char *PersonalityFn;
81
82 // If this is non-null, this personality requires a non-standard
83 // function for rethrowing an exception after a catchall cleanup.
84 // This function must have prototype void(void*).
85 const char *CatchallRethrowFn;
86
Reid Klecknerdeeddec2015-02-05 18:56:03 +000087 static const EHPersonality &get(CodeGenModule &CGM,
88 const FunctionDecl *FD);
89 static const EHPersonality &get(CodeGenFunction &CGF) {
90 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(CGF.CurCodeDecl));
91 }
92
Benjamin Kramer793bd552012-02-08 12:41:24 +000093 static const EHPersonality GNU_C;
94 static const EHPersonality GNU_C_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +000095 static const EHPersonality GNU_C_SEH;
Benjamin Kramer793bd552012-02-08 12:41:24 +000096 static const EHPersonality GNU_ObjC;
David Chisnall2ec1b10d2013-01-11 15:33:01 +000097 static const EHPersonality GNUstep_ObjC;
Benjamin Kramer793bd552012-02-08 12:41:24 +000098 static const EHPersonality GNU_ObjCXX;
99 static const EHPersonality NeXT_ObjC;
100 static const EHPersonality GNU_CPlusPlus;
101 static const EHPersonality GNU_CPlusPlus_SJLJ;
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000102 static const EHPersonality GNU_CPlusPlus_SEH;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000103 static const EHPersonality MSVC_except_handler;
104 static const EHPersonality MSVC_C_specific_handler;
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000105 static const EHPersonality MSVC_CxxFrameHandler3;
Benjamin Kramer793bd552012-02-08 12:41:24 +0000106 };
107}
108
Craig Topper8a13c412014-05-21 05:09:00 +0000109const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000110const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000111EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
112const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000113EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
114const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000115EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
116const EHPersonality
117EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
118const EHPersonality
119EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
Benjamin Kramer793bd552012-02-08 12:41:24 +0000120const EHPersonality
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000121EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
122const EHPersonality
Benjamin Kramer793bd552012-02-08 12:41:24 +0000123EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
124const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000125EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000126const EHPersonality
Craig Topper8a13c412014-05-21 05:09:00 +0000127EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
Reid Kleckner1d59f992015-01-22 01:36:17 +0000128const EHPersonality
129EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
130const EHPersonality
131EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000132const EHPersonality
133EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
John McCall36ea3722010-07-17 00:43:08 +0000134
Reid Klecknere070b992014-11-14 02:01:10 +0000135/// On Win64, use libgcc's SEH personality function. We fall back to dwarf on
136/// other platforms, unless the user asked for SjLj exceptions.
137static bool useLibGCCSEHPersonality(const llvm::Triple &T) {
138 return T.isOSWindows() && T.getArch() == llvm::Triple::x86_64;
139}
140
141static const EHPersonality &getCPersonality(const llvm::Triple &T,
142 const LangOptions &L) {
John McCall2faab302010-11-07 02:35:25 +0000143 if (L.SjLjExceptions)
144 return EHPersonality::GNU_C_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000145 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000146 return EHPersonality::GNU_C_SEH;
John McCall36ea3722010-07-17 00:43:08 +0000147 return EHPersonality::GNU_C;
148}
149
Reid Klecknere070b992014-11-14 02:01:10 +0000150static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
151 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000152 switch (L.ObjCRuntime.getKind()) {
153 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000154 return getCPersonality(T, L);
John McCall5fb5df92012-06-20 06:18:46 +0000155 case ObjCRuntime::MacOSX:
156 case ObjCRuntime::iOS:
157 return EHPersonality::NeXT_ObjC;
David Chisnallb601c962012-07-03 20:49:52 +0000158 case ObjCRuntime::GNUstep:
David Chisnall2ec1b10d2013-01-11 15:33:01 +0000159 if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
160 return EHPersonality::GNUstep_ObjC;
161 // fallthrough
David Chisnallb601c962012-07-03 20:49:52 +0000162 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000163 case ObjCRuntime::ObjFW:
John McCall36ea3722010-07-17 00:43:08 +0000164 return EHPersonality::GNU_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000165 }
John McCall5fb5df92012-06-20 06:18:46 +0000166 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000167}
168
Reid Klecknere070b992014-11-14 02:01:10 +0000169static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
170 const LangOptions &L) {
John McCall36ea3722010-07-17 00:43:08 +0000171 if (L.SjLjExceptions)
172 return EHPersonality::GNU_CPlusPlus_SJLJ;
Reid Klecknere070b992014-11-14 02:01:10 +0000173 else if (useLibGCCSEHPersonality(T))
Reid Kleckner8f45c9c2014-09-15 17:19:16 +0000174 return EHPersonality::GNU_CPlusPlus_SEH;
Reid Klecknere070b992014-11-14 02:01:10 +0000175 return EHPersonality::GNU_CPlusPlus;
John McCallbd309292010-07-06 01:34:17 +0000176}
177
178/// Determines the personality function to use when both C++
179/// and Objective-C exceptions are being caught.
Reid Klecknere070b992014-11-14 02:01:10 +0000180static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
181 const LangOptions &L) {
John McCall5fb5df92012-06-20 06:18:46 +0000182 switch (L.ObjCRuntime.getKind()) {
John McCallbd309292010-07-06 01:34:17 +0000183 // The ObjC personality defers to the C++ personality for non-ObjC
184 // handlers. Unlike the C++ case, we use the same personality
185 // function on targets using (backend-driven) SJLJ EH.
John McCall5fb5df92012-06-20 06:18:46 +0000186 case ObjCRuntime::MacOSX:
187 case ObjCRuntime::iOS:
188 return EHPersonality::NeXT_ObjC;
John McCallbd309292010-07-06 01:34:17 +0000189
John McCall5fb5df92012-06-20 06:18:46 +0000190 // In the fragile ABI, just use C++ exception handling and hope
191 // they're not doing crazy exception mixing.
192 case ObjCRuntime::FragileMacOSX:
Reid Klecknere070b992014-11-14 02:01:10 +0000193 return getCXXPersonality(T, L);
David Chisnallf9c42252010-05-17 13:49:20 +0000194
David Chisnallb601c962012-07-03 20:49:52 +0000195 // The GCC runtime's personality function inherently doesn't support
John McCall36ea3722010-07-17 00:43:08 +0000196 // mixed EH. Use the C++ personality just to avoid returning null.
David Chisnallb601c962012-07-03 20:49:52 +0000197 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000198 case ObjCRuntime::ObjFW: // XXX: this will change soon
David Chisnallb601c962012-07-03 20:49:52 +0000199 return EHPersonality::GNU_ObjC;
200 case ObjCRuntime::GNUstep:
John McCall5fb5df92012-06-20 06:18:46 +0000201 return EHPersonality::GNU_ObjCXX;
202 }
203 llvm_unreachable("bad runtime kind");
John McCallbd309292010-07-06 01:34:17 +0000204}
205
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000206static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
Reid Kleckner1d59f992015-01-22 01:36:17 +0000207 if (T.getArch() == llvm::Triple::x86)
208 return EHPersonality::MSVC_except_handler;
209 return EHPersonality::MSVC_C_specific_handler;
210}
211
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000212const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
213 const FunctionDecl *FD) {
Reid Klecknere070b992014-11-14 02:01:10 +0000214 const llvm::Triple &T = CGM.getTarget().getTriple();
215 const LangOptions &L = CGM.getLangOpts();
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000216
Reid Kleckner1d59f992015-01-22 01:36:17 +0000217 // Try to pick a personality function that is compatible with MSVC if we're
218 // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
219 // the GCC-style personality function.
220 if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000221 if (L.SjLjExceptions)
222 return EHPersonality::GNU_CPlusPlus_SJLJ;
223 else if (FD && FD->usesSEHTry())
224 return getSEHPersonalityMSVC(T);
Reid Kleckner1d59f992015-01-22 01:36:17 +0000225 else
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000226 return EHPersonality::MSVC_CxxFrameHandler3;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000227 }
228
John McCall36ea3722010-07-17 00:43:08 +0000229 if (L.CPlusPlus && L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000230 return getObjCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000231 else if (L.CPlusPlus)
Reid Klecknere070b992014-11-14 02:01:10 +0000232 return getCXXPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000233 else if (L.ObjC1)
Reid Klecknere070b992014-11-14 02:01:10 +0000234 return getObjCPersonality(T, L);
John McCallbd309292010-07-06 01:34:17 +0000235 else
Reid Klecknere070b992014-11-14 02:01:10 +0000236 return getCPersonality(T, L);
John McCall36ea3722010-07-17 00:43:08 +0000237}
John McCallbd309292010-07-06 01:34:17 +0000238
John McCall0bdb1fd2010-09-16 06:16:50 +0000239static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
John McCall36ea3722010-07-17 00:43:08 +0000240 const EHPersonality &Personality) {
John McCall36ea3722010-07-17 00:43:08 +0000241 llvm::Constant *Fn =
Chris Lattnerece04092012-02-07 00:39:47 +0000242 CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Benjamin Kramer793bd552012-02-08 12:41:24 +0000243 Personality.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000244 return Fn;
245}
246
247static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
248 const EHPersonality &Personality) {
249 llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
John McCallad7c5c12011-02-08 08:22:06 +0000250 return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
John McCall0bdb1fd2010-09-16 06:16:50 +0000251}
252
253/// Check whether a personality function could reasonably be swapped
254/// for a C++ personality function.
255static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000256 for (llvm::User *U : Fn->users()) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000257 // Conditionally white-list bitcasts.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000258 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000259 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
260 if (!PersonalityHasOnlyCXXUses(CE))
261 return false;
262 continue;
263 }
264
Bill Wendling58e58fe2011-09-19 22:08:36 +0000265 // Otherwise, it has to be a landingpad instruction.
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000266 llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(U);
Bill Wendling58e58fe2011-09-19 22:08:36 +0000267 if (!LPI) return false;
John McCall0bdb1fd2010-09-16 06:16:50 +0000268
Bill Wendling58e58fe2011-09-19 22:08:36 +0000269 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
John McCall0bdb1fd2010-09-16 06:16:50 +0000270 // Look for something that would've been returned by the ObjC
271 // runtime's GetEHType() method.
Bill Wendling58e58fe2011-09-19 22:08:36 +0000272 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
273 if (LPI->isCatch(I)) {
274 // Check if the catch value has the ObjC prefix.
Bill Wendling5d7469e2011-09-20 00:40:19 +0000275 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
276 // ObjC EH selector entries are always global variables with
277 // names starting like this.
278 if (GV->getName().startswith("OBJC_EHTYPE"))
279 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000280 } else {
281 // Check if any of the filter values have the ObjC prefix.
282 llvm::Constant *CVal = cast<llvm::Constant>(Val);
283 for (llvm::User::op_iterator
284 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
Bill Wendling5d7469e2011-09-20 00:40:19 +0000285 if (llvm::GlobalVariable *GV =
286 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
287 // ObjC EH selector entries are always global variables with
288 // names starting like this.
289 if (GV->getName().startswith("OBJC_EHTYPE"))
290 return false;
Bill Wendling58e58fe2011-09-19 22:08:36 +0000291 }
292 }
John McCall0bdb1fd2010-09-16 06:16:50 +0000293 }
294 }
295
296 return true;
297}
298
299/// Try to use the C++ personality function in ObjC++. Not doing this
300/// can cause some incompatibilities with gcc, which is more
301/// aggressive about only using the ObjC++ personality in a function
302/// when it really needs it.
303void CodeGenModule::SimplifyPersonality() {
John McCall0bdb1fd2010-09-16 06:16:50 +0000304 // If we're not in ObjC++ -fexceptions, there's nothing to do.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000305 if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
John McCall0bdb1fd2010-09-16 06:16:50 +0000306 return;
307
John McCall3c223932012-11-14 17:48:31 +0000308 // Both the problem this endeavors to fix and the way the logic
309 // above works is specific to the NeXT runtime.
310 if (!LangOpts.ObjCRuntime.isNeXTFamily())
311 return;
312
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000313 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
Reid Klecknere070b992014-11-14 02:01:10 +0000314 const EHPersonality &CXX =
315 getCXXPersonality(getTarget().getTriple(), LangOpts);
Benjamin Kramer793bd552012-02-08 12:41:24 +0000316 if (&ObjCXX == &CXX)
John McCall0bdb1fd2010-09-16 06:16:50 +0000317 return;
318
Benjamin Kramer793bd552012-02-08 12:41:24 +0000319 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
320 "Different EHPersonalities using the same personality function.");
321
322 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
John McCall0bdb1fd2010-09-16 06:16:50 +0000323
324 // Nothing to do if it's unused.
325 if (!Fn || Fn->use_empty()) return;
326
327 // Can't do the optimization if it has non-C++ uses.
328 if (!PersonalityHasOnlyCXXUses(Fn)) return;
329
330 // Create the C++ personality function and kill off the old
331 // function.
332 llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
333
334 // This can happen if the user is screwing with us.
335 if (Fn->getType() != CXXFn->getType()) return;
336
337 Fn->replaceAllUsesWith(CXXFn);
338 Fn->eraseFromParent();
John McCallbd309292010-07-06 01:34:17 +0000339}
340
341/// Returns the value to inject into a selector to indicate the
342/// presence of a catch-all.
343static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
344 // Possibly we should use @llvm.eh.catch.all.value here.
John McCallad7c5c12011-02-08 08:22:06 +0000345 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
John McCallbd309292010-07-06 01:34:17 +0000346}
347
John McCallbb026012010-07-13 21:17:51 +0000348namespace {
349 /// A cleanup to free the exception object if its initialization
350 /// throws.
John McCall5fcf8da2011-07-12 00:15:30 +0000351 struct FreeException : EHScopeStack::Cleanup {
352 llvm::Value *exn;
353 FreeException(llvm::Value *exn) : exn(exn) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000354 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall882987f2013-02-28 19:01:20 +0000355 CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
John McCallbb026012010-07-13 21:17:51 +0000356 }
357 };
358}
359
John McCall2e6567a2010-04-22 01:10:34 +0000360// Emits an exception expression into the given location. This
361// differs from EmitAnyExprToMem only in that, if a final copy-ctor
362// call is required, an exception within that copy ctor causes
363// std::terminate to be invoked.
David Majnemer7c237072015-03-05 00:46:22 +0000364void CodeGenFunction::EmitAnyExprToExn(const Expr *e, llvm::Value *addr) {
John McCallbd309292010-07-06 01:34:17 +0000365 // Make sure the exception object is cleaned up if there's an
366 // exception during initialization.
David Majnemer7c237072015-03-05 00:46:22 +0000367 pushFullExprCleanup<FreeException>(EHCleanup, addr);
368 EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
John McCall2e6567a2010-04-22 01:10:34 +0000369
370 // __cxa_allocate_exception returns a void*; we need to cast this
371 // to the appropriate type for the object.
David Majnemer7c237072015-03-05 00:46:22 +0000372 llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
373 llvm::Value *typedAddr = Builder.CreateBitCast(addr, ty);
John McCall2e6567a2010-04-22 01:10:34 +0000374
375 // FIXME: this isn't quite right! If there's a final unelided call
376 // to a copy constructor, then according to [except.terminate]p1 we
377 // must call std::terminate() if that constructor throws, because
378 // technically that copy occurs after the exception expression is
379 // evaluated but before the exception is caught. But the best way
380 // to handle that is to teach EmitAggExpr to do the final copy
381 // differently if it can't be elided.
David Majnemer7c237072015-03-05 00:46:22 +0000382 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
383 /*IsInit*/ true);
John McCall2e6567a2010-04-22 01:10:34 +0000384
John McCalle4df6c82011-01-28 08:37:24 +0000385 // Deactivate the cleanup block.
David Majnemer7c237072015-03-05 00:46:22 +0000386 DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
Mike Stump54066142009-12-01 03:41:18 +0000387}
388
John McCallbd309292010-07-06 01:34:17 +0000389llvm::Value *CodeGenFunction::getExceptionSlot() {
John McCall9b382dd2011-05-28 21:13:02 +0000390 if (!ExceptionSlot)
391 ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
John McCallbd309292010-07-06 01:34:17 +0000392 return ExceptionSlot;
Mike Stump54066142009-12-01 03:41:18 +0000393}
394
John McCall9b382dd2011-05-28 21:13:02 +0000395llvm::Value *CodeGenFunction::getEHSelectorSlot() {
396 if (!EHSelectorSlot)
397 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
398 return EHSelectorSlot;
399}
400
Bill Wendling79a70e42011-09-15 18:57:19 +0000401llvm::Value *CodeGenFunction::getExceptionFromSlot() {
402 return Builder.CreateLoad(getExceptionSlot(), "exn");
403}
404
405llvm::Value *CodeGenFunction::getSelectorFromSlot() {
406 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
407}
408
Reid Kleckneraca01db2015-02-04 22:37:07 +0000409llvm::Value *CodeGenFunction::getAbnormalTerminationSlot() {
410 if (!AbnormalTerminationSlot)
Nico Weber1bebad12015-02-11 22:33:32 +0000411 AbnormalTerminationSlot =
412 CreateTempAlloca(Int8Ty, "abnormal.termination.slot");
Reid Kleckneraca01db2015-02-04 22:37:07 +0000413 return AbnormalTerminationSlot;
414}
415
Richard Smithea852322013-05-07 21:53:22 +0000416void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
417 bool KeepInsertionPoint) {
David Majnemer7c237072015-03-05 00:46:22 +0000418 if (const Expr *SubExpr = E->getSubExpr()) {
419 QualType ThrowType = SubExpr->getType();
420 if (ThrowType->isObjCObjectPointerType()) {
421 const Stmt *ThrowStmt = E->getSubExpr();
422 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
423 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
424 } else {
425 CGM.getCXXABI().emitThrow(*this, E);
John McCall2e6567a2010-04-22 01:10:34 +0000426 }
David Majnemer7c237072015-03-05 00:46:22 +0000427 } else {
428 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
John McCall2e6567a2010-04-22 01:10:34 +0000429 }
Mike Stump75546b82009-12-10 00:06:18 +0000430
John McCall20f6ab82011-01-12 03:41:02 +0000431 // throw is an expression, and the expression emitters expect us
432 // to leave ourselves at a valid insertion point.
Richard Smithea852322013-05-07 21:53:22 +0000433 if (KeepInsertionPoint)
434 EmitBlock(createBasicBlock("throw.cont"));
Anders Carlsson4b08db72009-10-30 01:42:31 +0000435}
Mike Stump58ef18b2009-11-20 23:44:51 +0000436
Mike Stump1d849212009-12-07 23:38:24 +0000437void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000438 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000439 return;
440
Mike Stump1d849212009-12-07 23:38:24 +0000441 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000442 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000443 // Check if CapturedDecl is nothrow and create terminate scope for it.
444 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
445 if (CD->isNothrow())
446 EHStack.pushTerminate();
447 }
Mike Stump1d849212009-12-07 23:38:24 +0000448 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000449 }
Mike Stump1d849212009-12-07 23:38:24 +0000450 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000451 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000452 return;
453
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000454 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
455 if (isNoexceptExceptionSpec(EST)) {
456 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
457 // noexcept functions are simple terminate scopes.
458 EHStack.pushTerminate();
459 }
460 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
461 unsigned NumExceptions = Proto->getNumExceptions();
462 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000463
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000464 for (unsigned I = 0; I != NumExceptions; ++I) {
465 QualType Ty = Proto->getExceptionType(I);
466 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
467 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
468 /*ForEH=*/true);
469 Filter->setFilter(I, EHType);
470 }
Mike Stump1d849212009-12-07 23:38:24 +0000471 }
Mike Stump1d849212009-12-07 23:38:24 +0000472}
473
John McCall8e4c74b2011-08-11 02:22:43 +0000474/// Emit the dispatch block for a filter scope if necessary.
475static void emitFilterDispatchBlock(CodeGenFunction &CGF,
476 EHFilterScope &filterScope) {
477 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
478 if (!dispatchBlock) return;
479 if (dispatchBlock->use_empty()) {
480 delete dispatchBlock;
481 return;
482 }
483
John McCall8e4c74b2011-08-11 02:22:43 +0000484 CGF.EmitBlockAfterUses(dispatchBlock);
485
486 // If this isn't a catch-all filter, we need to check whether we got
487 // here because the filter triggered.
488 if (filterScope.getNumFilters()) {
489 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000490 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000491 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
492
493 llvm::Value *zero = CGF.Builder.getInt32(0);
494 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000495 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
496 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
497 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000498
499 CGF.EmitBlock(unexpectedBB);
500 }
501
502 // Call __cxa_call_unexpected. This doesn't need to be an invoke
503 // because __cxa_call_unexpected magically filters exceptions
504 // according to the last landing pad the exception was thrown
505 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000506 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000507 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000508 ->setDoesNotReturn();
509 CGF.Builder.CreateUnreachable();
510}
511
Mike Stump1d849212009-12-07 23:38:24 +0000512void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000514 return;
515
Mike Stump1d849212009-12-07 23:38:24 +0000516 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000517 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000518 // Check if CapturedDecl is nothrow and pop terminate scope for it.
519 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
520 if (CD->isNothrow())
521 EHStack.popTerminate();
522 }
Mike Stump1d849212009-12-07 23:38:24 +0000523 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000524 }
Mike Stump1d849212009-12-07 23:38:24 +0000525 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000526 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000527 return;
528
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000529 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
530 if (isNoexceptExceptionSpec(EST)) {
531 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
532 EHStack.popTerminate();
533 }
534 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
John McCall8e4c74b2011-08-11 02:22:43 +0000535 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
536 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000537 EHStack.popFilter();
538 }
Mike Stump1d849212009-12-07 23:38:24 +0000539}
540
Mike Stump58ef18b2009-11-20 23:44:51 +0000541void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000542 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000543 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000544 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000545}
546
John McCallb609d3f2010-07-07 06:56:46 +0000547void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000548 unsigned NumHandlers = S.getNumHandlers();
549 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000550
John McCallbd309292010-07-06 01:34:17 +0000551 for (unsigned I = 0; I != NumHandlers; ++I) {
552 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000553
John McCallbd309292010-07-06 01:34:17 +0000554 llvm::BasicBlock *Handler = createBasicBlock("catch");
555 if (C->getExceptionDecl()) {
556 // FIXME: Dropping the reference type on the type into makes it
557 // impossible to correctly implement catch-by-reference
558 // semantics for pointers. Unfortunately, this is what all
559 // existing compilers do, and it's not clear that the standard
560 // personality routine is capable of doing this right. See C++ DR 388:
561 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000562 Qualifiers CaughtTypeQuals;
563 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
564 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000565
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000566 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000567 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000568 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000569 else
David Majnemer5f0dd612015-03-17 20:35:05 +0000570 TypeInfo =
David Majnemer37b417f2015-03-29 21:55:10 +0000571 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000572 CatchScope->setHandler(I, TypeInfo, Handler);
573 } else {
574 // No exception decl indicates '...', a catch-all.
575 CatchScope->setCatchAllHandler(I, Handler);
576 }
577 }
John McCallbd309292010-07-06 01:34:17 +0000578}
579
John McCall8e4c74b2011-08-11 02:22:43 +0000580llvm::BasicBlock *
581CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
582 // The dispatch block for the end of the scope chain is a block that
583 // just resumes unwinding.
584 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000585 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000586
587 // Otherwise, we should look at the actual scope.
588 EHScope &scope = *EHStack.find(si);
589
590 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
591 if (!dispatchBlock) {
592 switch (scope.getKind()) {
593 case EHScope::Catch: {
594 // Apply a special case to a single catch-all.
595 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
596 if (catchScope.getNumHandlers() == 1 &&
597 catchScope.getHandler(0).isCatchAll()) {
598 dispatchBlock = catchScope.getHandler(0).Block;
599
600 // Otherwise, make a dispatch block.
601 } else {
602 dispatchBlock = createBasicBlock("catch.dispatch");
603 }
604 break;
605 }
606
607 case EHScope::Cleanup:
608 dispatchBlock = createBasicBlock("ehcleanup");
609 break;
610
611 case EHScope::Filter:
612 dispatchBlock = createBasicBlock("filter.dispatch");
613 break;
614
615 case EHScope::Terminate:
616 dispatchBlock = getTerminateHandler();
617 break;
618 }
619 scope.setCachedEHDispatchBlock(dispatchBlock);
620 }
621 return dispatchBlock;
622}
623
John McCallbd309292010-07-06 01:34:17 +0000624/// Check whether this is a non-EH scope, i.e. a scope which doesn't
625/// affect exception handling. Currently, the only non-EH scopes are
626/// normal-only cleanup scopes.
627static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000628 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000629 case EHScope::Cleanup:
630 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000631 case EHScope::Filter:
632 case EHScope::Catch:
633 case EHScope::Terminate:
634 return false;
635 }
636
David Blaikiee4d798f2012-01-20 21:50:17 +0000637 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000638}
639
640llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
641 assert(EHStack.requiresLandingPad());
642 assert(!EHStack.empty());
643
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000644 // If exceptions are disabled, there are usually no landingpads. However, when
645 // SEH is enabled, functions using SEH still get landingpads.
646 const LangOptions &LO = CGM.getLangOpts();
647 if (!LO.Exceptions) {
648 if (!LO.Borland && !LO.MicrosoftExt)
649 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000650 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000651 return nullptr;
652 }
John McCall2b7fc382010-07-13 20:32:21 +0000653
John McCallbd309292010-07-06 01:34:17 +0000654 // Check the innermost scope for a cached landing pad. If this is
655 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
656 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
657 if (LP) return LP;
658
659 // Build the landing pad for this scope.
660 LP = EmitLandingPad();
661 assert(LP);
662
663 // Cache the landing pad on the innermost scope. If this is a
664 // non-EH scope, cache the landing pad on the enclosing scope, too.
665 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
666 ir->setCachedLandingPad(LP);
667 if (!isNonEHScope(*ir)) break;
668 }
669
670 return LP;
671}
672
673llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
674 assert(EHStack.requiresLandingPad());
675
John McCall8e4c74b2011-08-11 02:22:43 +0000676 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
677 switch (innermostEHScope.getKind()) {
678 case EHScope::Terminate:
679 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000680
John McCall8e4c74b2011-08-11 02:22:43 +0000681 case EHScope::Catch:
682 case EHScope::Cleanup:
683 case EHScope::Filter:
684 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
685 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000686 }
687
688 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000689 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000690 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000691
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000692 const EHPersonality &personality = EHPersonality::get(*this);
John McCall36ea3722010-07-17 00:43:08 +0000693
John McCallbd309292010-07-06 01:34:17 +0000694 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000695 llvm::BasicBlock *lpad = createBasicBlock("lpad");
696 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000697
Bill Wendlingf0724e82011-09-19 20:31:14 +0000698 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000699 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +0000700 getOpaquePersonalityFn(CGM, personality), 0);
701
702 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
703 Builder.CreateStore(LPadExn, getExceptionSlot());
704 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
705 Builder.CreateStore(LPadSel, getEHSelectorSlot());
706
John McCallbd309292010-07-06 01:34:17 +0000707 // Save the exception pointer. It's safe to use a single exception
708 // pointer per function because EH cleanups can never have nested
709 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000710 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000711
712 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000713 bool hasCatchAll = false;
714 bool hasCleanup = false;
715 bool hasFilter = false;
716 SmallVector<llvm::Value*, 4> filterTypes;
717 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000718 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
719 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000720
721 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000722 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000723 // If we have a cleanup, remember that.
724 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000725 continue;
726
John McCallbd309292010-07-06 01:34:17 +0000727 case EHScope::Filter: {
728 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000729 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000730
Bill Wendlingf0724e82011-09-19 20:31:14 +0000731 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000732 EHFilterScope &filter = cast<EHFilterScope>(*I);
733 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000734
Bill Wendling8c4b7162011-09-22 20:32:54 +0000735 // Add all the filter values.
736 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
737 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000738 goto done;
739 }
740
741 case EHScope::Terminate:
742 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000743 assert(!hasCatchAll);
744 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000745 goto done;
746
747 case EHScope::Catch:
748 break;
749 }
750
John McCall8e4c74b2011-08-11 02:22:43 +0000751 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
752 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
753 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000754
John McCall8e4c74b2011-08-11 02:22:43 +0000755 // If this is a catch-all, register that and abort.
756 if (!handler.Type) {
757 assert(!hasCatchAll);
758 hasCatchAll = true;
759 goto done;
John McCallbd309292010-07-06 01:34:17 +0000760 }
761
762 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000763 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000764 // If not, add it directly to the landingpad.
765 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000766 }
John McCallbd309292010-07-06 01:34:17 +0000767 }
768
769 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000770 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000771 assert(!(hasCatchAll && hasFilter));
772 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000773 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000774
775 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000776 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000777 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000778 // Create a filter expression: a constant array indicating which filter
779 // types there are. The personality routine only lands here if the filter
780 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000781 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000782 llvm::ArrayType *AType =
783 llvm::ArrayType::get(!filterTypes.empty() ?
784 filterTypes[0]->getType() : Int8PtrTy,
785 filterTypes.size());
786
787 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
788 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
789 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
790 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000791
792 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000793 if (hasCleanup)
794 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000795
796 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000797 } else if (hasCleanup) {
798 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000799 }
800
Bill Wendlingf0724e82011-09-19 20:31:14 +0000801 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
802 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000803
804 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000805 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000806
807 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000808 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000809
John McCall8e4c74b2011-08-11 02:22:43 +0000810 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000811}
812
John McCall8e4c74b2011-08-11 02:22:43 +0000813/// Emit the structure of the dispatch block for the given catch scope.
814/// It is an invariant that the dispatch block already exists.
815static void emitCatchDispatchBlock(CodeGenFunction &CGF,
816 EHCatchScope &catchScope) {
817 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
818 assert(dispatchBlock);
819
820 // If there's only a single catch-all, getEHDispatchBlock returned
821 // that catch-all as the dispatch block.
822 if (catchScope.getNumHandlers() == 1 &&
823 catchScope.getHandler(0).isCatchAll()) {
824 assert(dispatchBlock == catchScope.getHandler(0).Block);
825 return;
826 }
827
828 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
829 CGF.EmitBlockAfterUses(dispatchBlock);
830
831 // Select the right handler.
832 llvm::Value *llvm_eh_typeid_for =
833 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
834
835 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000836 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000837
838 // Test against each of the exception types we claim to catch.
839 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
840 assert(i < e && "ran off end of handlers!");
841 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
842
843 llvm::Value *typeValue = handler.Type;
844 assert(typeValue && "fell into catch-all case!");
845 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
846
847 // Figure out the next block.
848 bool nextIsEnd;
849 llvm::BasicBlock *nextBlock;
850
851 // If this is the last handler, we're at the end, and the next
852 // block is the block for the enclosing EH scope.
853 if (i + 1 == e) {
854 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
855 nextIsEnd = true;
856
857 // If the next handler is a catch-all, we're at the end, and the
858 // next block is that handler.
859 } else if (catchScope.getHandler(i+1).isCatchAll()) {
860 nextBlock = catchScope.getHandler(i+1).Block;
861 nextIsEnd = true;
862
863 // Otherwise, we're not at the end and we need a new block.
864 } else {
865 nextBlock = CGF.createBasicBlock("catch.fallthrough");
866 nextIsEnd = false;
867 }
868
869 // Figure out the catch type's index in the LSDA's type table.
870 llvm::CallInst *typeIndex =
871 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
872 typeIndex->setDoesNotThrow();
873
874 llvm::Value *matchesTypeIndex =
875 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
876 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
877
878 // If the next handler is a catch-all, we're completely done.
879 if (nextIsEnd) {
880 CGF.Builder.restoreIP(savedIP);
881 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000882 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000883 // Otherwise we need to emit and continue at that block.
884 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +0000885 }
John McCall8e4c74b2011-08-11 02:22:43 +0000886}
887
888void CodeGenFunction::popCatchScope() {
889 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
890 if (catchScope.hasEHBranches())
891 emitCatchDispatchBlock(*this, catchScope);
892 EHStack.popCatch();
893}
894
John McCallb609d3f2010-07-07 06:56:46 +0000895void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000896 unsigned NumHandlers = S.getNumHandlers();
897 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
898 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +0000899
John McCall8e4c74b2011-08-11 02:22:43 +0000900 // If the catch was not required, bail out now.
901 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +0000902 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +0000903 EHStack.popCatch();
904 return;
905 }
906
907 // Emit the structure of the EH dispatch for this catch.
908 emitCatchDispatchBlock(*this, CatchScope);
909
John McCallbd309292010-07-06 01:34:17 +0000910 // Copy the handler blocks off before we pop the EH stack. Emitting
911 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000912 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +0000913 memcpy(Handlers.data(), CatchScope.begin(),
914 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +0000915
John McCallbd309292010-07-06 01:34:17 +0000916 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +0000917
John McCallbd309292010-07-06 01:34:17 +0000918 // The fall-through block.
919 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +0000920
John McCallbd309292010-07-06 01:34:17 +0000921 // We just emitted the body of the try; jump to the continue block.
922 if (HaveInsertPoint())
923 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +0000924
John McCalld8d00be2012-06-15 05:27:05 +0000925 // Determine if we need an implicit rethrow for all these catch handlers;
926 // see the comment below.
927 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +0000928 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +0000929 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
930 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +0000931
John McCall8e4c74b2011-08-11 02:22:43 +0000932 // Perversely, we emit the handlers backwards precisely because we
933 // want them to appear in source order. In all of these cases, the
934 // catch block will have exactly one predecessor, which will be a
935 // particular block in the catch dispatch. However, in the case of
936 // a catch-all, one of the dispatch blocks will branch to two
937 // different handlers, and EmitBlockAfterUses will cause the second
938 // handler to be moved before the first.
939 for (unsigned I = NumHandlers; I != 0; --I) {
940 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
941 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +0000942
John McCallbd309292010-07-06 01:34:17 +0000943 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +0000944 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +0000945
John McCallbd309292010-07-06 01:34:17 +0000946 // Enter a cleanup scope, including the catch variable and the
947 // end-catch.
948 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +0000949
John McCallbd309292010-07-06 01:34:17 +0000950 // Initialize the catch variable and set up the cleanups.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000951 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +0000952
Justin Bognerea278c32014-01-07 00:20:28 +0000953 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +0000954 RegionCounter CatchCnt = getPGORegionCounter(C);
955 CatchCnt.beginRegion(Builder);
956
John McCallbd309292010-07-06 01:34:17 +0000957 // Perform the body of the catch.
958 EmitStmt(C->getHandlerBlock());
959
John McCalld8d00be2012-06-15 05:27:05 +0000960 // [except.handle]p11:
961 // The currently handled exception is rethrown if control
962 // reaches the end of a handler of the function-try-block of a
963 // constructor or destructor.
964
965 // It is important that we only do this on fallthrough and not on
966 // return. Note that it's illegal to put a return in a
967 // constructor function-try-block's catch handler (p14), so this
968 // really only applies to destructors.
969 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +0000970 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +0000971 Builder.CreateUnreachable();
972 Builder.ClearInsertionPoint();
973 }
974
John McCallbd309292010-07-06 01:34:17 +0000975 // Fall out through the catch cleanups.
976 CatchScope.ForceCleanup();
977
978 // Branch out of the try.
979 if (HaveInsertPoint())
980 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +0000981 }
982
Justin Bogneref512b92014-01-06 22:27:43 +0000983 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +0000984 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +0000985 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +0000986}
Mike Stumpaff69af2009-12-09 03:35:49 +0000987
John McCall1e670402010-07-21 00:52:03 +0000988namespace {
John McCallcda666c2010-07-21 07:22:38 +0000989 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +0000990 llvm::Value *ForEHVar;
991 llvm::Value *EndCatchFn;
992 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
993 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
994
Craig Topper4f12f102014-03-12 06:41:41 +0000995 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +0000996 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
997 llvm::BasicBlock *CleanupContBB =
998 CGF.createBasicBlock("finally.cleanup.cont");
999
1000 llvm::Value *ShouldEndCatch =
1001 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1002 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1003 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001004 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001005 CGF.EmitBlock(CleanupContBB);
1006 }
1007 };
John McCall906da4b2010-07-21 05:47:49 +00001008
John McCallcda666c2010-07-21 07:22:38 +00001009 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001010 const Stmt *Body;
1011 llvm::Value *ForEHVar;
1012 llvm::Value *EndCatchFn;
1013 llvm::Value *RethrowFn;
1014 llvm::Value *SavedExnVar;
1015
1016 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1017 llvm::Value *EndCatchFn,
1018 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1019 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1020 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1021
Craig Topper4f12f102014-03-12 06:41:41 +00001022 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001023 // Enter a cleanup to call the end-catch function if one was provided.
1024 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001025 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1026 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001027
John McCallcebe0ca2010-08-11 00:16:14 +00001028 // Save the current cleanup destination in case there are
1029 // cleanups in the finally block.
1030 llvm::Value *SavedCleanupDest =
1031 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1032 "cleanup.dest.saved");
1033
John McCall906da4b2010-07-21 05:47:49 +00001034 // Emit the finally block.
1035 CGF.EmitStmt(Body);
1036
1037 // If the end of the finally is reachable, check whether this was
1038 // for EH. If so, rethrow.
1039 if (CGF.HaveInsertPoint()) {
1040 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1041 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1042
1043 llvm::Value *ShouldRethrow =
1044 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1045 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1046
1047 CGF.EmitBlock(RethrowBB);
1048 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001049 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1050 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001051 } else {
John McCall882987f2013-02-28 19:01:20 +00001052 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001053 }
1054 CGF.Builder.CreateUnreachable();
1055
1056 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001057
1058 // Restore the cleanup destination.
1059 CGF.Builder.CreateStore(SavedCleanupDest,
1060 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001061 }
1062
1063 // Leave the end-catch cleanup. As an optimization, pretend that
1064 // the fallthrough path was inaccessible; we've dynamically proven
1065 // that we're not in the EH case along that path.
1066 if (EndCatchFn) {
1067 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1068 CGF.PopCleanupBlock();
1069 CGF.Builder.restoreIP(SavedIP);
1070 }
1071
1072 // Now make sure we actually have an insertion point or the
1073 // cleanup gods will hate us.
1074 CGF.EnsureInsertPoint();
1075 }
1076 };
John McCall1e670402010-07-21 00:52:03 +00001077}
1078
John McCallbd309292010-07-06 01:34:17 +00001079/// Enters a finally block for an implementation using zero-cost
1080/// exceptions. This is mostly general, but hard-codes some
1081/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001082void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1083 const Stmt *body,
1084 llvm::Constant *beginCatchFn,
1085 llvm::Constant *endCatchFn,
1086 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001087 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001088 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001089 assert(rethrowFn && "rethrow function is required");
1090
1091 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001092
John McCallbd309292010-07-06 01:34:17 +00001093 // The rethrow function has one of the following two types:
1094 // void (*)()
1095 // void (*)(void*)
1096 // In the latter case we need to pass it the exception object.
1097 // But we can't use the exception slot because the @finally might
1098 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001099 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001100 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001101 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001102 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001103 if (rethrowFnTy->getNumParams())
1104 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001105
John McCallbd309292010-07-06 01:34:17 +00001106 // A finally block is a statement which must be executed on any edge
1107 // out of a given scope. Unlike a cleanup, the finally block may
1108 // contain arbitrary control flow leading out of itself. In
1109 // addition, finally blocks should always be executed, even if there
1110 // are no catch handlers higher on the stack. Therefore, we
1111 // surround the protected scope with a combination of a normal
1112 // cleanup (to catch attempts to break out of the block via normal
1113 // control flow) and an EH catch-all (semantically "outside" any try
1114 // statement to which the finally block might have been attached).
1115 // The finally block itself is generated in the context of a cleanup
1116 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001117
John McCallbd309292010-07-06 01:34:17 +00001118 // Jump destination for performing the finally block on an exception
1119 // edge. We'll never actually reach this block, so unreachable is
1120 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001121 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001122
John McCallbd309292010-07-06 01:34:17 +00001123 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001124 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1125 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001126
John McCallbd309292010-07-06 01:34:17 +00001127 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001128 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1129 ForEHVar, endCatchFn,
1130 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001131
1132 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001133 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1134 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1135 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001136}
1137
John McCall6b0feb72011-06-22 02:32:12 +00001138void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001139 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001140 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1141 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001142
1143 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001144
John McCall6b0feb72011-06-22 02:32:12 +00001145 // If there are any references to the catch-all block, emit it.
1146 if (catchBB->use_empty()) {
1147 delete catchBB;
1148 } else {
1149 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1150 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001151
Craig Topper8a13c412014-05-21 05:09:00 +00001152 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001153
John McCall6b0feb72011-06-22 02:32:12 +00001154 // If there's a begin-catch function, call it.
1155 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001156 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001157 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001158 }
1159
1160 // If we need to remember the exception pointer to rethrow later, do so.
1161 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001162 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001163 CGF.Builder.CreateStore(exn, SavedExnVar);
1164 }
1165
1166 // Tell the cleanups in the finally block that we're do this for EH.
1167 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1168
1169 // Thread a jump through the finally cleanup.
1170 CGF.EmitBranchThroughCleanup(RethrowDest);
1171
1172 CGF.Builder.restoreIP(savedIP);
1173 }
1174
1175 // Finally, leave the @finally cleanup.
1176 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001177}
1178
1179llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1180 if (TerminateLandingPad)
1181 return TerminateLandingPad;
1182
1183 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1184
1185 // This will get inserted at the end of the function.
1186 TerminateLandingPad = createBasicBlock("terminate.lpad");
1187 Builder.SetInsertPoint(TerminateLandingPad);
1188
1189 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001190 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001191 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +00001192 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +00001193 getOpaquePersonalityFn(CGM, Personality), 0);
1194 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001195
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001196 llvm::Value *Exn = 0;
1197 if (getLangOpts().CPlusPlus)
1198 Exn = Builder.CreateExtractValue(LPadInst, 0);
1199 llvm::CallInst *terminateCall =
1200 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001201 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001202 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001203
John McCallbd309292010-07-06 01:34:17 +00001204 // Restore the saved insertion state.
1205 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001206
John McCallbd309292010-07-06 01:34:17 +00001207 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001208}
Mike Stump2b488872009-12-09 22:59:31 +00001209
1210llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001211 if (TerminateHandler)
1212 return TerminateHandler;
1213
John McCallbd309292010-07-06 01:34:17 +00001214 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001215
John McCallbd309292010-07-06 01:34:17 +00001216 // Set up the terminate handler. This block is inserted at the very
1217 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001218 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001219 Builder.SetInsertPoint(TerminateHandler);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001220 llvm::Value *Exn = 0;
1221 if (getLangOpts().CPlusPlus)
1222 Exn = getExceptionFromSlot();
1223 llvm::CallInst *terminateCall =
1224 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCallc84e4e92013-06-20 21:37:43 +00001225 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001226 Builder.CreateUnreachable();
1227
John McCall21886962010-04-21 10:05:39 +00001228 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001229 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001230
Mike Stump2b488872009-12-09 22:59:31 +00001231 return TerminateHandler;
1232}
John McCallbd309292010-07-06 01:34:17 +00001233
David Chisnall9a837be2012-11-07 16:50:40 +00001234llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001235 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001236
1237 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1238
1239 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001240 EHResumeBlock = createBasicBlock("eh.resume");
1241 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001242
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001243 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001244
1245 // This can always be a call because we necessarily didn't find
1246 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001247 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001248 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001249 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001250 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001251 Builder.CreateUnreachable();
1252 Builder.restoreIP(SavedIP);
1253 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001254 }
1255
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001256 // Recreate the landingpad's return value for the 'resume' instruction.
1257 llvm::Value *Exn = getExceptionFromSlot();
1258 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001259
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001260 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001261 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001262 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1263 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1264 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1265
1266 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001267 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001268 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001269}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001270
1271void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001272 // FIXME: Implement SEH on other architectures.
1273 const llvm::Triple &T = CGM.getTarget().getTriple();
1274 if (T.getArch() != llvm::Triple::x86_64 ||
1275 !T.isKnownWindowsMSVCEnvironment()) {
1276 ErrorUnsupported(&S, "__try statement");
1277 return;
1278 }
1279
Reid Kleckneraca01db2015-02-04 22:37:07 +00001280 SEHFinallyInfo FI;
1281 EnterSEHTryStmt(S, FI);
Reid Klecknera5930002015-02-11 21:40:48 +00001282 {
Nico Weber5779f842015-02-12 23:16:11 +00001283 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001284
Reid Kleckner11c033e2015-02-12 23:40:45 +00001285 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001286 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001287 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001288
1289 if (!TryExit.getBlock()->use_empty())
1290 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1291 else
1292 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001293 }
Reid Kleckneraca01db2015-02-04 22:37:07 +00001294 ExitSEHTryStmt(S, FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001295}
1296
1297namespace {
1298struct PerformSEHFinally : EHScopeStack::Cleanup {
Reid Kleckneraca01db2015-02-04 22:37:07 +00001299 CodeGenFunction::SEHFinallyInfo *FI;
1300 PerformSEHFinally(CodeGenFunction::SEHFinallyInfo *FI) : FI(FI) {}
1301
Reid Kleckner1d59f992015-01-22 01:36:17 +00001302 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Kleckneraca01db2015-02-04 22:37:07 +00001303 // Cleanups are emitted at most twice: once for normal control flow and once
1304 // for exception control flow. Branch into the finally block, and remember
1305 // the continuation block so we can branch out later.
1306 if (!FI->FinallyBB) {
1307 FI->FinallyBB = CGF.createBasicBlock("__finally");
1308 FI->FinallyBB->insertInto(CGF.CurFn);
1309 FI->FinallyBB->moveAfter(CGF.Builder.GetInsertBlock());
1310 }
1311
1312 // Set the termination status and branch in.
1313 CGF.Builder.CreateStore(
1314 llvm::ConstantInt::get(CGF.Int8Ty, F.isForEHCleanup()),
1315 CGF.getAbnormalTerminationSlot());
1316 CGF.Builder.CreateBr(FI->FinallyBB);
1317
1318 // Create a continuation block for normal or exceptional control.
1319 if (F.isForEHCleanup()) {
1320 assert(!FI->ResumeBB && "double emission for EH");
1321 FI->ResumeBB = CGF.createBasicBlock("__finally.resume");
1322 CGF.EmitBlock(FI->ResumeBB);
1323 } else {
1324 assert(F.isForNormalCleanup() && !FI->ContBB && "double normal emission");
1325 FI->ContBB = CGF.createBasicBlock("__finally.cont");
1326 CGF.EmitBlock(FI->ContBB);
1327 // Try to keep source order.
1328 FI->ContBB->moveAfter(FI->FinallyBB);
1329 }
Reid Kleckner1d59f992015-01-22 01:36:17 +00001330 }
1331};
1332}
1333
1334/// Create a stub filter function that will ultimately hold the code of the
1335/// filter expression. The EH preparation passes in LLVM will outline the code
1336/// from the main function body into this stub.
1337llvm::Function *
1338CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1339 const SEHExceptStmt &Except) {
1340 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1341 llvm::Function *ParentFn = ParentCGF.CurFn;
1342
1343 Expr *FilterExpr = Except.getFilterExpr();
1344
1345 // Get the mangled function name.
1346 SmallString<128> Name;
1347 {
1348 llvm::raw_svector_ostream OS(Name);
1349 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1350 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1351 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1352 }
1353
1354 // Arrange a function with the declaration:
1355 // int filt(EXCEPTION_POINTERS *exception_pointers, void *frame_pointer)
1356 QualType RetTy = getContext().IntTy;
1357 FunctionArgList Args;
1358 SEHPointersDecl = ImplicitParamDecl::Create(
1359 getContext(), nullptr, FilterExpr->getLocStart(),
1360 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1361 Args.push_back(SEHPointersDecl);
1362 Args.push_back(ImplicitParamDecl::Create(
1363 getContext(), nullptr, FilterExpr->getLocStart(),
1364 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1365 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1366 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1367 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1368 llvm::Function *Fn = llvm::Function::Create(FnTy, ParentFn->getLinkage(),
1369 Name.str(), &CGM.getModule());
1370 // The filter is either in the same comdat as the function, or it's internal.
1371 if (llvm::Comdat *C = ParentFn->getComdat()) {
1372 Fn->setComdat(C);
1373 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1374 // FIXME: Unreachable with Rafael's changes?
1375 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1376 ParentFn->setComdat(C);
1377 Fn->setComdat(C);
1378 } else {
1379 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1380 }
1381
1382 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1383 FilterExpr->getLocStart(), FilterExpr->getLocStart());
1384
1385 EmitSEHExceptionCodeSave();
1386
1387 // Insert dummy allocas for every local variable in scope. We'll initialize
1388 // them and prune the unused ones after we find out which ones were
1389 // referenced.
1390 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1391 const Decl *VD = DeclPtrs.first;
1392 llvm::Value *Ptr = DeclPtrs.second;
1393 auto *ValTy = cast<llvm::PointerType>(Ptr->getType())->getElementType();
1394 LocalDeclMap[VD] = CreateTempAlloca(ValTy, Ptr->getName() + ".filt");
1395 }
1396
1397 // Emit the original filter expression, convert to i32, and return.
1398 llvm::Value *R = EmitScalarExpr(FilterExpr);
1399 R = Builder.CreateIntCast(R, CGM.IntTy,
1400 FilterExpr->getType()->isSignedIntegerType());
1401 Builder.CreateStore(R, ReturnValue);
1402
1403 FinishFunction(FilterExpr->getLocEnd());
1404
1405 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1406 const Decl *VD = DeclPtrs.first;
1407 auto *Alloca = cast<llvm::AllocaInst>(LocalDeclMap[VD]);
1408 if (Alloca->hasNUses(0)) {
1409 Alloca->eraseFromParent();
1410 continue;
1411 }
1412 ErrorUnsupported(FilterExpr,
1413 "SEH filter expression local variable capture");
1414 }
1415
1416 return Fn;
1417}
1418
1419void CodeGenFunction::EmitSEHExceptionCodeSave() {
1420 // Save the exception code in the exception slot to unify exception access in
1421 // the filter function and the landing pad.
1422 // struct EXCEPTION_POINTERS {
1423 // EXCEPTION_RECORD *ExceptionRecord;
1424 // CONTEXT *ContextRecord;
1425 // };
1426 // void *exn.slot =
1427 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1428 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1429 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1430 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1431 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
1432 llvm::Value *Rec = Builder.CreateStructGEP(Ptrs, 0);
1433 Rec = Builder.CreateLoad(Rec);
1434 llvm::Value *Code = Builder.CreateLoad(Rec);
1435 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1436 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1437 // slot an i32.
1438 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1439 Builder.CreateStore(Code, getExceptionSlot());
1440}
1441
1442llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1443 // Sema should diagnose calling this builtin outside of a filter context, but
1444 // don't crash if we screw up.
1445 if (!SEHPointersDecl)
1446 return llvm::UndefValue::get(Int8PtrTy);
1447 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1448}
1449
1450llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1451 // If we're in a landing pad or filter function, the exception slot contains
1452 // the code.
1453 assert(ExceptionSlot);
1454 llvm::Value *Code =
1455 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1456 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1457}
1458
Reid Kleckneraca01db2015-02-04 22:37:07 +00001459llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1460 // Load from the abnormal termination slot. It will be uninitialized outside
1461 // of __finally blocks, which we should warn or error on.
1462 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot());
1463 return Builder.CreateZExt(IsEH, Int32Ty);
1464}
1465
1466void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
Sean Silvab1287ee2015-02-05 01:20:26 +00001467 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001468 // Push a cleanup for __finally blocks.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001469 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, &FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001470 return;
1471 }
1472
1473 // Otherwise, we must have an __except block.
1474 SEHExceptStmt *Except = S.getExceptHandler();
1475 assert(Except);
1476 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001477
1478 // If the filter is known to evaluate to 1, then we can use the clause "catch
1479 // i8* null".
1480 llvm::Constant *C =
1481 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1482 if (C && C->isOneValue()) {
1483 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1484 return;
1485 }
1486
1487 // In general, we have to emit an outlined filter function. Use the function
1488 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001489 CodeGenFunction FilterCGF(CGM, /*suppressNewContext=*/true);
1490 llvm::Function *FilterFunc =
1491 FilterCGF.GenerateSEHFilterFunction(*this, *Except);
1492 llvm::Constant *OpaqueFunc =
1493 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1494 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1495}
1496
Reid Kleckneraca01db2015-02-04 22:37:07 +00001497void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001498 // Just pop the cleanup if it's a __finally block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001499 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001500 PopCleanupBlock();
Reid Kleckner16f9a6b2015-02-05 00:58:46 +00001501 assert(FI.ContBB && "did not emit normal cleanup");
Reid Kleckneraca01db2015-02-04 22:37:07 +00001502
1503 // Emit the code into FinallyBB.
Nico Webere68b9f32015-02-25 16:25:00 +00001504 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
Reid Kleckneraca01db2015-02-04 22:37:07 +00001505 Builder.SetInsertPoint(FI.FinallyBB);
1506 EmitStmt(Finally->getBlock());
1507
Nico Weberff62a6a2015-02-26 22:34:33 +00001508 if (HaveInsertPoint()) {
1509 if (FI.ResumeBB) {
1510 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot(),
1511 "abnormal.termination");
1512 IsEH = Builder.CreateICmpEQ(IsEH, llvm::ConstantInt::get(Int8Ty, 0));
1513 Builder.CreateCondBr(IsEH, FI.ContBB, FI.ResumeBB);
1514 } else {
1515 // There was nothing exceptional in the try body, so we only have normal
1516 // control flow.
1517 Builder.CreateBr(FI.ContBB);
1518 }
Reid Kleckneraca01db2015-02-04 22:37:07 +00001519 }
1520
Nico Webere68b9f32015-02-25 16:25:00 +00001521 Builder.restoreIP(SavedIP);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001522
Reid Kleckner1d59f992015-01-22 01:36:17 +00001523 return;
1524 }
1525
1526 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001527 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001528 assert(Except && "__try must have __finally xor __except");
1529 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1530
1531 // Don't emit the __except block if the __try block lacked invokes.
1532 // TODO: Model unwind edges from instructions, either with iload / istore or
1533 // a try body function.
1534 if (!CatchScope.hasEHBranches()) {
1535 CatchScope.clearHandlerBlocks();
1536 EHStack.popCatch();
1537 return;
1538 }
1539
1540 // The fall-through block.
1541 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1542
1543 // We just emitted the body of the __try; jump to the continue block.
1544 if (HaveInsertPoint())
1545 Builder.CreateBr(ContBB);
1546
1547 // Check if our filter function returned true.
1548 emitCatchDispatchBlock(*this, CatchScope);
1549
1550 // Grab the block before we pop the handler.
1551 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1552 EHStack.popCatch();
1553
1554 EmitBlockAfterUses(ExceptBB);
1555
1556 // Emit the __except body.
1557 EmitStmt(Except->getBlock());
1558
Reid Kleckner3a417c32015-01-30 22:16:45 +00001559 if (HaveInsertPoint())
1560 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001561
1562 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001563}
Nico Weber9b982072014-07-07 00:12:30 +00001564
1565void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001566 // If this code is reachable then emit a stop point (if generating
1567 // debug info). We have to do this ourselves because we are on the
1568 // "simple" statement path.
1569 if (HaveInsertPoint())
1570 EmitStopPoint(&S);
1571
1572 assert(!SEHTryEpilogueStack.empty() &&
1573 "sema should have rejected this __leave");
1574 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001575}