blob: f10d2e1ecc6196729999404b5495c50ef5ee6c7a [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) {
David Majnemer1f192e22015-04-01 04:45:52 +0000461 // TODO: Revisit exception specifications for the MS ABI. There is a way to
462 // encode these in an object file but MSVC doesn't do anything with it.
463 if (getTarget().getCXXABI().isMicrosoft())
464 return;
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000465 unsigned NumExceptions = Proto->getNumExceptions();
466 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
Mike Stump1d849212009-12-07 23:38:24 +0000467
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000468 for (unsigned I = 0; I != NumExceptions; ++I) {
469 QualType Ty = Proto->getExceptionType(I);
470 QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
471 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
472 /*ForEH=*/true);
473 Filter->setFilter(I, EHType);
474 }
Mike Stump1d849212009-12-07 23:38:24 +0000475 }
Mike Stump1d849212009-12-07 23:38:24 +0000476}
477
John McCall8e4c74b2011-08-11 02:22:43 +0000478/// Emit the dispatch block for a filter scope if necessary.
479static void emitFilterDispatchBlock(CodeGenFunction &CGF,
480 EHFilterScope &filterScope) {
481 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
482 if (!dispatchBlock) return;
483 if (dispatchBlock->use_empty()) {
484 delete dispatchBlock;
485 return;
486 }
487
John McCall8e4c74b2011-08-11 02:22:43 +0000488 CGF.EmitBlockAfterUses(dispatchBlock);
489
490 // If this isn't a catch-all filter, we need to check whether we got
491 // here because the filter triggered.
492 if (filterScope.getNumFilters()) {
493 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000494 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000495 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
496
497 llvm::Value *zero = CGF.Builder.getInt32(0);
498 llvm::Value *failsFilter =
Nico Weber1bebad12015-02-11 22:33:32 +0000499 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
500 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
501 CGF.getEHResumeBlock(false));
John McCall8e4c74b2011-08-11 02:22:43 +0000502
503 CGF.EmitBlock(unexpectedBB);
504 }
505
506 // Call __cxa_call_unexpected. This doesn't need to be an invoke
507 // because __cxa_call_unexpected magically filters exceptions
508 // according to the last landing pad the exception was thrown
509 // into. Seriously.
Bill Wendling79a70e42011-09-15 18:57:19 +0000510 llvm::Value *exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +0000511 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
John McCall8e4c74b2011-08-11 02:22:43 +0000512 ->setDoesNotReturn();
513 CGF.Builder.CreateUnreachable();
514}
515
Mike Stump1d849212009-12-07 23:38:24 +0000516void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000517 if (!CGM.getLangOpts().CXXExceptions)
Anders Carlsson9878f9f2010-02-06 23:59:05 +0000518 return;
519
Mike Stump1d849212009-12-07 23:38:24 +0000520 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
Craig Topper8a13c412014-05-21 05:09:00 +0000521 if (!FD) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000522 // Check if CapturedDecl is nothrow and pop terminate scope for it.
523 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
524 if (CD->isNothrow())
525 EHStack.popTerminate();
526 }
Mike Stump1d849212009-12-07 23:38:24 +0000527 return;
Alexey Bataev9959db52014-05-06 10:08:46 +0000528 }
Mike Stump1d849212009-12-07 23:38:24 +0000529 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
Craig Topper8a13c412014-05-21 05:09:00 +0000530 if (!Proto)
Mike Stump1d849212009-12-07 23:38:24 +0000531 return;
532
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000533 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
534 if (isNoexceptExceptionSpec(EST)) {
535 if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
536 EHStack.popTerminate();
537 }
538 } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
David Majnemer1f192e22015-04-01 04:45:52 +0000539 // TODO: Revisit exception specifications for the MS ABI. There is a way to
540 // encode these in an object file but MSVC doesn't do anything with it.
541 if (getTarget().getCXXABI().isMicrosoft())
542 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000543 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
544 emitFilterDispatchBlock(*this, filterScope);
Sebastian Redl0b94c9f2011-03-15 18:42:48 +0000545 EHStack.popFilter();
546 }
Mike Stump1d849212009-12-07 23:38:24 +0000547}
548
Mike Stump58ef18b2009-11-20 23:44:51 +0000549void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
John McCallb609d3f2010-07-07 06:56:46 +0000550 EnterCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000551 EmitStmt(S.getTryBlock());
John McCallb609d3f2010-07-07 06:56:46 +0000552 ExitCXXTryStmt(S);
John McCallb81884d2010-02-19 09:25:03 +0000553}
554
John McCallb609d3f2010-07-07 06:56:46 +0000555void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000556 unsigned NumHandlers = S.getNumHandlers();
557 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
John McCallb81884d2010-02-19 09:25:03 +0000558
John McCallbd309292010-07-06 01:34:17 +0000559 for (unsigned I = 0; I != NumHandlers; ++I) {
560 const CXXCatchStmt *C = S.getHandler(I);
John McCallb81884d2010-02-19 09:25:03 +0000561
John McCallbd309292010-07-06 01:34:17 +0000562 llvm::BasicBlock *Handler = createBasicBlock("catch");
563 if (C->getExceptionDecl()) {
564 // FIXME: Dropping the reference type on the type into makes it
565 // impossible to correctly implement catch-by-reference
566 // semantics for pointers. Unfortunately, this is what all
567 // existing compilers do, and it's not clear that the standard
568 // personality routine is capable of doing this right. See C++ DR 388:
569 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
David Majnemer571162a2014-10-12 06:58:22 +0000570 Qualifiers CaughtTypeQuals;
571 QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
572 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
John McCall2ca705e2010-07-24 00:37:23 +0000573
Rafael Espindolabb9e7a32014-06-04 18:51:46 +0000574 llvm::Constant *TypeInfo = nullptr;
John McCall2ca705e2010-07-24 00:37:23 +0000575 if (CaughtType->isObjCObjectPointerType())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +0000576 TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
John McCall2ca705e2010-07-24 00:37:23 +0000577 else
David Majnemer5f0dd612015-03-17 20:35:05 +0000578 TypeInfo =
David Majnemer37b417f2015-03-29 21:55:10 +0000579 CGM.getAddrOfCXXCatchHandlerType(CaughtType, C->getCaughtType());
John McCallbd309292010-07-06 01:34:17 +0000580 CatchScope->setHandler(I, TypeInfo, Handler);
581 } else {
582 // No exception decl indicates '...', a catch-all.
583 CatchScope->setCatchAllHandler(I, Handler);
584 }
585 }
John McCallbd309292010-07-06 01:34:17 +0000586}
587
John McCall8e4c74b2011-08-11 02:22:43 +0000588llvm::BasicBlock *
589CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
590 // The dispatch block for the end of the scope chain is a block that
591 // just resumes unwinding.
592 if (si == EHStack.stable_end())
David Chisnall9a837be2012-11-07 16:50:40 +0000593 return getEHResumeBlock(true);
John McCall8e4c74b2011-08-11 02:22:43 +0000594
595 // Otherwise, we should look at the actual scope.
596 EHScope &scope = *EHStack.find(si);
597
598 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
599 if (!dispatchBlock) {
600 switch (scope.getKind()) {
601 case EHScope::Catch: {
602 // Apply a special case to a single catch-all.
603 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
604 if (catchScope.getNumHandlers() == 1 &&
605 catchScope.getHandler(0).isCatchAll()) {
606 dispatchBlock = catchScope.getHandler(0).Block;
607
608 // Otherwise, make a dispatch block.
609 } else {
610 dispatchBlock = createBasicBlock("catch.dispatch");
611 }
612 break;
613 }
614
615 case EHScope::Cleanup:
616 dispatchBlock = createBasicBlock("ehcleanup");
617 break;
618
619 case EHScope::Filter:
620 dispatchBlock = createBasicBlock("filter.dispatch");
621 break;
622
623 case EHScope::Terminate:
624 dispatchBlock = getTerminateHandler();
625 break;
626 }
627 scope.setCachedEHDispatchBlock(dispatchBlock);
628 }
629 return dispatchBlock;
630}
631
John McCallbd309292010-07-06 01:34:17 +0000632/// Check whether this is a non-EH scope, i.e. a scope which doesn't
633/// affect exception handling. Currently, the only non-EH scopes are
634/// normal-only cleanup scopes.
635static bool isNonEHScope(const EHScope &S) {
John McCall2b7fc382010-07-13 20:32:21 +0000636 switch (S.getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000637 case EHScope::Cleanup:
638 return !cast<EHCleanupScope>(S).isEHCleanup();
John McCall2b7fc382010-07-13 20:32:21 +0000639 case EHScope::Filter:
640 case EHScope::Catch:
641 case EHScope::Terminate:
642 return false;
643 }
644
David Blaikiee4d798f2012-01-20 21:50:17 +0000645 llvm_unreachable("Invalid EHScope Kind!");
John McCallbd309292010-07-06 01:34:17 +0000646}
647
648llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
649 assert(EHStack.requiresLandingPad());
650 assert(!EHStack.empty());
651
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000652 // If exceptions are disabled, there are usually no landingpads. However, when
653 // SEH is enabled, functions using SEH still get landingpads.
654 const LangOptions &LO = CGM.getLangOpts();
655 if (!LO.Exceptions) {
656 if (!LO.Borland && !LO.MicrosoftExt)
657 return nullptr;
Reid Klecknere7b3f7c2015-02-11 00:00:21 +0000658 if (!currentFunctionUsesSEHTry())
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000659 return nullptr;
660 }
John McCall2b7fc382010-07-13 20:32:21 +0000661
John McCallbd309292010-07-06 01:34:17 +0000662 // Check the innermost scope for a cached landing pad. If this is
663 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
664 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
665 if (LP) return LP;
666
667 // Build the landing pad for this scope.
668 LP = EmitLandingPad();
669 assert(LP);
670
671 // Cache the landing pad on the innermost scope. If this is a
672 // non-EH scope, cache the landing pad on the enclosing scope, too.
673 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
674 ir->setCachedLandingPad(LP);
675 if (!isNonEHScope(*ir)) break;
676 }
677
678 return LP;
679}
680
681llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
682 assert(EHStack.requiresLandingPad());
683
John McCall8e4c74b2011-08-11 02:22:43 +0000684 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
685 switch (innermostEHScope.getKind()) {
686 case EHScope::Terminate:
687 return getTerminateLandingPad();
John McCallbd309292010-07-06 01:34:17 +0000688
John McCall8e4c74b2011-08-11 02:22:43 +0000689 case EHScope::Catch:
690 case EHScope::Cleanup:
691 case EHScope::Filter:
692 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
693 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000694 }
695
696 // Save the current IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000697 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
Adrian Prantl95b24e92015-02-03 20:00:54 +0000698 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
John McCallbd309292010-07-06 01:34:17 +0000699
Reid Klecknerdeeddec2015-02-05 18:56:03 +0000700 const EHPersonality &personality = EHPersonality::get(*this);
John McCall36ea3722010-07-17 00:43:08 +0000701
John McCallbd309292010-07-06 01:34:17 +0000702 // Create and configure the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000703 llvm::BasicBlock *lpad = createBasicBlock("lpad");
704 EmitBlock(lpad);
John McCallbd309292010-07-06 01:34:17 +0000705
Bill Wendlingf0724e82011-09-19 20:31:14 +0000706 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +0000707 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +0000708 getOpaquePersonalityFn(CGM, personality), 0);
709
710 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
711 Builder.CreateStore(LPadExn, getExceptionSlot());
712 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
713 Builder.CreateStore(LPadSel, getEHSelectorSlot());
714
John McCallbd309292010-07-06 01:34:17 +0000715 // Save the exception pointer. It's safe to use a single exception
716 // pointer per function because EH cleanups can never have nested
717 // try/catches.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000718 // Build the landingpad instruction.
John McCallbd309292010-07-06 01:34:17 +0000719
720 // Accumulate all the handlers in scope.
John McCall8e4c74b2011-08-11 02:22:43 +0000721 bool hasCatchAll = false;
722 bool hasCleanup = false;
723 bool hasFilter = false;
724 SmallVector<llvm::Value*, 4> filterTypes;
725 llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
Nico Webere68b9f32015-02-25 16:25:00 +0000726 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
727 ++I) {
John McCallbd309292010-07-06 01:34:17 +0000728
729 switch (I->getKind()) {
John McCallcda666c2010-07-21 07:22:38 +0000730 case EHScope::Cleanup:
John McCall8e4c74b2011-08-11 02:22:43 +0000731 // If we have a cleanup, remember that.
732 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
John McCall2b7fc382010-07-13 20:32:21 +0000733 continue;
734
John McCallbd309292010-07-06 01:34:17 +0000735 case EHScope::Filter: {
736 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
John McCall8e4c74b2011-08-11 02:22:43 +0000737 assert(!hasCatchAll && "EH filter reached after catch-all");
John McCallbd309292010-07-06 01:34:17 +0000738
Bill Wendlingf0724e82011-09-19 20:31:14 +0000739 // Filter scopes get added to the landingpad in weird ways.
John McCall8e4c74b2011-08-11 02:22:43 +0000740 EHFilterScope &filter = cast<EHFilterScope>(*I);
741 hasFilter = true;
John McCallbd309292010-07-06 01:34:17 +0000742
Bill Wendling8c4b7162011-09-22 20:32:54 +0000743 // Add all the filter values.
744 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
745 filterTypes.push_back(filter.getFilter(i));
John McCallbd309292010-07-06 01:34:17 +0000746 goto done;
747 }
748
749 case EHScope::Terminate:
750 // Terminate scopes are basically catch-alls.
John McCall8e4c74b2011-08-11 02:22:43 +0000751 assert(!hasCatchAll);
752 hasCatchAll = true;
John McCallbd309292010-07-06 01:34:17 +0000753 goto done;
754
755 case EHScope::Catch:
756 break;
757 }
758
John McCall8e4c74b2011-08-11 02:22:43 +0000759 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
760 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
761 EHCatchScope::Handler handler = catchScope.getHandler(hi);
John McCallbd309292010-07-06 01:34:17 +0000762
John McCall8e4c74b2011-08-11 02:22:43 +0000763 // If this is a catch-all, register that and abort.
764 if (!handler.Type) {
765 assert(!hasCatchAll);
766 hasCatchAll = true;
767 goto done;
John McCallbd309292010-07-06 01:34:17 +0000768 }
769
770 // Check whether we already have a handler for this type.
David Blaikie82e95a32014-11-19 07:49:47 +0000771 if (catchTypes.insert(handler.Type).second)
Bill Wendlingf0724e82011-09-19 20:31:14 +0000772 // If not, add it directly to the landingpad.
773 LPadInst->addClause(handler.Type);
John McCallbd309292010-07-06 01:34:17 +0000774 }
John McCallbd309292010-07-06 01:34:17 +0000775 }
776
777 done:
Bill Wendlingf0724e82011-09-19 20:31:14 +0000778 // If we have a catch-all, add null to the landingpad.
John McCall8e4c74b2011-08-11 02:22:43 +0000779 assert(!(hasCatchAll && hasFilter));
780 if (hasCatchAll) {
Bill Wendlingf0724e82011-09-19 20:31:14 +0000781 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +0000782
783 // If we have an EH filter, we need to add those handlers in the
Bill Wendlingf0724e82011-09-19 20:31:14 +0000784 // right place in the landingpad, which is to say, at the end.
John McCall8e4c74b2011-08-11 02:22:43 +0000785 } else if (hasFilter) {
Bill Wendling58e58fe2011-09-19 22:08:36 +0000786 // Create a filter expression: a constant array indicating which filter
787 // types there are. The personality routine only lands here if the filter
788 // doesn't match.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000789 SmallVector<llvm::Constant*, 8> Filters;
Bill Wendlingf0724e82011-09-19 20:31:14 +0000790 llvm::ArrayType *AType =
791 llvm::ArrayType::get(!filterTypes.empty() ?
792 filterTypes[0]->getType() : Int8PtrTy,
793 filterTypes.size());
794
795 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
796 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
797 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
798 LPadInst->addClause(FilterArray);
John McCallbd309292010-07-06 01:34:17 +0000799
800 // Also check whether we need a cleanup.
Bill Wendlingf0724e82011-09-19 20:31:14 +0000801 if (hasCleanup)
802 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000803
804 // Otherwise, signal that we at least have cleanups.
Logan Chiene9c8ccb2014-07-01 11:47:10 +0000805 } else if (hasCleanup) {
806 LPadInst->setCleanup(true);
John McCallbd309292010-07-06 01:34:17 +0000807 }
808
Bill Wendlingf0724e82011-09-19 20:31:14 +0000809 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
810 "landingpad instruction has no clauses!");
John McCallbd309292010-07-06 01:34:17 +0000811
812 // Tell the backend how to generate the landing pad.
John McCall8e4c74b2011-08-11 02:22:43 +0000813 Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
John McCallbd309292010-07-06 01:34:17 +0000814
815 // Restore the old IR generation state.
John McCall8e4c74b2011-08-11 02:22:43 +0000816 Builder.restoreIP(savedIP);
John McCallbd309292010-07-06 01:34:17 +0000817
John McCall8e4c74b2011-08-11 02:22:43 +0000818 return lpad;
John McCallbd309292010-07-06 01:34:17 +0000819}
820
John McCall8e4c74b2011-08-11 02:22:43 +0000821/// Emit the structure of the dispatch block for the given catch scope.
822/// It is an invariant that the dispatch block already exists.
823static void emitCatchDispatchBlock(CodeGenFunction &CGF,
824 EHCatchScope &catchScope) {
825 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
826 assert(dispatchBlock);
827
828 // If there's only a single catch-all, getEHDispatchBlock returned
829 // that catch-all as the dispatch block.
830 if (catchScope.getNumHandlers() == 1 &&
831 catchScope.getHandler(0).isCatchAll()) {
832 assert(dispatchBlock == catchScope.getHandler(0).Block);
833 return;
834 }
835
836 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
837 CGF.EmitBlockAfterUses(dispatchBlock);
838
839 // Select the right handler.
840 llvm::Value *llvm_eh_typeid_for =
841 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
842
843 // Load the selector value.
Bill Wendling79a70e42011-09-15 18:57:19 +0000844 llvm::Value *selector = CGF.getSelectorFromSlot();
John McCall8e4c74b2011-08-11 02:22:43 +0000845
846 // Test against each of the exception types we claim to catch.
847 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
848 assert(i < e && "ran off end of handlers!");
849 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
850
851 llvm::Value *typeValue = handler.Type;
852 assert(typeValue && "fell into catch-all case!");
853 typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
854
855 // Figure out the next block.
856 bool nextIsEnd;
857 llvm::BasicBlock *nextBlock;
858
859 // If this is the last handler, we're at the end, and the next
860 // block is the block for the enclosing EH scope.
861 if (i + 1 == e) {
862 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
863 nextIsEnd = true;
864
865 // If the next handler is a catch-all, we're at the end, and the
866 // next block is that handler.
867 } else if (catchScope.getHandler(i+1).isCatchAll()) {
868 nextBlock = catchScope.getHandler(i+1).Block;
869 nextIsEnd = true;
870
871 // Otherwise, we're not at the end and we need a new block.
872 } else {
873 nextBlock = CGF.createBasicBlock("catch.fallthrough");
874 nextIsEnd = false;
875 }
876
877 // Figure out the catch type's index in the LSDA's type table.
878 llvm::CallInst *typeIndex =
879 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
880 typeIndex->setDoesNotThrow();
881
882 llvm::Value *matchesTypeIndex =
883 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
884 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
885
886 // If the next handler is a catch-all, we're completely done.
887 if (nextIsEnd) {
888 CGF.Builder.restoreIP(savedIP);
889 return;
John McCall8e4c74b2011-08-11 02:22:43 +0000890 }
Ahmed Charles289896d2012-02-19 11:57:29 +0000891 // Otherwise we need to emit and continue at that block.
892 CGF.EmitBlock(nextBlock);
John McCall8e4c74b2011-08-11 02:22:43 +0000893 }
John McCall8e4c74b2011-08-11 02:22:43 +0000894}
895
896void CodeGenFunction::popCatchScope() {
897 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
898 if (catchScope.hasEHBranches())
899 emitCatchDispatchBlock(*this, catchScope);
900 EHStack.popCatch();
901}
902
John McCallb609d3f2010-07-07 06:56:46 +0000903void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
John McCallbd309292010-07-06 01:34:17 +0000904 unsigned NumHandlers = S.getNumHandlers();
905 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
906 assert(CatchScope.getNumHandlers() == NumHandlers);
Mike Stump58ef18b2009-11-20 23:44:51 +0000907
John McCall8e4c74b2011-08-11 02:22:43 +0000908 // If the catch was not required, bail out now.
909 if (!CatchScope.hasEHBranches()) {
Kostya Serebryanyba4aced2014-01-09 09:22:32 +0000910 CatchScope.clearHandlerBlocks();
John McCall8e4c74b2011-08-11 02:22:43 +0000911 EHStack.popCatch();
912 return;
913 }
914
915 // Emit the structure of the EH dispatch for this catch.
916 emitCatchDispatchBlock(*this, CatchScope);
917
John McCallbd309292010-07-06 01:34:17 +0000918 // Copy the handler blocks off before we pop the EH stack. Emitting
919 // the handlers might scribble on this memory.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000920 SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
John McCallbd309292010-07-06 01:34:17 +0000921 memcpy(Handlers.data(), CatchScope.begin(),
922 NumHandlers * sizeof(EHCatchScope::Handler));
John McCall8e4c74b2011-08-11 02:22:43 +0000923
John McCallbd309292010-07-06 01:34:17 +0000924 EHStack.popCatch();
Mike Stump58ef18b2009-11-20 23:44:51 +0000925
John McCallbd309292010-07-06 01:34:17 +0000926 // The fall-through block.
927 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
Mike Stump58ef18b2009-11-20 23:44:51 +0000928
John McCallbd309292010-07-06 01:34:17 +0000929 // We just emitted the body of the try; jump to the continue block.
930 if (HaveInsertPoint())
931 Builder.CreateBr(ContBB);
Mike Stump97329152009-12-02 19:53:57 +0000932
John McCalld8d00be2012-06-15 05:27:05 +0000933 // Determine if we need an implicit rethrow for all these catch handlers;
934 // see the comment below.
935 bool doImplicitRethrow = false;
John McCallb609d3f2010-07-07 06:56:46 +0000936 if (IsFnTryBlock)
John McCalld8d00be2012-06-15 05:27:05 +0000937 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
938 isa<CXXConstructorDecl>(CurCodeDecl);
John McCallb609d3f2010-07-07 06:56:46 +0000939
John McCall8e4c74b2011-08-11 02:22:43 +0000940 // Perversely, we emit the handlers backwards precisely because we
941 // want them to appear in source order. In all of these cases, the
942 // catch block will have exactly one predecessor, which will be a
943 // particular block in the catch dispatch. However, in the case of
944 // a catch-all, one of the dispatch blocks will branch to two
945 // different handlers, and EmitBlockAfterUses will cause the second
946 // handler to be moved before the first.
947 for (unsigned I = NumHandlers; I != 0; --I) {
948 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
949 EmitBlockAfterUses(CatchBlock);
Mike Stump75546b82009-12-10 00:06:18 +0000950
John McCallbd309292010-07-06 01:34:17 +0000951 // Catch the exception if this isn't a catch-all.
John McCall8e4c74b2011-08-11 02:22:43 +0000952 const CXXCatchStmt *C = S.getHandler(I-1);
Mike Stump58ef18b2009-11-20 23:44:51 +0000953
John McCallbd309292010-07-06 01:34:17 +0000954 // Enter a cleanup scope, including the catch variable and the
955 // end-catch.
956 RunCleanupsScope CatchScope(*this);
Mike Stump58ef18b2009-11-20 23:44:51 +0000957
John McCallbd309292010-07-06 01:34:17 +0000958 // Initialize the catch variable and set up the cleanups.
Reid Klecknerfff8e7f2015-03-03 19:21:04 +0000959 CGM.getCXXABI().emitBeginCatch(*this, C);
John McCallbd309292010-07-06 01:34:17 +0000960
Justin Bognerea278c32014-01-07 00:20:28 +0000961 // Emit the PGO counter increment.
Justin Bogneref512b92014-01-06 22:27:43 +0000962 RegionCounter CatchCnt = getPGORegionCounter(C);
963 CatchCnt.beginRegion(Builder);
964
John McCallbd309292010-07-06 01:34:17 +0000965 // Perform the body of the catch.
966 EmitStmt(C->getHandlerBlock());
967
John McCalld8d00be2012-06-15 05:27:05 +0000968 // [except.handle]p11:
969 // The currently handled exception is rethrown if control
970 // reaches the end of a handler of the function-try-block of a
971 // constructor or destructor.
972
973 // It is important that we only do this on fallthrough and not on
974 // return. Note that it's illegal to put a return in a
975 // constructor function-try-block's catch handler (p14), so this
976 // really only applies to destructors.
977 if (doImplicitRethrow && HaveInsertPoint()) {
David Majnemer442d0a22014-11-25 07:20:20 +0000978 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
John McCalld8d00be2012-06-15 05:27:05 +0000979 Builder.CreateUnreachable();
980 Builder.ClearInsertionPoint();
981 }
982
John McCallbd309292010-07-06 01:34:17 +0000983 // Fall out through the catch cleanups.
984 CatchScope.ForceCleanup();
985
986 // Branch out of the try.
987 if (HaveInsertPoint())
988 Builder.CreateBr(ContBB);
Mike Stump58ef18b2009-11-20 23:44:51 +0000989 }
990
Justin Bogneref512b92014-01-06 22:27:43 +0000991 RegionCounter ContCnt = getPGORegionCounter(&S);
John McCallbd309292010-07-06 01:34:17 +0000992 EmitBlock(ContBB);
Justin Bogneref512b92014-01-06 22:27:43 +0000993 ContCnt.beginRegion(Builder);
Mike Stump58ef18b2009-11-20 23:44:51 +0000994}
Mike Stumpaff69af2009-12-09 03:35:49 +0000995
John McCall1e670402010-07-21 00:52:03 +0000996namespace {
John McCallcda666c2010-07-21 07:22:38 +0000997 struct CallEndCatchForFinally : EHScopeStack::Cleanup {
John McCall1e670402010-07-21 00:52:03 +0000998 llvm::Value *ForEHVar;
999 llvm::Value *EndCatchFn;
1000 CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1001 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1002
Craig Topper4f12f102014-03-12 06:41:41 +00001003 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e670402010-07-21 00:52:03 +00001004 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1005 llvm::BasicBlock *CleanupContBB =
1006 CGF.createBasicBlock("finally.cleanup.cont");
1007
1008 llvm::Value *ShouldEndCatch =
1009 CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
1010 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1011 CGF.EmitBlock(EndCatchBB);
John McCall882987f2013-02-28 19:01:20 +00001012 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
John McCall1e670402010-07-21 00:52:03 +00001013 CGF.EmitBlock(CleanupContBB);
1014 }
1015 };
John McCall906da4b2010-07-21 05:47:49 +00001016
John McCallcda666c2010-07-21 07:22:38 +00001017 struct PerformFinally : EHScopeStack::Cleanup {
John McCall906da4b2010-07-21 05:47:49 +00001018 const Stmt *Body;
1019 llvm::Value *ForEHVar;
1020 llvm::Value *EndCatchFn;
1021 llvm::Value *RethrowFn;
1022 llvm::Value *SavedExnVar;
1023
1024 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1025 llvm::Value *EndCatchFn,
1026 llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1027 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1028 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1029
Craig Topper4f12f102014-03-12 06:41:41 +00001030 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall906da4b2010-07-21 05:47:49 +00001031 // Enter a cleanup to call the end-catch function if one was provided.
1032 if (EndCatchFn)
John McCallcda666c2010-07-21 07:22:38 +00001033 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1034 ForEHVar, EndCatchFn);
John McCall906da4b2010-07-21 05:47:49 +00001035
John McCallcebe0ca2010-08-11 00:16:14 +00001036 // Save the current cleanup destination in case there are
1037 // cleanups in the finally block.
1038 llvm::Value *SavedCleanupDest =
1039 CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
1040 "cleanup.dest.saved");
1041
John McCall906da4b2010-07-21 05:47:49 +00001042 // Emit the finally block.
1043 CGF.EmitStmt(Body);
1044
1045 // If the end of the finally is reachable, check whether this was
1046 // for EH. If so, rethrow.
1047 if (CGF.HaveInsertPoint()) {
1048 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1049 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1050
1051 llvm::Value *ShouldRethrow =
1052 CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
1053 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1054
1055 CGF.EmitBlock(RethrowBB);
1056 if (SavedExnVar) {
John McCall882987f2013-02-28 19:01:20 +00001057 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1058 CGF.Builder.CreateLoad(SavedExnVar));
John McCall906da4b2010-07-21 05:47:49 +00001059 } else {
John McCall882987f2013-02-28 19:01:20 +00001060 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
John McCall906da4b2010-07-21 05:47:49 +00001061 }
1062 CGF.Builder.CreateUnreachable();
1063
1064 CGF.EmitBlock(ContBB);
John McCallcebe0ca2010-08-11 00:16:14 +00001065
1066 // Restore the cleanup destination.
1067 CGF.Builder.CreateStore(SavedCleanupDest,
1068 CGF.getNormalCleanupDestSlot());
John McCall906da4b2010-07-21 05:47:49 +00001069 }
1070
1071 // Leave the end-catch cleanup. As an optimization, pretend that
1072 // the fallthrough path was inaccessible; we've dynamically proven
1073 // that we're not in the EH case along that path.
1074 if (EndCatchFn) {
1075 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1076 CGF.PopCleanupBlock();
1077 CGF.Builder.restoreIP(SavedIP);
1078 }
1079
1080 // Now make sure we actually have an insertion point or the
1081 // cleanup gods will hate us.
1082 CGF.EnsureInsertPoint();
1083 }
1084 };
John McCall1e670402010-07-21 00:52:03 +00001085}
1086
John McCallbd309292010-07-06 01:34:17 +00001087/// Enters a finally block for an implementation using zero-cost
1088/// exceptions. This is mostly general, but hard-codes some
1089/// language/ABI-specific behavior in the catch-all sections.
John McCall6b0feb72011-06-22 02:32:12 +00001090void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
1091 const Stmt *body,
1092 llvm::Constant *beginCatchFn,
1093 llvm::Constant *endCatchFn,
1094 llvm::Constant *rethrowFn) {
Craig Topper8a13c412014-05-21 05:09:00 +00001095 assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
John McCallbd309292010-07-06 01:34:17 +00001096 "begin/end catch functions not paired");
John McCall6b0feb72011-06-22 02:32:12 +00001097 assert(rethrowFn && "rethrow function is required");
1098
1099 BeginCatchFn = beginCatchFn;
Mike Stumpaff69af2009-12-09 03:35:49 +00001100
John McCallbd309292010-07-06 01:34:17 +00001101 // The rethrow function has one of the following two types:
1102 // void (*)()
1103 // void (*)(void*)
1104 // In the latter case we need to pass it the exception object.
1105 // But we can't use the exception slot because the @finally might
1106 // have a landing pad (which would overwrite the exception slot).
Chris Lattner2192fe52011-07-18 04:24:23 +00001107 llvm::FunctionType *rethrowFnTy =
John McCallbd309292010-07-06 01:34:17 +00001108 cast<llvm::FunctionType>(
John McCall6b0feb72011-06-22 02:32:12 +00001109 cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
Craig Topper8a13c412014-05-21 05:09:00 +00001110 SavedExnVar = nullptr;
John McCall6b0feb72011-06-22 02:32:12 +00001111 if (rethrowFnTy->getNumParams())
1112 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
Mike Stumpaff69af2009-12-09 03:35:49 +00001113
John McCallbd309292010-07-06 01:34:17 +00001114 // A finally block is a statement which must be executed on any edge
1115 // out of a given scope. Unlike a cleanup, the finally block may
1116 // contain arbitrary control flow leading out of itself. In
1117 // addition, finally blocks should always be executed, even if there
1118 // are no catch handlers higher on the stack. Therefore, we
1119 // surround the protected scope with a combination of a normal
1120 // cleanup (to catch attempts to break out of the block via normal
1121 // control flow) and an EH catch-all (semantically "outside" any try
1122 // statement to which the finally block might have been attached).
1123 // The finally block itself is generated in the context of a cleanup
1124 // which conditionally leaves the catch-all.
John McCall21886962010-04-21 10:05:39 +00001125
John McCallbd309292010-07-06 01:34:17 +00001126 // Jump destination for performing the finally block on an exception
1127 // edge. We'll never actually reach this block, so unreachable is
1128 // fine.
John McCall6b0feb72011-06-22 02:32:12 +00001129 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
John McCall21886962010-04-21 10:05:39 +00001130
John McCallbd309292010-07-06 01:34:17 +00001131 // Whether the finally block is being executed for EH purposes.
John McCall6b0feb72011-06-22 02:32:12 +00001132 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1133 CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
Mike Stumpaff69af2009-12-09 03:35:49 +00001134
John McCallbd309292010-07-06 01:34:17 +00001135 // Enter a normal cleanup which will perform the @finally block.
John McCall6b0feb72011-06-22 02:32:12 +00001136 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1137 ForEHVar, endCatchFn,
1138 rethrowFn, SavedExnVar);
John McCallbd309292010-07-06 01:34:17 +00001139
1140 // Enter a catch-all scope.
John McCall6b0feb72011-06-22 02:32:12 +00001141 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1142 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1143 catchScope->setCatchAllHandler(0, catchBB);
John McCallbd309292010-07-06 01:34:17 +00001144}
1145
John McCall6b0feb72011-06-22 02:32:12 +00001146void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
John McCallbd309292010-07-06 01:34:17 +00001147 // Leave the finally catch-all.
John McCall6b0feb72011-06-22 02:32:12 +00001148 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1149 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
John McCall8e4c74b2011-08-11 02:22:43 +00001150
1151 CGF.popCatchScope();
John McCallbd309292010-07-06 01:34:17 +00001152
John McCall6b0feb72011-06-22 02:32:12 +00001153 // If there are any references to the catch-all block, emit it.
1154 if (catchBB->use_empty()) {
1155 delete catchBB;
1156 } else {
1157 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1158 CGF.EmitBlock(catchBB);
John McCallbd309292010-07-06 01:34:17 +00001159
Craig Topper8a13c412014-05-21 05:09:00 +00001160 llvm::Value *exn = nullptr;
John McCallbd309292010-07-06 01:34:17 +00001161
John McCall6b0feb72011-06-22 02:32:12 +00001162 // If there's a begin-catch function, call it.
1163 if (BeginCatchFn) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001164 exn = CGF.getExceptionFromSlot();
John McCall882987f2013-02-28 19:01:20 +00001165 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
John McCall6b0feb72011-06-22 02:32:12 +00001166 }
1167
1168 // If we need to remember the exception pointer to rethrow later, do so.
1169 if (SavedExnVar) {
Bill Wendling79a70e42011-09-15 18:57:19 +00001170 if (!exn) exn = CGF.getExceptionFromSlot();
John McCall6b0feb72011-06-22 02:32:12 +00001171 CGF.Builder.CreateStore(exn, SavedExnVar);
1172 }
1173
1174 // Tell the cleanups in the finally block that we're do this for EH.
1175 CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
1176
1177 // Thread a jump through the finally cleanup.
1178 CGF.EmitBranchThroughCleanup(RethrowDest);
1179
1180 CGF.Builder.restoreIP(savedIP);
1181 }
1182
1183 // Finally, leave the @finally cleanup.
1184 CGF.PopCleanupBlock();
John McCallbd309292010-07-06 01:34:17 +00001185}
1186
1187llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1188 if (TerminateLandingPad)
1189 return TerminateLandingPad;
1190
1191 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1192
1193 // This will get inserted at the end of the function.
1194 TerminateLandingPad = createBasicBlock("terminate.lpad");
1195 Builder.SetInsertPoint(TerminateLandingPad);
1196
1197 // Tell the backend that this is a landing pad.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001198 const EHPersonality &Personality = EHPersonality::get(*this);
Bill Wendlingf0724e82011-09-19 20:31:14 +00001199 llvm::LandingPadInst *LPadInst =
Reid Kleckneree7cf842014-12-01 22:02:27 +00001200 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, nullptr),
Bill Wendlingf0724e82011-09-19 20:31:14 +00001201 getOpaquePersonalityFn(CGM, Personality), 0);
1202 LPadInst->addClause(getCatchAllValue(*this));
John McCallbd309292010-07-06 01:34:17 +00001203
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001204 llvm::Value *Exn = 0;
1205 if (getLangOpts().CPlusPlus)
1206 Exn = Builder.CreateExtractValue(LPadInst, 0);
1207 llvm::CallInst *terminateCall =
1208 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCalle142ad52013-02-12 03:51:46 +00001209 terminateCall->setDoesNotReturn();
John McCallad7c5c12011-02-08 08:22:06 +00001210 Builder.CreateUnreachable();
Mike Stumpaff69af2009-12-09 03:35:49 +00001211
John McCallbd309292010-07-06 01:34:17 +00001212 // Restore the saved insertion state.
1213 Builder.restoreIP(SavedIP);
John McCalldac3ea62010-04-30 00:06:43 +00001214
John McCallbd309292010-07-06 01:34:17 +00001215 return TerminateLandingPad;
Mike Stumpaff69af2009-12-09 03:35:49 +00001216}
Mike Stump2b488872009-12-09 22:59:31 +00001217
1218llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
Mike Stumpf5cbb082009-12-10 00:02:42 +00001219 if (TerminateHandler)
1220 return TerminateHandler;
1221
John McCallbd309292010-07-06 01:34:17 +00001222 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Mike Stump25b20fc2009-12-09 23:31:35 +00001223
John McCallbd309292010-07-06 01:34:17 +00001224 // Set up the terminate handler. This block is inserted at the very
1225 // end of the function by FinishFunction.
Mike Stumpf5cbb082009-12-10 00:02:42 +00001226 TerminateHandler = createBasicBlock("terminate.handler");
John McCallbd309292010-07-06 01:34:17 +00001227 Builder.SetInsertPoint(TerminateHandler);
Reid Klecknerfff8e7f2015-03-03 19:21:04 +00001228 llvm::Value *Exn = 0;
1229 if (getLangOpts().CPlusPlus)
1230 Exn = getExceptionFromSlot();
1231 llvm::CallInst *terminateCall =
1232 CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
John McCallc84e4e92013-06-20 21:37:43 +00001233 terminateCall->setDoesNotReturn();
Mike Stump2b488872009-12-09 22:59:31 +00001234 Builder.CreateUnreachable();
1235
John McCall21886962010-04-21 10:05:39 +00001236 // Restore the saved insertion state.
John McCallbd309292010-07-06 01:34:17 +00001237 Builder.restoreIP(SavedIP);
Mike Stump25b20fc2009-12-09 23:31:35 +00001238
Mike Stump2b488872009-12-09 22:59:31 +00001239 return TerminateHandler;
1240}
John McCallbd309292010-07-06 01:34:17 +00001241
David Chisnall9a837be2012-11-07 16:50:40 +00001242llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
John McCall8e4c74b2011-08-11 02:22:43 +00001243 if (EHResumeBlock) return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001244
1245 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1246
1247 // We emit a jump to a notional label at the outermost unwind state.
John McCall8e4c74b2011-08-11 02:22:43 +00001248 EHResumeBlock = createBasicBlock("eh.resume");
1249 Builder.SetInsertPoint(EHResumeBlock);
John McCallad5d61e2010-07-23 21:56:41 +00001250
Reid Klecknerdeeddec2015-02-05 18:56:03 +00001251 const EHPersonality &Personality = EHPersonality::get(*this);
John McCallad5d61e2010-07-23 21:56:41 +00001252
1253 // This can always be a call because we necessarily didn't find
1254 // anything on the EH stack which needs our help.
Benjamin Kramer793bd552012-02-08 12:41:24 +00001255 const char *RethrowName = Personality.CatchallRethrowFn;
Craig Topper8a13c412014-05-21 05:09:00 +00001256 if (RethrowName != nullptr && !isCleanup) {
John McCall882987f2013-02-28 19:01:20 +00001257 EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
Nico Weberff62a6a2015-02-26 22:34:33 +00001258 getExceptionFromSlot())->setDoesNotReturn();
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001259 Builder.CreateUnreachable();
1260 Builder.restoreIP(SavedIP);
1261 return EHResumeBlock;
John McCall9b382dd2011-05-28 21:13:02 +00001262 }
1263
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001264 // Recreate the landingpad's return value for the 'resume' instruction.
1265 llvm::Value *Exn = getExceptionFromSlot();
1266 llvm::Value *Sel = getSelectorFromSlot();
John McCallad5d61e2010-07-23 21:56:41 +00001267
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001268 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
Reid Kleckneree7cf842014-12-01 22:02:27 +00001269 Sel->getType(), nullptr);
Logan Chiene9c8ccb2014-07-01 11:47:10 +00001270 llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1271 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1272 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1273
1274 Builder.CreateResume(LPadVal);
John McCallad5d61e2010-07-23 21:56:41 +00001275 Builder.restoreIP(SavedIP);
John McCall8e4c74b2011-08-11 02:22:43 +00001276 return EHResumeBlock;
John McCallad5d61e2010-07-23 21:56:41 +00001277}
Reid Kleckner543a16c2013-09-16 21:46:30 +00001278
1279void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001280 // FIXME: Implement SEH on other architectures.
1281 const llvm::Triple &T = CGM.getTarget().getTriple();
1282 if (T.getArch() != llvm::Triple::x86_64 ||
1283 !T.isKnownWindowsMSVCEnvironment()) {
1284 ErrorUnsupported(&S, "__try statement");
1285 return;
1286 }
1287
Reid Kleckneraca01db2015-02-04 22:37:07 +00001288 SEHFinallyInfo FI;
1289 EnterSEHTryStmt(S, FI);
Reid Klecknera5930002015-02-11 21:40:48 +00001290 {
Nico Weber5779f842015-02-12 23:16:11 +00001291 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
Nico Weber5779f842015-02-12 23:16:11 +00001292
Reid Kleckner11c033e2015-02-12 23:40:45 +00001293 SEHTryEpilogueStack.push_back(&TryExit);
Reid Klecknera5930002015-02-11 21:40:48 +00001294 EmitStmt(S.getTryBlock());
Reid Kleckner11c033e2015-02-12 23:40:45 +00001295 SEHTryEpilogueStack.pop_back();
Nico Weber5779f842015-02-12 23:16:11 +00001296
1297 if (!TryExit.getBlock()->use_empty())
1298 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1299 else
1300 delete TryExit.getBlock();
Reid Klecknera5930002015-02-11 21:40:48 +00001301 }
Reid Kleckneraca01db2015-02-04 22:37:07 +00001302 ExitSEHTryStmt(S, FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001303}
1304
1305namespace {
1306struct PerformSEHFinally : EHScopeStack::Cleanup {
Reid Kleckneraca01db2015-02-04 22:37:07 +00001307 CodeGenFunction::SEHFinallyInfo *FI;
1308 PerformSEHFinally(CodeGenFunction::SEHFinallyInfo *FI) : FI(FI) {}
1309
Reid Kleckner1d59f992015-01-22 01:36:17 +00001310 void Emit(CodeGenFunction &CGF, Flags F) override {
Reid Kleckneraca01db2015-02-04 22:37:07 +00001311 // Cleanups are emitted at most twice: once for normal control flow and once
1312 // for exception control flow. Branch into the finally block, and remember
1313 // the continuation block so we can branch out later.
1314 if (!FI->FinallyBB) {
1315 FI->FinallyBB = CGF.createBasicBlock("__finally");
1316 FI->FinallyBB->insertInto(CGF.CurFn);
1317 FI->FinallyBB->moveAfter(CGF.Builder.GetInsertBlock());
1318 }
1319
1320 // Set the termination status and branch in.
1321 CGF.Builder.CreateStore(
1322 llvm::ConstantInt::get(CGF.Int8Ty, F.isForEHCleanup()),
1323 CGF.getAbnormalTerminationSlot());
1324 CGF.Builder.CreateBr(FI->FinallyBB);
1325
1326 // Create a continuation block for normal or exceptional control.
1327 if (F.isForEHCleanup()) {
1328 assert(!FI->ResumeBB && "double emission for EH");
1329 FI->ResumeBB = CGF.createBasicBlock("__finally.resume");
1330 CGF.EmitBlock(FI->ResumeBB);
1331 } else {
1332 assert(F.isForNormalCleanup() && !FI->ContBB && "double normal emission");
1333 FI->ContBB = CGF.createBasicBlock("__finally.cont");
1334 CGF.EmitBlock(FI->ContBB);
1335 // Try to keep source order.
1336 FI->ContBB->moveAfter(FI->FinallyBB);
1337 }
Reid Kleckner1d59f992015-01-22 01:36:17 +00001338 }
1339};
1340}
1341
1342/// Create a stub filter function that will ultimately hold the code of the
1343/// filter expression. The EH preparation passes in LLVM will outline the code
1344/// from the main function body into this stub.
1345llvm::Function *
1346CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
1347 const SEHExceptStmt &Except) {
1348 const Decl *ParentCodeDecl = ParentCGF.CurCodeDecl;
1349 llvm::Function *ParentFn = ParentCGF.CurFn;
1350
1351 Expr *FilterExpr = Except.getFilterExpr();
1352
1353 // Get the mangled function name.
1354 SmallString<128> Name;
1355 {
1356 llvm::raw_svector_ostream OS(Name);
1357 const NamedDecl *Parent = dyn_cast_or_null<NamedDecl>(ParentCodeDecl);
1358 assert(Parent && "FIXME: handle unnamed decls (lambdas, blocks) with SEH");
1359 CGM.getCXXABI().getMangleContext().mangleSEHFilterExpression(Parent, OS);
1360 }
1361
1362 // Arrange a function with the declaration:
1363 // int filt(EXCEPTION_POINTERS *exception_pointers, void *frame_pointer)
1364 QualType RetTy = getContext().IntTy;
1365 FunctionArgList Args;
1366 SEHPointersDecl = ImplicitParamDecl::Create(
1367 getContext(), nullptr, FilterExpr->getLocStart(),
1368 &getContext().Idents.get("exception_pointers"), getContext().VoidPtrTy);
1369 Args.push_back(SEHPointersDecl);
1370 Args.push_back(ImplicitParamDecl::Create(
1371 getContext(), nullptr, FilterExpr->getLocStart(),
1372 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy));
1373 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1374 RetTy, Args, FunctionType::ExtInfo(), /*isVariadic=*/false);
1375 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1376 llvm::Function *Fn = llvm::Function::Create(FnTy, ParentFn->getLinkage(),
1377 Name.str(), &CGM.getModule());
1378 // The filter is either in the same comdat as the function, or it's internal.
1379 if (llvm::Comdat *C = ParentFn->getComdat()) {
1380 Fn->setComdat(C);
1381 } else if (ParentFn->hasWeakLinkage() || ParentFn->hasLinkOnceLinkage()) {
1382 // FIXME: Unreachable with Rafael's changes?
1383 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(ParentFn->getName());
1384 ParentFn->setComdat(C);
1385 Fn->setComdat(C);
1386 } else {
1387 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1388 }
1389
1390 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1391 FilterExpr->getLocStart(), FilterExpr->getLocStart());
1392
1393 EmitSEHExceptionCodeSave();
1394
1395 // Insert dummy allocas for every local variable in scope. We'll initialize
1396 // them and prune the unused ones after we find out which ones were
1397 // referenced.
1398 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1399 const Decl *VD = DeclPtrs.first;
1400 llvm::Value *Ptr = DeclPtrs.second;
1401 auto *ValTy = cast<llvm::PointerType>(Ptr->getType())->getElementType();
1402 LocalDeclMap[VD] = CreateTempAlloca(ValTy, Ptr->getName() + ".filt");
1403 }
1404
1405 // Emit the original filter expression, convert to i32, and return.
1406 llvm::Value *R = EmitScalarExpr(FilterExpr);
1407 R = Builder.CreateIntCast(R, CGM.IntTy,
1408 FilterExpr->getType()->isSignedIntegerType());
1409 Builder.CreateStore(R, ReturnValue);
1410
1411 FinishFunction(FilterExpr->getLocEnd());
1412
1413 for (const auto &DeclPtrs : ParentCGF.LocalDeclMap) {
1414 const Decl *VD = DeclPtrs.first;
1415 auto *Alloca = cast<llvm::AllocaInst>(LocalDeclMap[VD]);
1416 if (Alloca->hasNUses(0)) {
1417 Alloca->eraseFromParent();
1418 continue;
1419 }
1420 ErrorUnsupported(FilterExpr,
1421 "SEH filter expression local variable capture");
1422 }
1423
1424 return Fn;
1425}
1426
1427void CodeGenFunction::EmitSEHExceptionCodeSave() {
1428 // Save the exception code in the exception slot to unify exception access in
1429 // the filter function and the landing pad.
1430 // struct EXCEPTION_POINTERS {
1431 // EXCEPTION_RECORD *ExceptionRecord;
1432 // CONTEXT *ContextRecord;
1433 // };
1434 // void *exn.slot =
1435 // (void *)(uintptr_t)exception_pointers->ExceptionRecord->ExceptionCode;
1436 llvm::Value *Ptrs = Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1437 llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1438 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy, nullptr);
1439 Ptrs = Builder.CreateBitCast(Ptrs, PtrsTy->getPointerTo());
1440 llvm::Value *Rec = Builder.CreateStructGEP(Ptrs, 0);
1441 Rec = Builder.CreateLoad(Rec);
1442 llvm::Value *Code = Builder.CreateLoad(Rec);
1443 Code = Builder.CreateZExt(Code, CGM.IntPtrTy);
1444 // FIXME: Change landing pads to produce {i32, i32} and make the exception
1445 // slot an i32.
1446 Code = Builder.CreateIntToPtr(Code, CGM.VoidPtrTy);
1447 Builder.CreateStore(Code, getExceptionSlot());
1448}
1449
1450llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
1451 // Sema should diagnose calling this builtin outside of a filter context, but
1452 // don't crash if we screw up.
1453 if (!SEHPointersDecl)
1454 return llvm::UndefValue::get(Int8PtrTy);
1455 return Builder.CreateLoad(GetAddrOfLocalVar(SEHPointersDecl));
1456}
1457
1458llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
1459 // If we're in a landing pad or filter function, the exception slot contains
1460 // the code.
1461 assert(ExceptionSlot);
1462 llvm::Value *Code =
1463 Builder.CreatePtrToInt(getExceptionFromSlot(), CGM.IntPtrTy);
1464 return Builder.CreateTrunc(Code, CGM.Int32Ty);
1465}
1466
Reid Kleckneraca01db2015-02-04 22:37:07 +00001467llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
1468 // Load from the abnormal termination slot. It will be uninitialized outside
1469 // of __finally blocks, which we should warn or error on.
1470 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot());
1471 return Builder.CreateZExt(IsEH, Int32Ty);
1472}
1473
1474void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
Sean Silvab1287ee2015-02-05 01:20:26 +00001475 if (S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001476 // Push a cleanup for __finally blocks.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001477 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, &FI);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001478 return;
1479 }
1480
1481 // Otherwise, we must have an __except block.
1482 SEHExceptStmt *Except = S.getExceptHandler();
1483 assert(Except);
1484 EHCatchScope *CatchScope = EHStack.pushCatch(1);
Reid Kleckner2a2e1562015-01-22 02:25:56 +00001485
1486 // If the filter is known to evaluate to 1, then we can use the clause "catch
1487 // i8* null".
1488 llvm::Constant *C =
1489 CGM.EmitConstantExpr(Except->getFilterExpr(), getContext().IntTy, this);
1490 if (C && C->isOneValue()) {
1491 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1492 return;
1493 }
1494
1495 // In general, we have to emit an outlined filter function. Use the function
1496 // in place of the RTTI typeinfo global that C++ EH uses.
Reid Kleckner1d59f992015-01-22 01:36:17 +00001497 CodeGenFunction FilterCGF(CGM, /*suppressNewContext=*/true);
1498 llvm::Function *FilterFunc =
1499 FilterCGF.GenerateSEHFilterFunction(*this, *Except);
1500 llvm::Constant *OpaqueFunc =
1501 llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1502 CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except"));
1503}
1504
Reid Kleckneraca01db2015-02-04 22:37:07 +00001505void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S, SEHFinallyInfo &FI) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001506 // Just pop the cleanup if it's a __finally block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001507 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
Reid Kleckner1d59f992015-01-22 01:36:17 +00001508 PopCleanupBlock();
Reid Kleckner16f9a6b2015-02-05 00:58:46 +00001509 assert(FI.ContBB && "did not emit normal cleanup");
Reid Kleckneraca01db2015-02-04 22:37:07 +00001510
1511 // Emit the code into FinallyBB.
Nico Webere68b9f32015-02-25 16:25:00 +00001512 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
Reid Kleckneraca01db2015-02-04 22:37:07 +00001513 Builder.SetInsertPoint(FI.FinallyBB);
1514 EmitStmt(Finally->getBlock());
1515
Nico Weberff62a6a2015-02-26 22:34:33 +00001516 if (HaveInsertPoint()) {
1517 if (FI.ResumeBB) {
1518 llvm::Value *IsEH = Builder.CreateLoad(getAbnormalTerminationSlot(),
1519 "abnormal.termination");
1520 IsEH = Builder.CreateICmpEQ(IsEH, llvm::ConstantInt::get(Int8Ty, 0));
1521 Builder.CreateCondBr(IsEH, FI.ContBB, FI.ResumeBB);
1522 } else {
1523 // There was nothing exceptional in the try body, so we only have normal
1524 // control flow.
1525 Builder.CreateBr(FI.ContBB);
1526 }
Reid Kleckneraca01db2015-02-04 22:37:07 +00001527 }
1528
Nico Webere68b9f32015-02-25 16:25:00 +00001529 Builder.restoreIP(SavedIP);
Reid Kleckneraca01db2015-02-04 22:37:07 +00001530
Reid Kleckner1d59f992015-01-22 01:36:17 +00001531 return;
1532 }
1533
1534 // Otherwise, we must have an __except block.
Reid Kleckneraca01db2015-02-04 22:37:07 +00001535 const SEHExceptStmt *Except = S.getExceptHandler();
Reid Kleckner1d59f992015-01-22 01:36:17 +00001536 assert(Except && "__try must have __finally xor __except");
1537 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1538
1539 // Don't emit the __except block if the __try block lacked invokes.
1540 // TODO: Model unwind edges from instructions, either with iload / istore or
1541 // a try body function.
1542 if (!CatchScope.hasEHBranches()) {
1543 CatchScope.clearHandlerBlocks();
1544 EHStack.popCatch();
1545 return;
1546 }
1547
1548 // The fall-through block.
1549 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1550
1551 // We just emitted the body of the __try; jump to the continue block.
1552 if (HaveInsertPoint())
1553 Builder.CreateBr(ContBB);
1554
1555 // Check if our filter function returned true.
1556 emitCatchDispatchBlock(*this, CatchScope);
1557
1558 // Grab the block before we pop the handler.
1559 llvm::BasicBlock *ExceptBB = CatchScope.getHandler(0).Block;
1560 EHStack.popCatch();
1561
1562 EmitBlockAfterUses(ExceptBB);
1563
1564 // Emit the __except body.
1565 EmitStmt(Except->getBlock());
1566
Reid Kleckner3a417c32015-01-30 22:16:45 +00001567 if (HaveInsertPoint())
1568 Builder.CreateBr(ContBB);
Reid Kleckner1d59f992015-01-22 01:36:17 +00001569
1570 EmitBlock(ContBB);
Reid Kleckner543a16c2013-09-16 21:46:30 +00001571}
Nico Weber9b982072014-07-07 00:12:30 +00001572
1573void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
Nico Weber5779f842015-02-12 23:16:11 +00001574 // If this code is reachable then emit a stop point (if generating
1575 // debug info). We have to do this ourselves because we are on the
1576 // "simple" statement path.
1577 if (HaveInsertPoint())
1578 EmitStopPoint(&S);
1579
1580 assert(!SEHTryEpilogueStack.empty() &&
1581 "sema should have rejected this __leave");
1582 EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
Nico Weber9b982072014-07-07 00:12:30 +00001583}